mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

时间:2021-06-22 09:07:56

文章介绍结构一览

一、使用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

项目结构如下:

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

正式开始!!!

一、使用maven创建web项目

1、新建项目

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

填写完成后,创建成功。

2、修改jre版本

properties->java build path,把默认的1.5版本remove,

然后Add Library-> JRE Library System->选择 Workspace default JRE

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

选择完成后,可以在Library列表看到这个

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

3、修改Project Facts

properties->Project Facts,修改java版本,然后把Dynamic Web Module前面打上勾

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

Apply后,查看项目结构可以看到多了个WebContent

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

4、将WebContent下的两个文件复制到src/main/webapp下,然后将WebContent整个删掉

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

5、修改Deployment Assembly,只留下下面几个

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

新增/src/main/webapp,步骤Add->Floder->src->main->webapp->finish

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

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学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

二、mybatis访问mysql

1、数据库准备,新建数据表tb_book,添加测试数据

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

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>

pom.xml

3、创建实体类,Book(id,bookName)

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

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、创建访问接口

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

package com.lmei.dao;

import java.util.List;
import com.lmei.entity.*; public interface BookDaoI {
public List<Book> getAllBook();
}

5、添加映射文件

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

<?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运行环境

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

新增db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username=root
password=

新增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工具类

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

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类实现接口

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

新建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

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

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,控制台输出

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

输出成,但 出现错误:“ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.”

新增log4j2.xml配置文件,文件位置如下:

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

<?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>

log4j2.xml

添加完成后,重新运行,可以在控制台看到向数据库发送的SQL请求,及数据库向程序响应的结果

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

但还有一个警告!

“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>

pom.xml

初次配置时,运行测试,报错“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:)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:)
at java.lang.reflect.Method.invoke(Method.java:)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:)
at com.sun.proxy.$Proxy7.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:)
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:)
at com.sun.proxy.$Proxy8.getAllBook(Unknown Source)
at com.lmei.test.TestMyBatisSpring.test(TestMyBatisSpring.java:)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:)
at java.lang.reflect.Method.invoke(Method.java:)
at org.junit.runners.model.FrameworkMethod$.runReflectiveCall(FrameworkMethod.java:)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:)
at org.junit.runners.ParentRunner$.run(ParentRunner.java:)
at org.junit.runners.ParentRunner$.schedule(ParentRunner.java:)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:)
at org.junit.runners.ParentRunner.access$(ParentRunner.java:)
at org.junit.runners.ParentRunner$.evaluate(ParentRunner.java:)
at org.junit.runners.ParentRunner.run(ParentRunner.java:)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:)

错误信息

一开始的mybatis-spring配置的版本是1.2.2,发生版本不兼容的问题,将其改为1.3.0就没问题了,上面pom.xml配置信息是1.3.0

2、添加ApplicationContext.xml配置

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

<?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用户或者跟你电脑账号一样名字的用户,就会报错。

一般为了避免和Windows基本配置冲突,数据库连接名常常写的较长如{jdbc.username}这样就可以唯一识别用户名而不会和Windows冲突。

将db.properties文件中的进行修改,如下(其他并不会冲突,但为了统一都改了)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=

将上面的ApplicationContext.xml进行修改

<bean id="jdbcDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

修改后的完整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="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.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>

ApplicationContext.xml

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> <!--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="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments> -->
<mappers>
<!--注册BookMapper映射-->
<mapper resource="com/lmei/mapper/BookMapper.xml" />
</mappers>
</configuration>

3、编写测试类TestMyBatisSpring

package com.lmei.test;

import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.lmei.dao.BookDaoI;
import com.lmei.entity.Book; public class TestMyBatisSpring {
@Test
public void test() {
//初始化容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml"); BookDaoI bookDao = ctx.getBean("bookDao",BookDaoI.class); List<Book> books = bookDao.getAllBook();
for (Book book : books) {
System.out.println(book.getBookName());
}
assertNotNull(books);
}
}

项目右键->Run As->JUnit Test,控制台输出

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

四、Spring与MyBatis整合升级

1、修改ApplicationContext.xml,弃用MyBatisCfg.xml

“三、Spring与MyBatis初级整合”中ApplicationContext.xml需要用到MyBatisCfg.xml

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="jdbcDataSource" /><property name="configLocation" value="classpath:MyBatisCfg.xml"></property> <!--指定配置文件-->
</bean>

MyBatisCfg.xml中,需要注册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> <!--com.lmei.entity下的所有类定义别名 -->
<typeAliases>
<package name="com.lmei.entity"/>
</typeAliases> <mappers>
<!--注册BookMapper映射-->
<mapper resource="com/lmei/mapper/BookMapper.xml" />
</mappers>
</configuration>

引入自动扫描,将ApplicationContext.xml进行修改,原MyBatisCfg.xml弃用,将其配置转移到ApplicationContext.xml中

下面代码注释部分为原来配置,优化sql会话工厂bean,新增的自动扫描接口

<?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="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.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> --> <!--创建一个sql会话工厂bean,指定数据源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定数据源 -->
<property name="dataSource" ref="jdbcDataSource" />
<!--类型别名包,默认引入com.lmei.entity下的所有类 -->
<property name="typeAliasesPackage" value="com.lmei.entity"></property>
<!--指定sql映射xml文件的路径 -->
<property name="mapperLocations"
value="classpath:com/lmei/mapper/*Mapper.xml"></property>
</bean> <!--自动扫描映射接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定sql会话工厂,在上面配置过的 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 指定基础包,即自动扫描com.lmei.dao这个包下的所有接口类 -->
<property name="basePackage" value="com.lmei.dao"></property>
</bean> <!--下面的配置暂时未使用 -->
<context:component-scan base-package="com.lmei">
</context:component-scan>
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>

2、修改测试类TestMyBasticSpring.java

package com.lmei.test;

import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.lmei.dao.BookDaoI;
import com.lmei.entity.Book; public class TestMyBatisSpring {
@Test
public void test() {
//初始化容器
ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext.xml");
//获得bean
/* BookDaoI bookDao = ctx.getBean("bookDao",BookDaoI.class);*/
BookDaoI bookDao = ctx.getBean(BookDaoI.class);
//访问数据库
List<Book> books = bookDao.getAllBook();
for (Book book : books) {
System.out.println(book.getBookName());
}
assertNotNull(books);
}
}

项目右键->Run As->Junit Test

mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)

以上学习参考资料:

http://www.cnblogs.com/best/p/5638827.html

http://www.cnblogs.com/xdp-gacl/p/4271627.html

问题解决参考:

http://blog.csdn.net/xwin1989/article/details/6754790

http://blog.csdn.net/hy245120020/article/details/51821950

@_@)... 未完待续...接下来学习将在下一篇介绍

mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下)