整合spring與mybaties

一、mybaties的使用

a、通過SqlSessionFactory獲得 SqlSession 的實例。

b、SqlSession 包含了面向數據庫執行 SQL 命令所需的方法。通過 SqlSession 實例來執行已映射的 SQL 語句。

思路

核心配置(mybaties-config)——》映射(mapper)——》SqlSessionFactory——》SqlSession

配置數據源

mybatis-config.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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
   </environment>
 </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

 

映射器(mappers) 

BlogMapper.mapper

<?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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

構建 SqlSessionFactory 

test.java

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
//Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);

 

二、springJdbc的使用

思路

Dao——》配置——》applicationContext容器

數據模型

Student.java ——

public class Student {
   private Integer age;
   private String name;
   private Integer id;
   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
}

Dao

StudentDAO.java——

public interface StudentDAO {
   public void setDataSource(DataSource ds);
   public void create(String name, Integer age);
   public Student getStudent(Integer id);
   public List<Student> listStudents();
   public void delete(Integer id);
   public void update(Integer id, Integer age);
}

 

StudentJDBCTemplate.java——

public class StudentJDBCTemplate implements StudentDAO {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject; 
   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void create(String name, Integer age) {
      String SQL = "insert into Student (name, age) values (?, ?)";     
      jdbcTemplateObject.update( SQL, name, age);
      return;
   }
   public Student getStudent(Integer id) {
      String SQL = "select * from Student where id = ?";
      Student student = jdbcTemplateObject.queryForObject(SQL,  new Object[]{id}, new StudentMapper());
      return student;
   }
   public List<Student> listStudents() {
      String SQL = "select * from Student";
      List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
      return students;
   }
   public void delete(Integer id){
      String SQL = "delete from Student where id = ?";
      jdbcTemplateObject.update(SQL, id);
      return;
   }
   public void update(Integer id, Integer age){
      String SQL = "update Student set age = ? where id = ?";
      jdbcTemplateObject.update(SQL, age, id);
      return;
   }
}

配置數據源 

 Beans.xml ——bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
   <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/TEST"/>
      <property name="username" value="root"/>
      <property name="password" value="password"/>
   </bean>
   <bean id="studentJDBCTemplate" class="com.tutorialspoint.StudentJDBCTemplate">
      <property name="dataSource"  ref="dataSource" />    
   </bean>
</beans>

ApplicationContext 容器

MainApp.java——

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");    
      List<Student> students = studentJDBCTemplate.listStudents();
      studentJDBCTemplate.update(2, 20);
      Student student = studentJDBCTemplate.getStudent(2);   
   }
}

 

整合demo1

搭建項目

【src】中創建 4 個空包:

  • cn.wmyskxz.dao

(放置 DAO 數據交互層處理類)

  • cn.wmyskxz.mapper

(放置 Mapper 代理接口)

  • cn.wmyskxz.pojo

(放置 Java 實體類)

  • cn.wmyskxz.test

(放置測試類)

【config】用於放置各種資源配置文件:

  • 【config / mybatis】

“SqlMapConfig.xml” : MyBatis 全局配置文件

  • 【config / spring】

“applicationContext.xml” : Spring 資源配置文件

  • 【config / sqlmap】

 “UserMapper.xml” : Mapper 映射文件。

  • 【config】

 “db.properties” :用於數據庫連接

“log4j.properties”:日誌系統參數設置

引入依賴 jar 包

在【WEB-INF】文件夾下的【lib】文件夾中放置上面列舉的 jar 包,然後添加依賴

a、MyBatis 的包(MyBatis 3.4.6

b、Spring 的 jar 包(Spring 4.3.15

c、MyBatis 與 Spring 的整合 jar 包(mybatis-spring 1.3.2

d、mysql-connector-java-5.1.21.jar

e、junit-4.12.jar

編寫 Spring 配置文件

a、頭部的信息就是聲明 xml 文檔配置標籤的規則的限制與規範。

b、“context:property-placeholder” 配置是用於讀取工程中的靜態屬性文件

c、配置了一個名爲 dataSrouce的 bean 的信息,實際上是連接數據庫的數據源。

d、設置 sqlSessionFactory 的 bean 實現類爲 MyBatis 與 Spring 整合 jar 包中的 SqlSessionFactoryBean

<?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"
       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">

    <!-- 加載配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置數據源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加載 MyBatis 的配置文件 -->
        <property name="configLocation" value="mybatis/SqlMapConfig.xml"/>
        <!-- 數據源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

編寫 MyBatis 配置文件

a、通過 settings 配置了一些延遲加載和緩存的開關信息

b、在 typeAliases 中設置了一個 package 的別名掃描路徑,在該路徑下的 Java 實體類都可以擁有一個別名(即首字母小寫的類名)

c、在 mappers 配置中,使用 mapper 標籤配置了即將要加載的 Mapper 映射文件的資源路徑

d、有了 Spring 託管數據源,在 MyBatis 配置文件中僅僅需要關注性能化配置

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>

    <!-- settings -->
    <settings>
        <!-- 打開延遲加載的開關 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 將積極加載改爲消極加載(即按需加載) -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 打開全局緩存開關(二級緩存)默認值就是 true -->
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <!-- 別名定義 -->
    <typeAliases>
        <package name="cn.wmyskxz.pojo"/>
    </typeAliases>

    <!-- 加載映射文件 -->
    <mappers>
        <!-- 通過 resource 方法一次加載一個映射文件 -->
        <mapper resource="sqlmap/UserMapper.xml"/>
        <!-- 批量加載mapper -->
        <package name="cn.wmyskxz.mapper"/>
    </mappers>
</configuration>

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="test">
    <select id="findUserById" parameterType="_int" resultType="user">
    SELECT * FROM USER WHERE id = #{id}
</select>
</mapper>

Dao

UserDAOImpl

a、SqlSessionDaoSupport 類是 MyBatis 與 Spring 整合的 jar 包中提供的

b、在該類中已經包含了 sqlSessionFactory 對象作爲其成員變量,而且對外提供 get 和 set 方法

package cn.wmyskxz.dao;
import cn.wmyskxz.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
public class UserDAOImpl extends SqlSessionDaoSupport implements UserDAO {
    @Override
    public User findUserById(int id) throws Exception {
        // 繼承 SqlSessionDaoSupport 類,通過 this.getSqlSession() 得到 sqlSession
        SqlSession sqlSession = this.getSqlSession();
        User user = sqlSession.selectOne("test.findUserById", id);
        return user;
    }
}

測試

package cn.wmyskxz.test;
import cn.wmyskxz.dao.UserDAO;
import cn.wmyskxz.pojo.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserServiceTest {
    private ApplicationContext applicationContext;
    // 在執行測試方法之前首先獲取 Spring 配置文件對象
    // 註解@Before在執行本類所有測試方法之前先調用這個方法
    @Before
    public void setup() throws Exception {
        applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }
    @Test
    public void testFindUserById() throws Exception {
        // 通過配置資源對象獲取 userDAO 對象
        UserDAO userDAO = (UserDAO) applicationContext.getBean("userDAO");
        // 調用 UserDAO 的方法
        User user = userDAO.findUserById(1);
        // 輸出用戶信息
        System.out.println(user.getId() + ":" + user.getUsername());
    }
}

整合demo2

mybatis配置文件

SqlMapconfig.xml

<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 定義 別名 -->
    <typeAliases>
        <!-- 單個別名的定義  alias:別名,type:別名映射的類型  -->
        <!-- <typeAlias type="com.hust.mybatis.po.User" alias="user"/> -->
        <!-- 批量別名定義 指定包路徑,別名默認爲類名(首字母小寫或大寫) -->
        <package name="com.hust.springmybatis.po"/>
    </typeAliases>
    <mappers>
        <!-- 通過resource引用mapper的映射文件 -->
        <mapper resource="sqlmap/User.xml" />
        <mapper resource="mapper/UserMapper.xml" />
    </mappers>
</configuration>

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"
    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-3.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

    <!-- 配置數據源 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 如果是用額外的配置文件 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="maxActive" value="10"></property>
        <property name="maxIdle" value="5"></property>
    </bean>

    <!-- SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 數據源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
    </bean>

    <bean id="userDao" class="com.hust.springmybatis.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <!-- MapperFactoryBean:用於生成mapper代理對象 -->
    <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.hust.springmybatis.mapper.UserMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean> -->

    <!-- MapperScannerConfigurer:mapper的掃描器,將包下邊的mapper接口自動創建代理對象
        自動創建到spring容器中,bean的id是mapper的類名(首字母小寫)
     -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置掃描包路徑, 如果要掃描多個包,中間使用半角逗好隔開 -->
        <property name="basePackage" value="com.hust.springmybatis.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans>

開發dao

dao接口

user.xml

測試

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章