純註解版spring與mybatis的整合過程

今天給大傢分享純註解版spring與mybatis的整合

mybatis包下:有這幾個,上面圖片沒有展開

配置Bean:MyBatisAutoConfiguration

 User

UserDAO

MybatisProperties

MyBatisAutoConfiguration:

package com.baizhiedu.mybatis;
 
import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
 
 
import javax.sql.DataSource;
import java.io.IOException;
 
@Configuration
@ComponentScan(basePackages = "com.baizhiedu.mybatis")
@MapperScan(basePackages = "com.baizhiedu.mybatis") //掃描dao接口對象
public class MyBatisAutoConfiguration {
 
    //連接池對象
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&charaterEcoding=utf-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }
    //工廠對象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.baizhiedu.mybatis");
        //設置Mapper文件的路徑,這個隻會 掃描一個Mapper文件,如果需要掃描多個文件,則需要讓他掃描包
        sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("UserDAOMapper.xml"));
 
        //通配寫法讓他掃描包下的所有Mapper文件資源
        try {
            ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
            Resource[] resources=resolver.getResources("com.baizhiedu.mapper/*Mapper.xml");
            sqlSessionFactoryBean.setMapperLocations(resources);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return  sqlSessionFactoryBean;
    }
}

 User:

package com.baizhiedu.mybatis;
 
public class User {
    private Integer id;
    private String name;
    private String password;
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
}

UserDAO:

package com.baizhiedu.mybatis;
 
public interface UserDAO {
    public void save(User user);
}

UserDAOMapper.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.baizhiedu.mybatis.UserDAO">
    <!--使用insert,update,delete,select標簽來寫sql語句-->
    <insert id="save" parameterType="User">
        insert into tb_users (name,password) values (#{name},#{password})
    </insert>
 
</mapper>

TestMyBatis:

package com.baizhiedu;
 
import com.baizhiedu.mybatis.MyBatisAutoConfiguration;
import com.baizhiedu.mybatis.User;
import com.baizhiedu.mybatis.UserDAO;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
public class TestMyBatis {
    //用於測試Spring+Mybatis註解的整合
    @Test
    public void test1(){
        ApplicationContext ctx=new AnnotationConfigApplicationContext(MyBatisAutoConfiguration.class);
        UserDAO userDAO=(UserDAO)ctx.getBean("userDAO");
 
        User user=new User();
        user.setName("annotation1");
        user.setPassword("123456");
 
        userDAO.save(user);
    }
}

 上面配置Bean:MyBatisAutoConfiguration:存在數據耦合,可以通過配置文件來解耦合:

mybatis.properties:

mybatis.driverClassName=com.mysql.jdbc.Driver
mybatis.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;charaterEcoding=utf-8
mybatis.username=root
mybatis.password=123456
mybatis.typeAliasesPackages=com.baizhiedu.mybatis
mybatis.mapperLocations=com.baizhiedu.mapper/*Mapper.xml

定義類來封裝配置文件中的配置信息:MybatisProperties:

package com.baizhiedu.mybatis;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
 
@Component
@PropertySource("classpath:mybatis.properties") //讀取配置文件
public class MybatisProperties {
    @Value("${mybatis.driverClassName}")
    private String driverClassName;
    @Value("${mybatis.url}")
    private String url;
    @Value("${mybatis.username}")
    private String username;
    @Value("${mybatis.password}")
    private String password;
    @Value("${mybatis.typeAliasesPackages}")
    private String typeAliasesPackages;
    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;
 
    public String getDriverClassName() {
        return driverClassName;
    }
 
    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }
 
    public String getUrl() {
        return url;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public String getTypeAliasesPackages() {
        return typeAliasesPackages;
    }
 
    public void setTypeAliasesPackages(String typeAliasesPackages) {
        this.typeAliasesPackages = typeAliasesPackages;
    }
 
    public String getMapperLocations() {
        return mapperLocations;
    }
 
    public void setMapperLocations(String mapperLocations) {
        this.mapperLocations = mapperLocations;
    }
}

更改配置MyBatisAutoConfiguration:

package com.baizhiedu.mybatis;
 
import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
 
 
import javax.sql.DataSource;
import java.io.IOException;
 
@Configuration
@ComponentScan(basePackages = "com.baizhiedu.mybatis")
@MapperScan(basePackages = "com.baizhiedu.mybatis") //掃描dao接口對象
public class MyBatisAutoConfiguration {
 
    @Autowired //註解 自定義類型註入,用來解耦合
    private MybatisProperties mybatisProperties;
 
    //連接池對象
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName(mybatisProperties.getDriverClassName());
        dataSource.setUrl(mybatisProperties.getUrl());
        dataSource.setUsername(mybatisProperties.getUsername());
        dataSource.setPassword(mybatisProperties.getPassword());
        return dataSource;
    }
    //工廠對象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackages());
        //設置Mapper文件的路徑,這個隻會 掃描一個Mapper文件,如果需要掃描多個文件,則需要讓他掃描包
        sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("UserDAOMapper.xml"));
 
        //通配寫法讓他掃描包下的所有Mapper文件資源
        try {
            ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
            Resource[] resources=resolver.getResources(mybatisProperties.getMapperLocations());
            sqlSessionFactoryBean.setMapperLocations(resources);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return  sqlSessionFactoryBean;
    }
}

TestMyBatis:test:

到此這篇關於基於純註解實現spring與mybatis的整合的文章就介紹到這瞭,更多相關spring與mybatis整合內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: