0
点赞
收藏
分享

微信扫一扫

MyBatis与Spring整合

眼君 2022-06-29 阅读 87


整合背景

稍微大一点的项目都会使用SSM或者SSH框架,但是如果项目不是那么的大,用MyBatis和Spring就足够了,MyBatis的优势就是sql灵活,可以适应多变的需求;使用spring可以降低各模块之间的耦合度,方便系统的升级与维护。

整合思路

需要spring通过单例的方式管理SqlSessionFactory
spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession(自动完成)
持久层mapper都需要spring进行管理

相关准备

一、创建一个Java工程

添加一个lib文件夹

MyBatis与Spring整合_sql

二、jar准备

mybatis-3.4.4所有jar
spring4.2.1相关jar​
整合jar:mybatis-spring-1.3.1.jar​
数据库驱动:mysql-connector-java-5.1.7-bin.jar​
数据连接池:数据连接池(c3p0)​
mchange-commons-java-0.2.3.4.jar:C3P0辅助包​
EHcache缓存(如果有需要)mybatis-ehcache-1.0.3和ehcache-core-2.6.11.jar
相关jar文件导入lib文件后Build-path一下

mybatis全局配置文件

在工程中创建一个资源文件夹

MyBatis与Spring整合_框架_02
在config资源夹中创建mybatis包,包中创建mybatis全局配置文件SqlMapConfig.xml
把连接数据库的配置抽取到db.properties,以便后期维护
为了方便调试,建立日志文件log4j.properties
在config资源夹中创建spring包,包中创建spring全局配置文件applicationContext.xml

MyBatis与Spring整合_spring_03
db.properties内容
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/MyBatis?useUnicode=true&characterEncoding=UTF8
jdbc.username=root
jdbc.password=123456


log4j.properties内容
#Global logging configuration

log4j.rootLogger=DEBUG, 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


SqlMapConfig.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>

</configuration>


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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>

创建几个文件包

最后项目结构差不多就是这样

MyBatis与Spring整合_sql_04

在applicationContext.xml中配置数据源和SqlSessionFactory

<!-- 加载数据库配置信息 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 数据源配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name= "driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>


<!-- SqlSessionFactory配置
class:属性在mybatis-spring-1.3.1的第一个包中
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
<!-- 数据源 -->
<property name="dataSourcev" ref="dataSource"></property>
</bean>

建一个pojo类(User.java)

package com.hl.ld.pojo;

import java.util.Date;

public class User {

private int id;
private String username;
private char sex;
private Date birthday;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address + "]";
}

}


因为打算用mapper接口的方式开发,所以要采用mapper规范
具体请参考:Mybatis Mapper代理开发规范
创建UserMapper.xml,写几个statement
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hl.ld.mapper.UserMapper">

<select id="findUserById" parameterType="int" resultType="user">
select * FROM user WHERE id = #{id}
</select>

<select id="findUserByName" parameterType="String" resultType="user">
select * FROM user WHERE address LIKE '%${value}%'
</select>

<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id = #{value}
</delete>

</mapper>


根据mapper代理开发规范创建UserMapper.java接口
package com.hl.ld.mapper;


import java.util.List;

import com.hl.ld.pojo.User;


public interface UserMapper {

//根据id查询用户信息
public User findUserById(int id) throws Exception;
//根据id删除用户
public void deleteUser(int id);
//根据用户姓名模糊查找
public List<User> findUserByName(String name);
}

在SqlMapConfig.xml中定义pojo类的别名

<!-- 别名 -->
<typeAliases>

<!-- 批量定义别名
指定包名,MyBatis会自动扫描包内类,自动定义别名,别名就是类名,首字母不区分大小写
-->
<package name="com.hl.ld.pojo"/>
</typeAliases>

在SqlMapConfig.xml中引入映射文件UserMapper.xml

<!-- 加载映射文件 -->
<mappers>
<package name="com.hl.ld.mapper.UserMapper"/>
</mappers>

applicationContext.xml中配置mapper接口

<!-- mapper的配置,通过MapperFactoryBean生成代理对象
name:根据指定接口生成代理对象
-->
<bean id="userMaper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.hl.ld.mapper.UserMapper"/>
<!-- sqlSessionFactory -->
<property name="sqlSessionFactory" res="sqlSessionFactory"/>

</bean>


测试

package com.hl.ld.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hl.ld.mapper.UserMapper;
import com.hl.ld.pojo.User;


public class SpringMybatisTest {
private ApplicationContext applicationContext;

@Before
public void before(){
String configLocation = "classpath:spring/applicationContext.xml";
//获取spring容器
applicationContext = new ClassPathXmlApplicationContext(configLocation);
}
@Test
public void testFindUserById() throws Exception{
UserMapper userMaper = (UserMapper) applicationContext.getBean("userMaper");
User user = userMaper.findUserById(3);
System.out.println(user);
}
}


结果:

DEBUG [main] - ==>  Preparing: select * FROM user WHERE id = ? 
DEBUG [main] - ==> Parameters: 3(Integer)
DEBUG [main] - <== Total: 1
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2556db07]
DEBUG [main] - Returning JDBC Connection to DataSource
DEBUG [main] - com.mchange.v2.async.ThreadPoolAsynchronousRunner@ab519aa: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask@4867b7f4
DEBUG [main] - trace com.mchange.v2.resourcepool.BasicResourcePool@6d05629f [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@4a8f5018)
DEBUG [C3P0PooledConnectionPoolManager[identityToken->1hge0ys9ojz0qmodgyzri|85132f5]-HelperThread-#0] - com.mchange.v2.c3p0.impl.NewProxyConnection@38cf9a71: close() called more than once.
User [id=3, username=项羽, sex=1, birthday=Wed Apr 05 00:00:00 CST 2017, address=秦时明月之万里长城]


花了点时间,还是实现了

源码在此




MyBatis与Spring整合_spring_05


举报

相关推荐

0 条评论