springboot集成mybatis

Posted 草木物语

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot集成mybatis相关的知识,希望对你有一定的参考价值。

配置pom.xml:

<dependency><!--mybatis-->
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency><!--mysql-->
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency><!--c3p0-->
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>

 


创建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>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedkeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true"/>

        <!-- 使用列标签替换列别名 默认:true -->
        <setting name="useColumnLabel" value="true"/>

        <!-- 开启驼峰命名转换 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

 

创建DataSourceConfiguration类:

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.beans.PropertyVetoException;
/**
 * 补充一下,datasource这些配置是可以在application.properties里配置,不过翔仔这样做是有两个考虑:
 * 1.可以让同学了解一下第三方datasource的配置方法,spring自带的是可以在application.properties里配置的
 * 2.和之前的实战课衔接,因为实战课程既讲了SpringMVC同时讲了SpringBoot,在教大家SpringMVC迁移到SpringBoot的时候,咱们用的是类似的方式将XML转成了Bean,所以为了无缝衔接起来
 * 实战过程中,黑猫白猫,能抓住老鼠的都是好猫。并且大一些的项目数据库连接池用的是自定义而非spring自带的多一些:)
 */
@Configuration
@MapperScan("com.xc.boot.dao")
public class DataSourceConfiguration {

    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Bean(name = "dataSource")
    public ComboPooledDataSource createDateSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        dataSource.setAutoCommitOnClose(false);// 关闭连接后不自动commit
        return dataSource;
    }
}

 


配置application.properties:

#jdbc.driver=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/boot?useUnicode=true&characterEncoding=utf8&userSSL=false
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/boot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
jdbc.username=root
jdbc.password=123456

 

创建表:

CREATE TABLE `tb_area` (
`area_id` int(2) NOT NULL AUTO_INCREMENT,
`area_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`priority` int(2) NOT NULL DEFAULT 0,
`create_time` datetime DEFAULT NULL,
`last_edit_time` datetime DEFAULT NULL,
PRIMARY KEY (`area_id`),
UNIQUE KEY `UK_AREA` (`area_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

 


创建SessionFactoryConfiguration类:

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
@Configuration
public class SessionFactoryConfiguration {

    @Value("${mybatis_config_file}")
    private String mybatisConfigFilePath;//mybatis-config.xml配置文件的路径
    @Value("${mapper_path}")
    private String mapperPath;// mybatis mapper文件所在路径
    @Value("${entity_package}")
    private String entityPackage;// 实体类所在的package

    //    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactroyBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}

 


配置application.properties:

#Mybatis
mybatis_config_file=mybatis-config.xml
mapper_path=/mapper/**.xml
entity_package=com.xc.boot.entity

 

创建实体类:

package com.xc.boot.entity;
import java.util.Date;
public class Area {
    // 主键id
    private Integer areaId;
    // 名称
    private String areaName;
    // 权重,越大越排前显示
    private Integer priority;
    // 创建时间
    private Date createTime;
    // 更新时间
    private Date lastEditTime;
//...get,set
}

 


创建dao层:

package com.xc.boot.dao;
import com.xc.boot.entity.Area;
import java.util.List;
public interface AreaDao {
    List<Area> queryArea();
    Area queryAreaById(int areaId);
    int insertArea(Area area);
    int updateArea(Area area);
    int deleteArea(int areaId);
}

 

创建测试类:

package com.xc.boot.dao;
import com.xc.boot.entity.Area;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AreaDaoTest {

    @Autowired
    private AreaDao areaDao;

    @Test
    public void queryArea() {
        List<Area> areaList = areaDao.queryArea();
        assertEquals(2, areaList.size());
    }

    @Test
    public void queryAreaById() {
        Area area = areaDao.queryAreaById(1);
        assertEquals("东苑",area.getAreaName());
    }

    @Test
    @Ignore
    public void insertArea() {
        Area area = new Area();
        area.setAreaName("南苑");
        area.setPriority(1);
        int insertArea = areaDao.insertArea(area);
        assertEquals(1,insertArea);
    }

    @Test
    @Ignore
    public void updateArea() {
        Area area = new Area();
        area.setAreaName("西苑");
        area.setAreaId(3);
        area.setLastEditTime(new Date());
        int updateArea = areaDao.updateArea(area);
        assertEquals(1,updateArea);
    }

    @Test
    public void deleteArea() {
        int deleteArea = areaDao.deleteArea(3);
        assertEquals(1,deleteArea);
    }
}

 






以上是关于springboot集成mybatis的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot集成mybatis以及自动化测试代码实现

SpringBoot集成mybatis

springboot-简单集成mybatis

01.springboot集成mybatis与jsp

SpringBoot 集成MyBatis-Plus提示反序列化异常:cannot deserialize from Object value (no delegate- or property-bas

Springboot 和 Mybatis集成开发