文章介绍结构一览
一、使用maven创建web项目
1、新建maven项目
2、修改jre版本
3、修改Project Facts,生成WebContent文件夾
4、将WebContent下的两个文件复制到src/main/webapp下,删掉WebContent
5、修改Deployment Assembly
6、测试
二、mybatis访问mysql
1、数据库准备
2、修改pom.xml
3、创建实体类
4、创建访问接口
5、添加映射文件
6、添加MyBatisCfg.xml配置文件,注册mapper,实体类别名
7、添加MyBatisUtil工具类
8、创建Impl类继承接口
9、测试
10、添加log4j2配置(控制台看到向数据库发送的SQL请求,及数据库向程序响应)
三、Spring与Mybatis初级整合
1、修改pom.xml
2、添加ApplicationContext.xml,修改MyBatisCfg.xml
3、测试
四、Spring与Mybatis整合升级
1、修改ApplicationContext.xml,引入自动扫描,弃用MyBasticCfg.xml
2、修改测试类,测试
Demo下载:spring_mybatis_1.rar
项目结构如下:
正式开始!!!
一、使用maven创建web项目
1、新建项目
填写完成后,创建成功。
2、修改jre版本
properties->java build path,把默认的1.5版本remove,
然后Add Library-> JRE Library System->选择 Workspace default JRE
选择完成后,可以在Library列表看到这个
3、修改Project Facts
properties->Project Facts,修改java版本,然后把Dynamic Web Module前面打上勾
Apply后,查看项目结构可以看到多了个WebContent
4、将WebContent下的两个文件复制到src/main/webapp下,然后将WebContent整个删掉
5、修改Deployment Assembly,只留下下面几个
新增/src/main/webapp,步骤Add->Floder->src->main->webapp->finish
6、测试,在src/main/webapp下,新建一个index.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body>hello </body> </html>
运行tomcat,访问:http://localhost:8888/spring_mybatis_1/,页面显示“hello”
二、mybatis访问mysql
1、数据库准备,新建数据表tb_book,添加测试数据
2、修改pom.xml文件,新增下面代码
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </dependencies>
完整pom.xml文件,
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lmei</groupId> <artifactId>spring_mybatis_1</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </dependencies> </project>
3、创建实体类,Book(id,bookName)
package com.lmei.entity; public class Book { private int id; private String bookName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } }
4、创建访问接口
package com.lmei.dao; import java.util.List; import com.lmei.entity.*; public interface BookDaoI { public List<Book> getAllBook(); }
5、添加映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.lmei.dao.BookDaoI"> <select id="getAllBook" parameterType="int" resultType="Book"> select * from tb_book </select> </mapper>
6、新建MyBatisCfg.xml文件,用于配置MyBatis运行环境
新增db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull username=root password=123456
新增MyBatisCfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 指定数据库连接信息的位置 --> <properties resource="db.properties"></properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> </configuration>
在MyBatisCfg.xml加入“com.lmei.entity"别名配置,注册mapper
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 指定数据库连接信息的位置 --> <properties resource="db.properties"></properties> <!--com.lmei.entity下的所有类定义别名 --> <typeAliases> <package name="com.lmei.entity"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <mappers> <!--注册BookMapper映射--> <mapper resource="com/lmei/mapper/BookMapper.xml" /> </mappers> </configuration>
注:关于实体类别名可参考:mybatis学习笔记(四)-- 为实体类定义别名两种方法(基于xml映射)
7、新增MyBatisUtil工具类
package com.lmei.util; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { /** * 获取SqlSessionFactory * @return SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactory() { String resource = "MyBatisCfg.xml"; InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); return factory; } /** * 获取SqlSession * @return SqlSession */ public static SqlSession getSqlSession() { return getSqlSessionFactory().openSession(); } /** * 获取SqlSession * @param isAutoCommit * true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务 * false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务 * @return SqlSession */ public static SqlSession getSqlSession(boolean isAutoCommit) { return getSqlSessionFactory().openSession(isAutoCommit); } }
8、创建Impl类实现接口
新建BookImpl类,继承BookDaoI接口
package com.lmei.dao.impl; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.lmei.entity.*; import com.lmei.util.MyBatisUtil; import com.lmei.dao.*;; public class BookImpl implements BookDaoI { @Override public List<Book> getAllBook() { //获得会话对象 SqlSession session= MyBatisUtil.getSqlSession(true); try { BookDaoI bookDao = session.getMapper(BookDaoI.class); return bookDao.getAllBook(); } finally { session.close(); } } }
9、测试
添加测试类TestBookImpl.java
package com.lmei.test; import static org.junit.Assert.*; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import com.lmei.dao.impl.*; import com.lmei.entity.*; import com.lmei.dao.*; public class TestBookImpl { static BookDaoI bookDao; @BeforeClass public static void beforeClass() { bookDao = new BookImpl(); } @Test public void testGetAllBookTypes() { List<Book> books = bookDao.getAllBook(); for (Book book : books) { System.out.println(book.getBookName()); } assertNotNull(books); } }
项目右键->Run As->JUnit Test,控制台输出
输出成,但 出现错误:“ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.”
新增log4j2.xml配置文件,文件位置如下:
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="off" monitorInterval="1800"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> </Appenders> <Loggers> <Root level="debug"> <AppenderRef ref="Console" /> </Root> </Loggers> </Configuration>
添加完成后,重新运行,可以在控制台看到向数据库发送的SQL请求,及数据库向程序响应的结果
但还有一个警告!
“Description Resource Path Location Type
No grammar constraints (DTD or XML schema) detected for the document. log4j2.xml /spring_mybatis_1/src/main/resources line 1 XML Problem”
修改log4j2.xml如下,即可
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd"> <Configuration status="off" monitorInterval="1800"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> </Appenders> <Loggers> <Root level="debug"> <AppenderRef ref="Console" /> </Root> </Loggers> </Configuration>
三、Spring与MyBatis初级整合
1、修改pom.xml文件,新增下面这些包
<!-- 添加Spring-core包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-context包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-tx包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-jdbc包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 为了方便进行单元测试,添加spring-test包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--添加spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--添加aspectjweaver包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> <!-- 添加mybatis与Spring整合的核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
完整pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lmei</groupId> <artifactId>spring_mybatis_1</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> <!-- 添加Spring-core包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-context包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-tx包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 添加spring-jdbc包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- 为了方便进行单元测试,添加spring-test包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--添加spring-web包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!--添加aspectjweaver包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> <!-- 添加mybatis与Spring整合的核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> </dependencies> </project>
初次配置时,运行测试,报错“java.lang.AbstractMethodError: org.mybatis.spring.transaction.SpringManagedTransaction.getTimeout()Ljava/lang/Integer;”
完整的错误信息:
java.lang.AbstractMethodError: org.mybatis.spring.transaction.SpringManagedTransaction.getTimeout()Ljava/lang/Integer; at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:85) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:62) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:358) at com.sun.proxy.$Proxy7.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53) at com.sun.proxy.$Proxy8.getAllBook(Unknown Source) at com.lmei.test.TestMyBatisSpring.test(TestMyBatisSpring.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
一开始的mybatis-spring配置的版本是1.2.2,发生版本不兼容的问题,将其改为1.3.0就没问题了,上面pom.xml配置信息是1.3.0
2、添加ApplicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!-- 引入db.properties属性文件 --> <context:property-placeholder location="classpath:db.properties" /> <!--定义一个jdbc数据源,创建一个驱动管理数据源的bean --> <bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <!--创建一个sql会话工厂bean,指定数据源 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="jdbcDataSource" /><!-- 指定数据源 --> <property name="configLocation" value="classpath:MyBatisCfg.xml"></property> <!-- 指定配置文件 --> </bean> <!--创建一个bookDao --> <bean id="bookDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <!--指定映射文件 --> <property name="mapperInterface" value="com.lmei.dao.BookDaoI"></property> <!-- 指定sql会话工厂 --> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> </beans>
测试时报错“java.sql.SQLException: Access denied for user 'USER'@'localhost' (using password: YES)”
出错在这句配置: <property name="username" value="${username}" />
发生属性冲突,将配置文件里的username换成其他的名字即可, 如jdbc.username
原因: (参考来自http://blog.csdn.net/hy245120020/article/details/51821950)
username在windows下默认取值为电脑的账号,一般电脑账号为administrator,
如果你的电脑账号是自己设置的那就为你设置的账号,数据库连接时数据库中没有administrator用户或者跟你电脑账