MyBatis与Spring的整合(Eclipse版本和IDEA版本)
Posted nuist__NJUPT
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis与Spring的整合(Eclipse版本和IDEA版本)相关的知识,希望对你有一定的参考价值。
MyBatis与Spring的整合
通过Spring和MyBatis的整合,开发者只需要进行业务处理,不需要再进行SqlSession对象的创建,数据库事务处理等繁琐的代码,MyBatis整合Spring后方便了数据库访问操作,提高了开发效率。
下面通过Eclipse编写一个实例演示MyBatis与Spring整合。
1-创建一个名为ch6ss的Web应用,导入相关jar包到lib目录下。(jar包共包括:MyBatis框架所需的核心包和依赖包,Spring框架所需的jar包,MyBatis和Spring整合的中间jar包,数据库驱动jar包,DBCP数据源jar包和连接池jar包)
2-在mysql数据库中创建数据库spring,并创建用户表user,字符串编码方式设置为utf8,需要在该表中录入几行数据,自行录入即可
录入四行数据信息
3-在src目录下创建包com.po,在该包中创建持久化类MyUser
public class MyUser {
private Integer uid ;
private String uname, usex ;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUsex() {
return usex;
}
public void setUsex(String usex) {
this.usex = usex;
}
public String toString() {
return "MyUser " + "uid = " + uid + " uname = " + uname + " usex = " + usex ;
}
}
4-在src目录下创建一个名为com.mybatis的包,在该包中创建SQL映射文件UserMapper.xml和MyBatis的核心配置文件mybatis-config.xml
UserMapper.xml的代码如下:
<?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.dao.UserDao">
<!-- 根据uid查询一个用户信息 -->
<select id = "selectUserById" parameterType = "Integer"
resultType = "com.po.MyUser">
select * from user where uid = #{uid}
</select>
<!-- 查询所有用户信息 -->
<select id = "selectAllUser" resultType = "com.po.MyUser">
select * from user
</select>
<!-- 添加一个用户 -->
<insert id = "addUser" parameterType = "com.po.MyUser">
insert into user (uid,uname,usex) values(#{uid}, #{uname}, #{usex})
</insert>
<!-- 修改一个用户 -->
<update id = "updateUser" parameterType = "com.po.MyUser">
update user set uname = #{uname}, usex = #{usex} where uid = #{uid}
</update>
<!-- 删除一个用户信息 -->
<delete id = "deleteUser" parameterType = "Integer">
delete from user where uid = #{uid}
</delete>
</mapper>
mybatis-config.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>
<!-- 告诉MyBatis去那哪里寻找映射文件 -->
<mappers>
<mapper resource = "com/mybatis/UserMapper.xml" />
</mappers>
</configuration>
5-在src目录下创建一个名为com.dao的包,在该包中创建数据访问接口UserDao,并将接口使用@Mapper注解为Mapper,接口中的方法与SQL映射文件一致。
@Mapper注解:使用Spring自动扫描MyBatis的接口并装配,Spring将指定包中所有被@Mapper注解过的接口自动装配为MyBatis的映射接口
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import com.po.MyUser;
@Repository("userDao")
@Mapper
/**
* 使用Spring自动扫描MyBatis的接口并装配
* Spring将指定包中所有被@Mapper注解标注的接口自动装配为MyBatis的映射接口
* @author nuist__NJUPT
*
*/
public interface UserDao {
//接口方法对应SQL映射文件UerMapper.xml中的id
public MyUser selectUserById(Integer uid) ;
public List<MyUser> selectAllUser() ;
public int addUser(MyUser user) ;
public int updateUser(MyUser user) ;
public int deleteUser(Integer uid) ;
}
6-在src目录下创建日志文件log4j.properties,MyBatis默认使用log4j输出日志信息,如果开发者需要在控制台输出SQL语句,那么需要在classpath路径下配置日志文件
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
7-创建控制层,在src目录下创建一个名为com.controller的包,在该包中创建UserController类,在该类中调用数据访问接口的方法
/**
* 从该类中可以看出,开发者只需要进行业务处理,不需要进行SqlSession的创建,数据库事务处理等繁琐的代码
* 因此MyBatis和Spring整合方便了数据库的访问,提高了开发效率
*/
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.dao.UserDao;
import com.po.MyUser;
@Controller("userController")
public class UserController {
//在该类中调用数据访问接口中的方法
@Autowired
private UserDao userDao ;
public void test() {
//查询一个用户
MyUser auser = userDao.selectUserById(1) ;
System.out.println(auser) ;
System.out.println("================");
//添加一个用户
MyUser addmu = new MyUser() ;
addmu.setUid(10) ;
addmu.setUname("刘海") ;
addmu.setUsex("男") ;
int add = userDao.addUser(addmu) ;
System.out.println("添加了" + add + "条记录") ;
System.out.println("================") ;
//修改一个用户
MyUser updatemu = new MyUser() ;
updatemu.setUid(2) ;
updatemu.setUname("张男神") ;
updatemu.setUsex("男") ;
int up = userDao.updateUser(updatemu) ;
System.out.println("修改了" + up + "条记录") ;
System.out.println("=================");
//删除一个用户
int d1 = userDao.deleteUser(1) ;
System.out.println("删除了" + d1 + "条记录") ;
System.out.println("=================") ;
//查询所有用户
List <MyUser> list = userDao.selectAllUser() ;
for(MyUser myUser : list) {
System.out.println(myUser) ;
}
}
}
8-在src目录下创建spring配置文件applicationContext.xml,在配置文件中配置数据源,MyBatis工厂以及Mapper代理开发等信息,需要加载mybatis的核心配置文件mybatis-config.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 指定需要扫描的包,使得注解生效 -->
<context:component-scan base-package="com.dao"/>
<context:component-scan base-package="com.controller"/>
<!-- 配置数据源 -->
<bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/spring?characterEncoding=utf8"/>
<property name = "username" value = "root"/>
<property name = "password" value = "123456"/>
<!-- 最大连接数 -->
<property name = "maxTotal" value = "30" />
<!-- 最大空闲连接数 -->
<property name = "maxIdle" value = "10"/>
<!-- 初始化连接数 -->
<property name = "initialSize" value = "5"/>
</bean>
<!-- 添加事务支持 -->
<bean id = "txManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name = "dataSource" ref = "dataSource"/>
</bean>
<!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager = "txManager"/>
<!-- 配置MyBatis工厂,指定数据源,并与MyBtis完美整合 -->
<bean id = "sqlSesssionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
<property name = "dataSource" ref = "dataSource" />
<!-- configLocation属性值为MyBatis的核心配置文件 -->
<property name = "configLocation" value = "classpath:com/mybatis/mybatis-config.xml"/>
</bean>
<!-- Mapper代理开发,使用Spring自动扫描MyBatis的接口并装配
Spring将指定包中所有被@Mapper注解标注的接口自动装配为MyBatis的映射接口 -->
<bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- mybatis-spring组件的扫描器 -->
<property name = "basePackage" value = "com.dao"/>
<property name = "sqlSessionFactoryBeanName" value = "sqlSesssionFactory"/>
</bean>
</beans>
9-在com.controller包中创建测试类TestController
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestController {
public static void main(String[] args) {
//初始化Spring容器,加载配置文件
ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml") ;
//获取实例对象
UserController uc = (UserController) appCon.getBean("userController") ;
uc.test() ;
}
}
10-控制台运行结果和spring数据库中user表的结果分别如下:
控制台:
数据库user表:
下面通过IDEA编写一个实例演示MyBatis与Spring整合。
1-新建一个名为ch6ss的web应用,如下所示:
2-在web/WEB-INF目录下创建lib目录,在lib目录中导入相关jar包,并把jar添加为项目库
3-在MySQL数据库中创建数据库spring,并创建用户表user,字符串编码方式设置为utf8,需要在该表中录入几行数据
创建数据库和用户表user:
在user表录入四行数据:
4-创建持久化类,在src目录下创建一个名为com.po的包,在该包中创建持久化类MyUser,该类中定义的字段与数据库中定义的字段一致
public class MyUser {
private Integer uid ;
private String uname, usex ;
//访问和修改方法
public void setUid(Integer uid){
this.uid = uid ;
}
public Integer getUid(){
return uid ;
}
public void setUname(String uname){
this.uname = uname ;
}
public String getUname(){
return uname ;
}
public void setUsex(String usex){
this.usex = usex ;
}
public String getUse(){
return usex ;
}
@Override
public String toString(){
return "MyUser " + "uid = " + uid + " uname = " + uname + " usex = " + usex ;
}
}
5-在src目录下创建一个名为com.mybatis的包,在该包中SQL映射文件UserMapper.xml和MyBatis的核心配置文件
SQL映射文件配置代码:
<?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.dao.UserDao">
<!--根据uid查询一个用户信息-->
<select id = "selectUserById" parameterType = "Integer" resultType = "com.po.MyUser">
select * from user where uid = #{uid}
</select>
<!--查询所有用户信息-->
<select id = "selectAllUser" resultType = "com.po.MyUser">
select * from user
</select>
<!--添加一个用户-->
<insert id = "addUser" parameterType = "com.po.MyUser">
insert into user (uid,uname,usex) values(#{uid},#{uname}, #{usex})
</insert>
<!--修改一个用户-->
<update id = "updateUser" parameterType = "com.po.MyUser">
update user set uname = #{uname}, usex = #{usex} where uid = #{uid}
</update>
<!--删除一个用户-->
<delete id = "deleteUser" parameterType = "Integer">
delete from user where uid = #{uid}
</delete>
</mapper>
MyBatis核心配置文件代码:
<?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>
<!--告诉MyBatis映射文件的位置-->
<mappers>
<mapper resource = "com/mybatis/UserMapper.xml"/>
</mappers>
</configuration>
6-在src目录下创建一个名为com.dao的包,在该包中创建数据访问接口UserDao,并将该接口使用@Mapper注解,接口中的方法与SQL映射文件中一致,Spring将指定包中所有被@Mapper注解标注过的接口自动装配为MyBatis的映射接口
UserDao接口代码如下:
import com.po.MyUser;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Spring将指定包中被@Mapper注解标注的接口自动装配为MyBatis映射的接口
*/
@Repository("userDao")
@Mapper
public interface UserDao {
//接口方法对应SQL映射文件的UserMapper.xml的id
public MyUser selectUserById(Integer uid) ;
public List<MyUser> selectAllUser() ;
public int addUser(MyUser user) ;
public int updateUser(MyUser user) ;
public int deleteUser(Integer uid) ;
}
7-在src目录下创建日志文件log4j.properties,MyBatis默认使用log4j输出日志信息,如果开发者需要查看控制台输出的SQL语句,那么需要在classpath路径下配置其日志文件、
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
8-创建控制层,在src目录下创建一个名为com.contoller的包,在该包中创建UserController类,在该类中调用数据访问接口的方法
import com.dao.UserDao;
import com.po.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.util.List;
@Controller("userController")
public class UserController {
@Autowired
private UserDao userDao ;
public void test(){
//查询一个用户
MyUser auser = userDao.selectUserById(1) ;
System.out.println(auser) ;
System.out.println("=================") ;
//添加一个用户
MyUser addmu = new MyUser() ;
addmu.setUid(5) ;
addmu.setUname("薛仁贵") ;
addmu.setUsex("男") ;
int add = userDao.addUser(addmu) ;
System.out.println("添加了" + add + "条记录") ;
System.out.println("==================") ;
//修改一个用户
MyUser updatemu = new MyUser() ;
updatemu.setUid(1) ;
updatemu.setUname("王国栋") ;
updatemu.setUsex("男") ;
int up = userDao.updateUser(updatemu) ;
System.out.println("修改了" + up + "条记录") ;
System.out.println("==================") ;
//删除一个用户
int delete = userDao.deleteUser(2) ;
System.out.println("删除" + delete + "个记录") ;
System.out.println("==================") ;
//查询所有用户
List<MyUser> list = userDao.selectAllUser() ;
for(MyUser myUser : list){
System.out.println(myUser) ;
}
}
}
9-在src目录下创建Spring的配置文件applicationContext.xml,在配置文件中配置数据源,MyBatis工厂以及Mapper代理开发等信息
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--指定需要扫描的包,是注解生效-->
<context:component-scan base-package="com.dao"/>
<context:component-scan base-package="com.controller"/>
<!--配置数据源-->
<bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource">
<!--配置数据库驱动-->
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<!--配置连接数据库的url-->
<property name = "url" value = "jdbc:mysql://localhost:3306/spring?characterEncoding=utf8"/>
<!--连接数据库的用户名-->
<property name = "username" value = "root"/>
<!--连接数据库的密码-->
<property name = "password" value = "123456"/>
<!--最大连接数-->
<property name = "maxTotal" value = "30"/>
<!--最大空闲连接数-->
<property name = "maxIdle" value = "10"/>
<!--初始化最大连接数-->
<property name = "initialSize" value = "5"/>
</bean>
<!--添加事务支持-->
<bean id = "txManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name = "dataSource" ref = "dataSource"/>
</bean>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="txManager"/>
<!--配置MyBatis工厂,同时指定数据源,并与MyBatis完美整合-->
<bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
<property name = "dataSource" ref = "dataSource"/>
<!--configLocation的属性值为MyBatis的核心配置文件-->
<property name = "configLocation" value = "classpath:com/mybatis/mybatis-config.xml"/>
</bean>
<!--Mapper代理开发,使用Spring自动扫描MyBatis接口并装配,Spring将指定包中的所有被@Mapper注解过的接口自动装配为MyBatis的映射接口-->
<bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--mybatis-spring的组件扫描器-->
<property name = "basePackage" value = "com.dao"/>
<property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory"/>
</bean>
</beans>
10-在com.controller包中创建测试类TestController,代码如下:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestController {
public static void main(String[] args){
//初始化Spring容器,加载配置文件
ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml") ;
//获取目标对象的实例
UserController uc = (UserController) appCon.getBean("userController") ;
uc.test() ;
}
}
11-控制台输出结果如下:
12-spring数据库中user表的如下:
以上是关于MyBatis与Spring的整合(Eclipse版本和IDEA版本)的主要内容,如果未能解决你的问题,请参考以下文章