Spring整合Mybatis的简单示例(注解)

参考链接:Spring整合Mybatis的简单示例(配置文件)

1、创建数据库表

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(12) DEFAULT NULL,
  `password` varchar(12) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2、实体类、DAO接口

User.java

package com.yusian.entity;

import java.io.Serializable;

public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

UserDao.java

package com.yusian.dao;

import com.yusian.entity.User;

public interface UserDao {

    /**
     * 保存用户信息
     * @param user
     */
    void saveUser(User user);
}

3、Mapper及数据相关属性

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.yusian.dao.UserDao">
    <insert id="saveUser" parameterType="User">
        insert into t_user(username, password) values(#{username}, #{password})
    </insert>

    <select id="getUsers" resultType="User">
        select * from t_user
    </select>
</mapper>

mybatis.properties

mybatis.driverClassName = com.mysql.jdbc.Driver
mybatis.url = jdbc:mysql://example.com/spring?useSSL=false
mybatis.username = root
mybatis.password = ******
mybatis.typeAliasPackage = com.yusian.entity
mybatis.mapperLocations = com/yusian/mapper/*Mapper.xml

MybatisProperties.java

package com.yusian.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Repository;

@Repository
@PropertySource("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.typeAliasPackage}")
    private String typeAliasPackage;
    @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 getTypeAliasPackage() {
        return typeAliasPackage;
    }

    public void setTypeAliasPackage(String typeAliasPackage) {
        this.typeAliasPackage = typeAliasPackage;
    }

    public String getMapperLocations() {
        return mapperLocations;
    }

    public void setMapperLocations(String mapperLocations) {
        this.mapperLocations = mapperLocations;
    }
}

4、Spring工厂的注解配置类

AppConfig.java

package com.yusian.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.yusian.entity.MybatisProperties;
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.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

@Configuration  // Spring注解配置文件
@MapperScan("com.yusian.dao")   // Mapper扫描,等效于xml配置中加载MapperScannerConfigure
@ComponentScan("com.yusian.entity") // 实体类扫描,生成mybatisProperties对象
public class AppConfig {

    @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) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage(mybatisProperties.getTypeAliasPackage());
        // 通配路径,获取一组资源对象
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(mybatisProperties.getMapperLocations());
        bean.setMapperLocations(resources);
        return bean;
    }
}

5、测试

ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
UserDao userDao = (UserDao) ctx.getBean("userDao");
userDao.saveUser(new User("Annotation", "10010"));

Leave a Reply