10、MyBatis与Spring整合
来源:互联网 发布:单片机控制方案 编辑:程序博客网 时间:2024/05/21 14:59
整合思路
- SqlSessionFactory对象应该是放到spring容器中,并且是单例;
- 传统的DAO开发应该从spring容器中获取sqlsession对象;
- Mapper代理形式中应该从spring容器中直接获得mapper代理对象;
- 数据库连接以及数据库连接池事务管理都交给spring容器来完成。
整合的jar包
http://download.csdn.net/download/qq_25343557/10162260
详细整合步骤
1、导入jar包
2、加入配置文件:
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> <typeAliases> <!-- 批量设置别名,别名为类名,不区分大小写 --> <package name="cn.xpu.hcp.bean"/> </typeAliases> <!-- 数据库的配置交给spring处理 --></configuration>
spring的配置文件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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 加载数据库配置属性文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置数据源 --> <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"> <!-- 载入核心配置文件 --> <property name="configLocation" value="classpath:SqlMapConfig.xml"/> <property name="dataSource" ref="dataSource"/> </bean></beans>
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql:///MybatisSpringjdbc.username=rootjdbc.password=
DAO开发
需求:
- 实现根据用户id查询
- 实现根据用户名模糊查询
- 添加用户
创建User表:
CREATE TABLE `user` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `username` VARCHAR(32) NOT NULL COMMENT '用户名称', `birthday` DATE DEFAULT NULL COMMENT '生日', `sex` CHAR(1) DEFAULT NULL COMMENT '性别', `address` VARCHAR(256) DEFAULT NULL COMMENT '地址', PRIMARY KEY (`id`)) ENGINE=INNODB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', '王五', '2014-07-10', '2', '重庆市');INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');INSERT INTO `user` VALUES ('16', '张小明', '1995-07-10', '1', '河南郑州');INSERT INTO `user` VALUES ('22', '陈小明', '1996-09-10', '1', '河南郑州');INSERT INTO `user` VALUES ('24', '张三丰', '1990-08-10', '1', '河南郑州');INSERT INTO `user` VALUES ('25', '陈小明', '1995-08-20', '1', '河南郑州');INSERT INTO `user` VALUES ('26', '王五', '1996-07-10', '1', '上海市');
创建User类:
public class User implements Serializable{ private static final long serialVersionUID = 1L; private int id; private String username; private String sex; private Date birthday; private String address; 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; } public User() { super(); } public User(String username, String sex, Date date, String address) { super(); this.username = username; this.sex = sex; this.birthday = date; this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; }}
原始DAO开发
原始DAO开发:DAO接口+实现类
原始DAO开发实现类需要继承SqlsessionDaoSupport类
实现DAO接口:
public interface UserDao { User getUserById(int id); List<User> getLikeByName(String name); void insertUser(User user);}
实现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="user"> <select id="getUserById" parameterType="int" resultType="User"> select * from user where id=#{id} </select> <select id="getLikeByName" parameterType="string" resultType="User"> select * from user where username like "%"#{username}"%" </select> <insert id="insertUser" parameterType="User"> <selectKey keyColumn="id" keyProperty="id" order="AFTER" resultType="int"> SELECT LAST_INSERT_ID() </selectKey> insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address}) </insert></mapper>
编写UserDao实现类:
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { @Override public User getUserById(int id) { SqlSession session = super.getSqlSession(); User user = session.selectOne("getUserById", 1); return user; } @Override public List<User> getLikeByName(String name) { SqlSession session = super.getSqlSession(); List<User> list = session.selectList("getLikeByName", name); return list; } @Override public void insertUser(User user) { SqlSession session = super.getSqlSession(); session.insert("insertUser", user); }}
在Spring的applicationContext.xml中配置userDao:
<!-- 原始DAO开发,配置DAO到spring中 --><bean id="userDao" class="cn.xpu.hcp.daoImpl.UserDaoImpl"> <!-- 配置SqlSessionFactory --> <property name="SqlSessionFactory" ref="sqlSessionFactory"/></bean>
测试:
<!--使用spring的单元测试功能需要导入额外jar包-->@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class TestUtils { @Autowired @Qualifier("userDao") private UserDao userDao; @Test public void test() { User user = userDao.getUserById(1); System.out.println(user); List<User> list = userDao.getLikeByName("王"); for (User u : list) { System.out.println(u); } User temp = new User("李四","1",new Date(),"南昌市"); userDao.insertUser(temp); }}
Mapper代理形式开发Dao
UserMapper接口与UserDao接口相同,和UserMapper.xml放在一起;
UserMapper.xml中的名称空间设置为UserMapper的全类名。
现在要在applicationContext.xml中配置mapper接口:
方法一:
<!-- 方法一 --><bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="cn.xpu.hcp.mapper.UserMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/></bean>
测试:
@Autowired @Qualifier("userMapper") private UserMapper userMapper; @Test public void test() { User user = userMapper.getUserById(1); System.out.println(user); List<User> list = userMapper.getLikeByName("王"); for (User u : list) { System.out.println(u); } User temp = new User("赵四","1",new Date(),"西宁市"); userMapper.insertUser(temp); System.out.println(temp); }
这种方式有一个明显的缺点:如果我们有很多的mapper接口那么我们要写很多次这种配置,很繁琐。使用方法二可以很方便解决。
方法二:
仅仅是配置mapper的方法不同而已:
<!-- 扫描包的形式配置mapper--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 这种方法不需要写id --> <!-- 配置基础包,每个mapper代理对象的id就是类名,首字母小写 --> <property name="basePackage" value="cn.xpu.hcp.mapper"/></bean>
阅读全文
3 0
- 10、MyBatis与Spring整合
- spring与mybatis整合
- 整合spring与myBatis
- mybatis 与 spring 整合
- mybatis与spring整合
- mybatis与spring整合
- mybatis与spring整合
- spring与mybatis整合
- spring与mybatis整合
- Spring与Mybatis整合
- Mybatis与Spring整合
- spring与mybatis整合
- mybatis与spring整合
- spring与mybatis整合
- Mybatis与Spring整合
- MyBatis与Spring整合
- Spring与MyBatis整合
- Spring与MyBatis整合
- netty源码分析(二十四)TCP粘包与拆包实例演示及分析
- CentOS 7 Linux 中Yum方式安装MySQL(咋个办呢 zgbn)
- Centos 7 从零搭建nginx+tomcat集群
- pytorch可视化工具visdom启动失败解决方法
- MySQL数据库使用——MySQL字段管理
- 10、MyBatis与Spring整合
- Django处理一个请求的过程
- okhttp拦截器
- 神经网络的十万个为什么
- 通过FEDERATED变相实现多数据源
- 搜索详情
- jvm的GC算法总结
- test
- PHP伪静态步骤