美文网首页
springboot + mybatis使用xml方式九

springboot + mybatis使用xml方式九

作者: AmeeLove | 来源:发表于2018-04-25 15:51 被阅读30次

springboot集成mybatis使用 xml方式

依赖

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.12.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.8</version>
    </dependency>
</dependencies>

application.properties

debug=true
#path
server.context-path=/Chapter02
server.port=9090
spring.devtools.restart.exclude=static/**,public/**

spring.http.encoding.force=true


# mybatis
mybatis.config-location=classpath:mybatis-config.xml
mybatis.type-aliases-package=com.ghgcn.mysb.chapter03.entity
mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml


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>


    <!--<properties resource="jdbc.properties" />-->

    <settings>
        <!-- 这个配置使全局的映射器启用或禁用缓存 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
       <!-- <setting name="lazyLoadingEnabled" value="true" />
        <setting name="multipleResultSetsEnabled" value="true" />
        <setting name="useColumnLabel" value="true" />
        <setting name="defaultExecutorType" value="REUSE" />-->
        <setting name="defaultStatementTimeout" value="25000" />
        <!-- 强制使用自动生成主键
         <setting name="useGeneratedKeys" value="true" /> -->
        <!-- 开启自动驼峰命名与下划线分隔列自动映射
         <setting name="mapUnderscoreToCamelCase" value="true"/> -->
        <setting name="logImpl" value="SLF4J" />
    </settings>
   <!-- <typeAliases>
        <package name="com.ghgcn.mysb.chapter03.entity" />
    </typeAliases>
-->


   
</configuration>

jdbc.properties

#jdbc.driver=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull
#jdbc.username=root
#jdbc.password=root

#数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
#连接池的配置信息
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  
spring.datasource.maxWait=60000  
spring.datasource.timeBetweenEvictionRunsMillis=60000  
spring.datasource.minEvictableIdleTimeMillis=300000  
spring.datasource.validationQuery=SELECT 1 FROM DUAL  
spring.datasource.testWhileIdle=true  
spring.datasource.testOnBorrow=false  
spring.datasource.testOnReturn=false  
spring.datasource.poolPreparedStatements=true  
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  
spring.datasource.filters=stat,wall,log4j  
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

数据源

package com.ghgcn.mysb.chapter03.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@PropertySource(value={"classpath:jdbc.properties"})
public class DruidDBConfig {

    private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.filters}")
    private String filters;

    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;


    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }

    //设置模版与数据源
    @Bean
    public JdbcTemplate jdbcTemplate(){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource());
        return jdbcTemplate;
    }

    public String getDbUrl() {
        return dbUrl;
    }

    public void setDbUrl(String dbUrl) {
        this.dbUrl = dbUrl;
    }

    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 getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public int getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(int initialSize) {
        this.initialSize = initialSize;
    }

    public int getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }

    public int getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public int getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(int maxWait) {
        this.maxWait = maxWait;
    }

    public int getTimeBetweenEvictionRunsMillis() {
        return timeBetweenEvictionRunsMillis;
    }

    public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
        this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
    }

    public int getMinEvictableIdleTimeMillis() {
        return minEvictableIdleTimeMillis;
    }

    public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
        this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
    }

    public String getValidationQuery() {
        return validationQuery;
    }

    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }

    public boolean isTestWhileIdle() {
        return testWhileIdle;
    }

    public void setTestWhileIdle(boolean testWhileIdle) {
        this.testWhileIdle = testWhileIdle;
    }

    public boolean isTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public boolean isTestOnReturn() {
        return testOnReturn;
    }

    public void setTestOnReturn(boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }

    public boolean isPoolPreparedStatements() {
        return poolPreparedStatements;
    }

    public void setPoolPreparedStatements(boolean poolPreparedStatements) {
        this.poolPreparedStatements = poolPreparedStatements;
    }

    public int getMaxPoolPreparedStatementPerConnectionSize() {
        return maxPoolPreparedStatementPerConnectionSize;
    }

    public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
        this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
    }

    public String getFilters() {
        return filters;
    }

    public void setFilters(String filters) {
        this.filters = filters;
    }

    public String getConnectionProperties() {
        return connectionProperties;
    }

    public void setConnectionProperties(String connectionProperties) {
        this.connectionProperties = connectionProperties;
    }
}

sql

CREATE TABLE `student` (
  `stud_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学生id',
  `name` varchar(255) NOT NULL COMMENT '学生姓名',
  `email` varchar(255) NOT NULL COMMENT '邮箱',
  `dob` date DEFAULT NULL COMMENT '生日',
  PRIMARY KEY (`stud_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;


mapper

public interface StudentMapper {

    
    public List<Student> findAllStudents();
    public Student findStudentById(Integer stuId);
    public int insertStudent(Student stu);
    public int updateStudent(Student stu);
    
    
    public List<Student> getStudents();
}

mapper - 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.ghgcn.mysb.chapter03.mapper.StudentMapper">


    <resultMap type="com.ghgcn.mysb.chapter03.entity.Student"
               id="BaseResultMap">
        <id column="stud_id" property="studId"/>
        <result column="name" property="name"/>
        <result column="email" property="email"/>
        <result column="dob" property="dob"/>


    </resultMap>


    <sql id="baseSql">
        stud_id,name,email,dob
    </sql>


    <select id="findAllStudents" resultMap="BaseResultMap">
        SELECT
        <include refid="baseSql"/>
        FROM student
    </select>

    <select id="findStudentById" resultMap="BaseResultMap">
        SELECT
        <include refid="baseSql"/>
        FROM
        student
        WHERE stud_id = #{stuId}
    </select>
    <insert id="insertStudent" parameterType="Student">
        INSERT INTO
        STUDENT
        (NAME,EMAIL,DOB)
        VALUES(#{name},#{email},#{dob})
    </insert>

    <update id="updateStudent" parameterType="Student">
        UPDATE STUDENT
        SET
        NAME=#{name},
        EMAIL=#{email},
        DOB=#{dob}

        WHERE stud_id = #{studId}
    </update>

    <select id="getStudents" resultMap="BaseResultMap">
        SELECT
        <include refid="baseSql"/>
        FROM student
    </select>
</mapper>

application

最后在启动类上加上 扫描maper interface注解

@SpringBootApplication
@MapperScan("com.ghgcn.mysb.chapter03.mapper")
public class Chpater03Application {


    public static  void main(String [] args){
        SpringApplication.run(Chpater03Application.class,args);
    }
}

image.png

或者在每个XXMapper类上加上@mapper注解也行 二选一即可


image.png

个人建议使用直接在启动类上application上@MapperScan方便,一次搞定,不必每写一个mapper类都加上@mapper注解

测试

import com.ghgcn.mysb.chapter03.Chpater03Application;
import com.ghgcn.mysb.chapter03.entity.Student;
import com.ghgcn.mysb.chapter03.mapper.StudentMapper;
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;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Chpater03Application.class)
public class Test1 {


    @Autowired
    private StudentMapper studentMapper;


    @Test
    public void testStuMapper() {

        System.err.println("studentMapper  "+studentMapper);
    }


    @Test
    public void testStuMapperGetALL() {

        System.err.println("studentMapper  "+studentMapper.findAllStudents());
    }


    @Test
    public void testStuMapperInster() {

        Student student = new Student();
        student.setDob(new Date());
        student.setName("测试inster1");
        student.setEmail("test1@qq.com");
        System.err.println("studentMapper  "+studentMapper.insertStudent(student));
    }


    @Test
    public void testStuMapperUpdate() {
        Student student =studentMapper.findStudentById(7);

        student.setDob(new Date());
        student.setName("update1修改");
        student.setEmail("update1修改@qq.com");
        System.err.println("studentMapper  "+studentMapper.updateStudent(student));
    }
}

相关文章

网友评论

      本文标题:springboot + mybatis使用xml方式九

      本文链接:https://www.haomeiwen.com/subject/ssrylftx.html