Spring 整合 myBatis

思路

  1. 數據庫鏈接池交給 Spring 管理
  2. SqlSessionFactory 交給 Spring 管理
  3. 從 Spring 容器中直接得到 mapper 的代理對象

步驟

  1. 建立工程
  2. 導入 jar
  3. 建立 config 文件夾,放置配置文件
    • 配置文件:
      • jdbc.properties : 數據庫配置
        xml jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC jdbc.username=root jdbc.password=root
      • log4j.properties :日誌打印
      • mybatis_config.xml:myBatis 配置,只須要配置二級緩存就能夠了,其餘都交給 Spring 處理。
        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>        <setting name="cacheEnabled" value="true" />    </settings> </configuration>
      • applicationContext.xml:Spring 配置文件
        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:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:context="http://www.springframework.org/schema/context" 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:config/jdbc.properties" />    <!-- 數據庫鏈接池 -->    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">        <property name="driverClassName" value="${jdbc.driverClass}" />        <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">        <!-- 配置 mybatis 核心配置文件 -->        <property name="configLocation" value="classpath:config/mybatis_config.xml" />        <!-- 配置數據源 -->        <property name="dataSource" ref="dataSource" />        </bean>    </beans>
  4. DAO 開發
    1. 建立 POJO User.javajava

      public class User {    
          private Integer id;    
          private String username;    
          private Date birthday;    
          private String address;    
          private boolean sex;    
          public boolean isSex() {        
          return sex;   
          }   
          public void setSex(boolean sex) {      
           this.sex = sex;   
          }   
          public Integer getId() {        
           return id;   
          }    
          public void setId(Integer id) {      
            this.id = id;  
          }   
          public String getUsername() {       
           return username;  
          }   
          public void setUsername(String username) {      
           this.username = username;   
          }   
          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 + '\'' +                ", birthday=" + birthday +                ", address='" + address + '\'' +                ", sex=" + sex +                '}';    
          }
      }
    2. 在 applicatonContext.xml 中配置別名掃描
      e80e05d0437f77fd2b0b25e3461a1025.pngmysql

    3. 實現 UserMapper 接口git

      public interface UserMapper {    
          User quertUserById(int id);   
      
          List<User> queryUserByUserName(String username);   
      
          void saveUser(User user);
      }
    4. 實現 UserMapper.xml 配置文件github

      <?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="cc.lijingbo.ssm.mapper.UserMapper">    
          <select id="quertUserById" parameterType="int" resultType="user">        
              select * from user where id = #{id}    
          </select>    
          <select id="queryUserByUserName" resultType="user" parameterType="String">        
              select * from user where username like '%${value}%'    
          </select>    
          <insert id="saveUser" parameterType="user">        
              <selectKey keyProperty="id" keyColumn="id" order="AFTER"   resultType="int">            
              select last_insert_id()        
              </selectKey>        
              insert into user (username,sex,address) values (#{username},#{sex},#{address})    
          </insert>
      </mapper>
    5. 在 applicationContext.xml 中配置 mapper 掃描
      bfaac79b7f67c47b95aba96d6f649cb0.png
    6. 測試spring

      public class UserMapperTest {   
          ApplicationContext applicationContext;    
          @Before    
          public void setUp() throws Exception {       
              applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
          }    
          @Test    
          public void quertUserById() {       
              UserMapper userMapper = 
              applicationContext.getBean(UserMapper.class);       
              User user = userMapper.quertUserById(3);        
              System.out.println(user);   
          }   
          @Test    
          public void queryUserByUserName() {        
              UserMapper userMapper = applicationContext.getBean(UserMapper.class);       
              List<User> users = userMapper.queryUserByUserName("張");        
              for (User u : users) {          
                  System.out.println(u);      
              }   
          }   
          @Test    
          public void saveUser() {       
              UserMapper userMapper = applicationContext.getBean(UserMapper.class);       
              User user = new User();       
              user.setUsername("劉備");      
              user.setAddress("深圳XXX");      
              user.setSex(false);      
              userMapper.saveUser(user); 
          }
      }

源碼 github 地址sql

相關文章
相關標籤/搜索