spring整合Mybatis
重点
1. 重要的包:mybatis(实现SQL的封装和结果的映射) 和 mybatis-spring(将Mybatis的配置注入bean)
2. 配置数据源
3. 将sqlSessionFactory注入到bean,将Mybatis的映射文件注入到bean
4. Mybatis映射文件,怎么将结果集和javabean进行映射
5. 跟 spring-jdbc 有所区别的是,spring-jdbc 需要实现类,实现类做封装增删改查,而Mybatis只要定义接口,然后操作全部写在映射文件的SQL中
代码
需要的jar包
<!-- 链接MySQL数据库用的 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> </dependency> <!-- 用于spring连接数据库,包括:dataSource、事务、封装数据库操作 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.1.RELEASE</version> <scope>compile</scope> </dependency> <!-- 可以通过spring配置bean的方式进行mybatis配置了,不然需要单独使用mybatis的配置 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!-- Mybatis要用的包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency>
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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 要扫描的包 --> <context:component-scan base-package="com.emerson.suzhou" /> <!-- 用spring jdbc连接数据库 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/your_database" /> <property name="username" value="your_username" /> <property name="password" value="your_password" /> </bean> <!-- SqlSessionFactory创建SqlSession对象,打开一个数据库会话 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 使用的数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 配置Mapper文件所在位置--> <property name="mapperLocations" value="classpath:com/emerson/suzhou/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.emerson.suzhou.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
在这个配置文件中,我们指定了:
1. 数据源:用于连接目标数据库
2. Spring扫描路径:会扫描指定路径下的所有Component,为后面的依赖注入做准备。如果我们需要对Mybatis进行一些特别设置,可以在这里指定配置文件的路径
3. 映射文件路径:Mybatis会在指定路径加下加载数据表是映射文件
4. Dao接口包名称:对应着每个数据表的映射文件,我们都会为其编写一个接口
记得别忘了在web.xml中加入applicationContext.xml文件的配置
<!-- spring-mybatis configuration file location --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
javabean
package com.emerson.suzhou.pojo;
import java.sql.Timestamp;
public class User {
private int userId;
private String userPassword;
private String userName;
private String nickName;
private String email;
private int isValid;
private Timestamp createdTime;
private Timestamp updateTime;
//setter , getter ...
}
Mapper.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="com.emerson.suzhou.dao.IUserDao"> <!-- sql查询的字段 --> <sql id="columns">user_id, user_name, user_password, nick_name, email, is_valid, created_time, update_time </sql> <!-- 查询后的结果集映射 --> <resultMap id="userResult" type="com.emerson.suzhou.pojo.User"> <id property="userId" column="user_id" /> <result property="userName" column="user_name" /> <result property="userPassword" column="user_password" /> <result property="nickName" column="nick_name" /> <result property="email" column="email" /> <result property="isValid" column="is_valid" /> <result property="createdTime" column="created_time" /> <result property="updateTime" column="update_time" /> </resultMap> <!-- 根据传入的Id值,到数据库中查询记录 --> <select id="getById" parameterType="int" resultMap="userResult"> SELECT <include refid="columns"></include> FROM sys_user WHERE user_id = #{id} </select> </mapper>
Dao接口
package com.emerson.suzhou.dao;
import com.emerson.suzhou.pojo.User;
public interface IUserDao {
public User getById(int id);
}
Service接口
package com.emerson.suzhou.service;
import com.emerson.suzhou.pojo.User;
public interface IUserService {
public User getById(int id);
}
Service实现类
package com.emerson.suzhou.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.emerson.suzhou.dao.IUserDao;
import com.emerson.suzhou.pojo.User;
import com.emerson.suzhou.service.IUserService;
@Service("userService")
public class UserSerivceImpl implements IUserService {
@Resource
private IUserDao dao;
@Override
public User getById(int id) {
return this.dao.getById(id);
}
}
测试类
package com.emerson.suzhou;
import static org.junit.Assert.*;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.emerson.suzhou.pojo.User;
import com.emerson.suzhou.service.IUserService;
public class TestMybatis {
private static Logger logger = Logger.getLogger(TestMybatis.class);
@Resource
private IUserService userService = null;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
assertNotNull(userService);
User user = userService.getById(1);
logger.info(user);
}
}
参考:
http://blog.csdn.net/chris_mao/article/details/48904711