测试代码在下面(没jar)
集成步骤
1、 jar包集成;
2、 配置文件集成(数据源);
3、 Spring对SqlSessionFactory进行管理配置;
4、 Mybatis程序编写(接口、映射文件);
5、 Spring通过配置文件管理mybatis 的对象;
jar包集成
Mybatis3.2.7 的jar包(mybatis核心包、依赖包)
Spring3.2.0 的jar包
Spring与mybatis的集成包
数据库驱动包
Dbcp连接池包
搭建工程环境
配置文件集成
注意:Mybatis的配置文件中的数据源配置去掉,由spring进行管理配置。
Mybatis的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> <!-- 设置全局参数 --> <settings> <!-- lazyLoadingEnabled:延迟加载的开关,默认是false --> <setting name="lazyLoadingEnabled"value="true"/> <!-- aggressiveLazyLoading:默认为true,一旦为true上面的懒加载开关失效 --> <setting name="aggressiveLazyLoading"value="false"/> <!-- cacheEnabled:二级缓存的总开关默认是false--> <setting name="cacheEnabled"value="true"/> </settings> <!-- 定义别名 --> <typeAliases> <!-- 批量定义别名 --> <!-- name:指定需要别名定义的包的名称它的别名就是类名(类名的首字母大小写都可)--> <package name="cn.mybatis.sm.domain"></package> </typeAliases> <!-- 注意:与spring集成后,数据源和事务交给spring来管理 --> <!-- 加载mapper文件 --> <mappers> <!-- 批量加载mapper 注意:mapper接口文件和mapper映射文件,名称相同,在同一个包下 --> <package name="cn.mybatis.sm.mapper"/> </mappers> </configuration> |
Spring的applicationContext.xml配置文件头:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> |
Spring的applicationContext.xml配置文件内容:
<!-- 引用db.properties配置文件 -->
<context:property-placeholder location="db.properties"/>
<!-- 配置数据源,使用dbcp连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"value="${db.driver}" />
<property name="url"value="${db.url}" />
<property name="username"value="${db.username}" />
<property name="password"value="${db.password}" />
<property name="maxActive"value="10" />
<property name="maxIdle"value="5" />
</bean> |
<!-- Spring管理SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- mybatis配置文件的地址 --> <property name="configLocation" value="mybatis/sqlMapConfig.xml"></property> <!-- 配置数据源 --> <property name="dataSource" ref="dataSource"></property> </bean> |
MyBatis程序编写
编写DAO接口
package cn.mybatis.sm.dao;
import cn.mybatis.sm.domain.User;
public interface UserDao {
public User findUserById(int id);
} |
package cn.mybatis.sm.dao.impl;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import cn.mybatis.sm.dao.UserDao;
import cn.mybatis.sm.domain.User;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
public User findUserById(int id) {
return this.getSqlSession().selectOne("cn.mybatis.sm.mapper.UserMapper.findUserById", id);
}
} |
编写Mapper映射文件
<select id="findUserById" parameterType="int" resultType="user">
SELECT <include refid="selectUserSql"></include> FROM USER WHERE ID = #{id}
</select> |
Spring定义bean
<!-- 配置UserDao进行注入开发 --> <bean id="userDao" class="cn.mybatis.sm.dao.impl.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> |
编写测试代码
package cn.mybatis.sm.dao;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.mybatis.sm.domain.User;
public class UserDaoTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
}
@Test
public void testFindUserById() {
UserDao dao = (UserDao) applicationContext.getBean("userDao");
User user = dao.findUserById(1);
System.out.println(user);
}
} |
Mapper接口开发
编写mapper接口
package cn.mybatis.sm.mapper;
import java.util.List;
import cn.mybatis.sm.domain.User;
import cn.mybatis.sm.domain.UserQuery;
/**
* 这是一个mapper接口,就和DAO的接口一样
* 定义方法,然后其他的实现都由MyBatis来完成就好啦
* @author 刘泽栋
* @date 2015年6月20日 下午2:33:58
*/
public interface UserMapper {
// 根据用户的ID来查询用户
public User findUserById(int id);
// 根据用户的名字来模糊查询用户
public List<User> findUserByName(String username);
// 添加用户
public void insertUser(User user);
// 根据用户的 性别和姓名来查询用户
public List<User> findUserByUser(User user);
// 复杂查询,就是使用 封装类,里面的类的条件进行查询
public List<User> findUserByList(UserQuery userQuery);
// 查询所有用户的id
public List<Integer> findIdList();
// 测试if
public List<User> findUser4If(User user);
// 测试where,动态的查询用户,看用户传入的是什么,在配置文件中做判断
public List<User> findUser4Where(User user);
//根据用户ID的集合查询用户列表(学习foreach标签之直接传ID集合)
public List<User> findUserByIdListForEach(List<Integer> idList);
} |
编写mapper映射文件
<?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">
<!-- namespace:此时用mapper代理方式开发,它的值必须等于对应mapper接口的全限定名 -->
<mapper namespace="cn.mybatis.sm.mapper.UserMapper">
<!-- 定义sql片段 -->
<!--
[sql标签]:定义一个SQL片段
[id]:SQL片段的唯一标识
建议:
1、SQL片段中的内容最好是以单表来定义
2、如果是查询字段,则不要写上SELECT
3、如果是条件语句,则不要写上WHERE
-->
<sql id="selectUserSql">
ID,USERNAME,SEX,BIRTHDAY,ADDRESS
</sql>
<!-- 根据id查询用户 -->
<!--
[include标签]:引用已经定义好的SQL片段
[refid]:引用的SQL片段id
-->
<select id="findUserById" parameterType="int" resultType="user">
SELECT <include refid="selectUserSql"></include> FROM USER WHERE ID = #{id}
</select>
<!-- 根据用户的姓名模糊查询用户列表 -->
<select id="findUserByName" parameterType="String" resultType="User">
SELECT * FROM USER WHERE USERNAME LIKE ‘%${value}%‘
</select>
<!-- 添加用户 -->
<insert id="insertUser" parameterType="User">
INSERT INTO USER(username,sex,birthday,address) VALUES(#{username},#{sex},#{birthday},#{address})
</insert>
<!-- 根据用户的性别和姓名来查询用户 -->
<!--
[if标签]:进行动态判断,如果成功则把if标签内的内容拼接到原有SQL上
[test]:填写判断表达式
-->
<select id="findUserByUser" parameterType="User" resultType="User">
SELECT * FROM USER WHERE sex = #{sex} AND username like ‘%${username}%‘
</select>
<!-- 复杂查询,就是查询类,里面的类 -->
<select id="findUserByList" parameterType="UserQuery" resultType="User">
SELECT * FROM USER WHERE sex = #{user.sex} AND username like ‘%${user.username}%‘
</select>
<!-- 查询所有id,返回的是简单类型 -->
<select id="findIdList" resultType="int">
SELECT ID FROM USER
</select>
<!-- 测试动态查询(if) -->
<!--
[if标签]:进行动态判断,如果成功则把if标签内的内容拼接到原有SQL上
[test]:填写判断表达式
-->
<select id="findUser4If" parameterType="User" resultType="User">
SELECT * FROM USER WHERE sex = #{sex}
<if test="username != null and username != ‘‘ ">
AND username like ‘%${username}%‘
</if>
</select>
<!-- 测试动态查询(where) -->
<!--
通过动态SQL可以看出,为了保证SQL语句的正确性,需要在where 后面添加没有任何意义的1=1
[where标签]:使用它可以去掉它后面的第一个and,这样就可以保证SQL的正确性了
-->
<select id="findUser4Where" parameterType="User" resultType="User">
SELECT <include refid="selectUserSql"/> FROM USER
<where>
<if test="sex != null and sex != ‘‘">
AND sex=#{sex}
</if>
<if test="username != null and username != ‘‘">
AND username LIKE ‘%${username}%‘
</if>
</where>
</select>
<!-- 根据用户ID的集合查询用户列表(学习foreach标签之直接传ID集合) -->
<!--
[foreach标签]:表示一个foreach循环
[collection]:集合参数的名称,如果是直接传入集合参数,则该处只能填写[list]。
[item]:定义遍历集合之后的参数名称
[open]:开始遍历之前需要拼接的SQL串
[close]:结束遍历之后需要拼接的SQL串
[separator]:遍历出的每个对象之间需要拼接的字符
-->
<select id="findUserByIdListForEach" parameterType="list" resultType="User">
select <include refid="selectUserSql"/> from user
<where>
<if test="list != null and list.size > 0">
<foreach collection="list" item="id" open="AND ID IN (" close=")" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
</mapper> |
Spring定义bean
Mapper代理开发方式有两种bean的定义方法,一种是MapperFactoryBean,一种是MapperScannerConfigurer。
通过MapperFactoryBean创建代理对象
通过MapperScannerConfigurer批量扫描创建代理对象
<!-- 使用mapper接口的形式开发 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定扫描的包 --> <property name="basePackage" value="cn.mybatis.sm.mapper"></property> <!-- 指定sqlSessionFactory的名字 --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> |
编写测试代码
package cn.mybatis.sm.mapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.mybatis.sm.domain.User;
/**
* Mapper测试代码
* @author 刘泽栋
* @date 2015年6月22日 下午11:39:58
*/
public class UserMapperTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
}
@Test
public void testFindUserById() {
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}
} |
测试结果
原文地址:http://liuzedong.blog.51cto.com/8906170/1664250