mybatis3.2.3整合spring其实就那么几步,网上很多文章大篇幅地将原理,很多时候把人给弄糊涂了,我的建议是“先学会怎么用,再去学原理”。看此文章时,最好与《Mybatis3.2.3+mysql第一个例子(入门)》一起来看,这样你就能更好地理解整合spring的好处。
先看下此文章使用的项目的目录结构:
mybatis整合spring最简单的理解就是“把mybatis数据源的配置、事务的管理、SqlSessionFactory的创建以及数据映射器接口Mapper的创建交由spring去管理”,所以mybatis的配置文件mybatis-config.xml中不需要再配置数据源及事务,在业务层service实现时不需要手动地获取SqlSession以及对应的数据映射器接口Mapper,通过spring的注入即可。
1、准备工作:
(1)、下载mybatis:http://code.google.com/p/mybatis/downloads/list?can=3&q=Product%3DMyBatis
(2)、下载mybatis-spring:https://code.google.com/p/mybatis/downloads/detail?name=mybatis-spring-1.2.1.zip
(3)、下载mysql-connector-java-5.1.14.jar
(4)、mybatis-spring官方地址:http://mybatis.github.io/spring/
2、创建一个User实体:
package com.luoshengsha.bean;
public class User {
private String id;
private String name;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3、创建userMapper:
package com.luoshengsha.mapper;
import com.luoshengsha.bean.User;
public interface UserMapper {
/**保存**/
public void save(User user);
/**修改**/
public void update(User user);
/**查找**/
public User find(String id);
/**删除**/
public void delete(String id);
}
4、创建UserMapper.xml://跟UserMapper.java在同一目录下
<?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.luoshengsha.mapper.UserMapper">
<!-- 保存 -->
<insert id="save" parameterType="user">
insert into user(id,name,password) values(#{id},#{name},#{password})
</insert>
<!-- 更新 -->
<update id="update" parameterType="user">
update user set name=#{name},password=#{password} where id=#{id}
</update>
<!-- 查找 -->
<select id="find" parameterType="string" resultType="user">
select * from user where id=#{id}
</select>
<!-- 删除 -->
<delete id="delete" parameterType="string">
delete from user where id=#{id}
</delete>
</mapper>
5、创建UserService:
package com.luoshengsha.service;
import com.luoshengsha.bean.User;
public interface UserService {
/**保存**/
public void save(User user);
/**修改**/
public void update(User user);
/**查找**/
public User find(String id);
/**删除**/
public void delete(String id);
}
6、创建UserServiceImpl:
package com.luoshengsha.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.luoshengsha.bean.User;
import com.luoshengsha.mapper.UserMapper;
import com.luoshengsha.service.UserService;
@Service //告诉spring这个业务组件
@Transactional //告诉spring这个类需要事务
public class UserServiceImpl implements UserService {
@Resource
private UserMapper mapper;
@Override
public void save(User user) {
//此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。
mapper.save(user);
}
@Override
public void update(User user) {
//此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。
mapper.update(user);
}
@Override
public User find(String id) {
//此处不再进行创建SqlSession,都已交由spring去管理了。
return mapper.find(id);
}
@Override
public void delete(String id) {
//此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。
mapper.delete(id);
}
}
7、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>
<!-- <properties resource="jdbc.properties" /> -->
<settings>
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。默认:true -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<!--//此处的配置不再需要
<environments>...</environments>
-->
<typeAliases><!--设置别名-->
<typeAlias type="com.luoshengsha.bean.User" alias="user"/>
</typeAliases>
<!--说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml-->
<mappers>
<mapper resource="com/luoshengsha/Mapper/UserMapper.xml"/>
</mappers>
</configuration>
8、spring配置文件bean.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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<aop:aspectj-autoproxy/>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--告诉spring从什么地方开始扫描组件,根据自己项目的实际目录配置-->
<context:component-scan base-package="com.luoshengsha" />
<!--数据源配置-->
<context:property-placeholder location="classpath:jdbc.properties"/><!--从classpath下面的jdbc.properties中读取数据库的链接信息-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
<!-- 初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="1"/>
<!-- 连接池中保留的最小连接数。 -->
<property name="minPoolSize" value="1"/>
<!-- 连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="300"/>
<!-- 最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="60"/>
<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="5"/>
<!-- 每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60"/>
</bean>
<!--把mybatis SqlSessionFactory的创建交由spring管理-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" /><!--数据源-->
<property name="configLocation" value="classpath:mybatis-config.xml" /><!--mybatis配置文件路径-->
</bean>
<!-- scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.luoshengsha.mapper" /><!---根据自己的项目路径配置-->
</bean>
<!--把mybatis的事务交由spring去管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" /><!--注意:此处的数据源要与sqlSessionFactory中的dataSource相同-->
</bean>
<!--启用spring @Transactional注解 -->
<tx:annotation-driven />
</beans>
9、jdbc.properties配置文件:
driver=org.gjt.mm.mysql.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
10、log4j.properties:
log4j.rootLogger=debug, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.org.apache=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
11、web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>mybatisSpring</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!--告诉项目spring配置文件所处的位置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
12、junit测试:
package com.luoshengsha;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.luoshengsha.bean.User;
import com.luoshengsha.service.UserService;
public class UserTest {
protected static UserService userService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
userService = (UserService)cxt.getBean("userServiceImpl");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void save() {
User user = new User();
user.setId("2");
user.setName("绿竹");
user.setPassword("123456");
userService.save(user);
}
@Test
public void find() {
User user = userService.find("2");
System.out.println("name: " + user.getName());
}
@Test
public void update() {
User user = userService.find("2");
user.setName("绿竹2");
userService.update(user);
}
@Test
public void delete() {
userService.delete("2");
}
}
13、源码下载地址:http://pan.baidu.com/s/123Xd1
本文出自 luoshengsha.com,欢迎转载,转载时请注明出处及相应链接。