一、Spring与Mybatis整合环境
-
1.1 创建一个java项目,搭建项目结构
src:存放java文件
conf:存放配置文件
test:用于测试
lib:存放jar包
-
1.2 在conf/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 ">
<!-- 加载配置文件:存放数据库信息 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源:dbcp数据库连接池配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="5"/>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置configLocation,mybatis配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml" ></property>
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
这样把applicationContext.xml配置好,spring和mybatis就整合完毕了,下面引入两个小demo测试,一个原始dao开发,一个使用mapper接口开发
二、原始dao开发
-
2.1 在conf/mybatis下创建SqlMapConfig.xml为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>
<!-- 定义别名 -->
<typeAliases>
<typeAlias type="cn.zhao.ssm.pojo.User" alias="user"/>
<package name="cn.zhao.ssm.pojo"/>
</typeAliases>
<mappers>
<mapper resource="sqlmap/UserMapper.xml"/>
</mappers>
</configuration>
mybatis和spring整合后,就不需要配置environment环境了,其数据库配置都由spring注册
-
2.2 在src/cn/zhao/ssm/pojo包下创建User.java的Pojo类
package cn.zhao.ssm.pojo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
//这里实现序列化是之前测试二级缓存的,可以不用加
public class User implements Serializable {
//属性名和数据库表的字段对应
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
//用户创建的订单列表
private List<Orders> ordersList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String 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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
+ address + ", ordersList=" + ordersList + "]";
}
public List<Orders> getOrdersList() {
return ordersList;
}
public void setOrdersList(List<Orders> ordersList) {
this.ordersList = ordersList;
}
}
-
2.3 在src/cn/zhao/ssm/dao包下创建UserDao接口和UserDaoImpl实现类
package cn.zhao.ssm.dao;
import cn.zhao.ssm.pojo.User;
//UserDao接口
public interface UserDao {
//根据id查询user
public User findUserById(int id) throws Exception;
}
package cn.zhao.ssm.dao;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import cn.zhao.ssm.pojo.User;
/*
* UserDaoImpl实现类
*/
//注意要继承SqlSessionDaoSupport
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User findUserById(int id) throws Exception {
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("user.getUserById", id);
return user;
}
}
在UserDaoImpl实现类中,继承了SqlSessionDaoSupport,在之前没有整合spring时是没有的,继承该类就由spring来管理SqlSession了,而不需要我们自己创建,直接this.getSqlSession()即可得到SqlSession对象。
并且该Dao实现类,需要注入SqlSessionFactory类对象,会在下面的spring配置文件配置,还需注意!
-
2.4 在applicationContext中注册dao接口
<!-- 原始Dao开发配置UserDao -->
<bean id="userDao" class="cn.zhao.ssm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
注意:这里注入了SqlSessionFactory,是非常必要的
配置完spring,基本demo就成型了,剩下就需要测试我们的demo能不能运行
-
2.5 测试类,在test下创建UserDaoTest
package spring_mybatis;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.zhao.ssm.dao.UserDao;
import cn.zhao.ssm.pojo.User;
public class UserDaoImplTest {
private ApplicationContext applicationContext;
@Before
//测试前先获取application对象
public void getApplicationContext() {
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception {
//向spring容器拿UserDao接口对象
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
User user = userDao.findUserById(1);
System.out.println(user);
}
}
junit测试可以看到测试成功
三、使用Mapper代理开发
实际开发中,基本不会用到原始Dao开发,都是mapper代理居多,现在写一个mapper代理开发的demo
-
3.1 在src/cn/zhao/ssm/mapper包下创建UserMapper.java接口和UserMapper.xml配置文件
package cn.zhao.ssm.mapper;
import cn.zhao.ssm.pojo.User;
public interface UserMapper {
//根据id查询user
public User findUserById(int id) throws Exception;
}
<?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="cn.zhao.ssm.mapper.UserMapper">
<!--
根据id查询用户
resultType:映射成单条记录的java对象
#{}中如果是简单数据类型可以随便填,其他需要添为参数名称 -->
<select id="findUserById" parameterType="int" resultType="user" >
select * from user where id = #{value}
</select>
</mapper>
-
3.2 在applicationContext中注册mapper代理
<!-- mapper接口开发-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.zhao.ssm.mapper.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
-
3.3 测试
在test包下创建测试类 UserMapperTest
package spring_mybatis;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.zhao.ssm.mapper.UserMapper;
import cn.zhao.ssm.pojo.User;
public class UserMapperTest {
private ApplicationContext applicationContext;
@Before
public void getApplicationContext() {
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void test() throws Exception {
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}
}
测试结果
-
3.4 改进
可以看到,在applicationContext配置文件中,如果每个mapper就配置一个,会出现大量代码雷同
这里,我们就可以使用MapperScannerConfigurer进行mapper扫描
<!-- mapper接口包扫描,MapperScannerConfigurer包扫描器,
自动注册mapper接口,名字为mapperbean的id(首字母小写) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名
如果是多个包,使用,分隔 -->
<property name="basePackage" value="cn.zhao.ssm.mapper"></property>
<!-- 使用sqlSessionFactoryBeanName
如果使用sqlSessionFactory,其数据源加载就会后执行,就会出错 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>