Spring integrates Mybatis

Spring integrates Mybatis

 

focus

 

      1. Important packages: mybatis (implementing SQL encapsulation and result mapping) and mybatis-spring (injecting Mybatis configuration into beans)

 

      2. Configure the data source

 

      3. Inject the sqlSessionFactory into the bean and the Mybatis mapping file into the bean

 

      4. Mybatis mapping file, how to map the result set and javabean

 

      5. The difference from spring-jdbc is that spring-jdbc needs to implement classes, and the implementation classes do encapsulation, addition, deletion, modification and checking, while Mybatis only needs to define the interface, and then write all operations in the SQL of the mapping file

 

 

 

code

 

Required jar package

<!-- Link to MySQL database -->
<dependency>  
    <groupId>mysql</groupId>  
    <artifactId>mysql-connector-java</artifactId>  
    <version>5.1.36</version>  
</dependency>  
<!-- Used for spring to connect to the database, including: dataSource, transaction, encapsulated database operation-->
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-jdbc</artifactId>  
    <version>4.2.1.RELEASE</version>  
    <scope>compile</scope>  
</dependency>  
<!-- Mybatis configuration can be done by configuring beans in spring, otherwise the configuration of mybatis needs to be used separately-->
<dependency>  
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>   
    <version>1.2.3</version>  
</dependency>  
<!-- Packages for 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">  

    <!-- Packages to scan -->
    <context:component-scan base-package="com.emerson.suzhou" />  
  
    <!-- Use spring jdbc to connect to the database -->
    <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 creates a SqlSession object and opens a database session -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <!-- Data source used -->
        <property name="dataSource" ref="dataSource" />  
        <!-- Configure the location of the Mapper file-->
        <property name="mapperLocations" value="classpath:com/emerson/suzhou/mapping/*.xml"></property>   
    </bean>  

    <!-- The package name of the DAO interface, Spring will automatically find the class under it -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.emerson.suzhou.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  
    <!-- (transaction management) transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
</beans>  

 

In this configuration file, we specified:

 

      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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326575059&siteId=291194637