SpringBoot学习(四)集成mybatis

1.springboot集成mybatis

    1.1基本环境搭建

        1.创建maven项目

bf521c689683caeb22a7db7cb6492af6c87.jpg

        2.pom.xml加入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.gobon</groupId>
    <artifactId>springboot-mybatis-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- springboot父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>

    <dependencies>
        <!--springboot-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mybatis整合springboot-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- Mysql数据库连接驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- mybatis逆向工程 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <!--配置文件的位置-->
                    <configurationFile>src/main/resources/personal-generator.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>

            </plugin>

        </plugins>
        <resources>
            <!-- 在idea开发会存在路径下.xml配置编译不了到target目录下,在这里指定编译.xml到target目录下 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
    </build>
    
</project>

        3.配置application.properties

#指定端口号和上下文路径
server.port=9090
server.context-path=/springboot-mybatis-test

#指定mapper配置文件路径
mybatis.mapper-locations=classpath:cn/gobon/mapper/*.xml

#配置数据库连接信息
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8

        4.编写Application.java启动类

package cn.gobon;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @version V1.0
 * @ClassName: ValidateActionJson
 * @Description: springboot启动类
 * @Auther: Jianxiong Yi
 * @Date: 2018/8/11 15:17
 */
@SpringBootApplication
@MapperScan(basePackages = "cn.gobon.mapper") //扫描mapper
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

    1.2逆向工程生成mapper和实体类

        1.在src/resources加入personal-generator.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 指定数据库连接信息文件 -->
    <properties resource="personal-db.properties"></properties>
    <classPathEntry location="${jdbc.driverLocation}" />
    <context id="context1" targetRuntime="MyBatis3">

        <commentGenerator>
            <!-- 去除自动生成的注释 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 数据库连接配置 -->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}" />
        <!--jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"
                        userId="root"
                        password="mysql" /-->

        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--配置生成的实体包
            targetPackage:生成的实体包位置,默认存放在src目录下
            targetProject:目标工程名
         -->
        <javaModelGenerator targetPackage="cn.gobon.pojo"
                            targetProject="src/main/java" />

        <!-- 实体包对应映射文件位置及名称,默认存放在src目录下 -->
        <sqlMapGenerator targetPackage="cn.gobon.mapper" targetProject="src/main/java" />

        <!-- 生成mapper接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="cn.gobon.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!-- 配置表
            schema:不用填写
            tableName: 表名
            enableCountByExample、enableSelectByExample、enableDeleteByExample、enableUpdateByExample、selectByExampleQueryId:
            去除自动生成的例子
        -->
        <table schema="" tableName="department" enableCountByExample="false" enableSelectByExample="false"
               enableDeleteByExample="false" enableUpdateByExample="false" selectByExampleQueryId="false" >
        </table>
    </context>
</generatorConfiguration>

        2.在src/resources加入personal-db.properties

jdbc.driverLocation=C:\\develop\\apache-maven-3.3.9\\repository\\mysql\\mysql-connector-java\\5.1.43\\mysql-connector-java-5.1.43.jar
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8
jdbc.userId=root
jdbc.password=root

        3.执行maven插件生成

caee68500ea187d784e77d505d4fd30eb66.jpg

0ab2fc22bdccdc12f47d141885192f95397.jpg

    1.3编写相关类

        1.在DepartmentMapper.java添加一个测试方法

package cn.gobon.mapper;

import cn.gobon.pojo.Department;

import java.util.List;

public interface DepartmentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Department record);

    int insertSelective(Department record);

    Department selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Department record);

    int updateByPrimaryKey(Department record);

    //查询所有部门
    List<Department> findAll();
}

        2.编写service接口和实现类

package cn.gobon.service;

import cn.gobon.pojo.Department;

import java.util.List;

/**
 * @version V1.0
 * @ClassName: ValidateActionJson
 * @Description: TODO
 * @Auther: Jianxiong Yi
 * @Date: 2018/8/11 15:12
 */
public interface DepartmentService {

    //查询所有部门
    List<Department> findAll();

    //更新
    void update(Department department);
}

    

package cn.gobon.service.impl;

import cn.gobon.mapper.DepartmentMapper;
import cn.gobon.pojo.Department;
import cn.gobon.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @version V1.0
 * @ClassName: ValidateActionJson
 * @Description: TODO
 * @Auther: Jianxiong Yi
 * @Date: 2018/8/11 15:13
 */
@Service
public class DepartmentImpl implements DepartmentService {

    //注入mapper对象
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> findAll() {
        return departmentMapper.findAll();
    }

    @Override
    public void update(Department department) {
        departmentMapper.updateByPrimaryKey(department);
    }
}

        3.编写controller

package cn.gobon.controller;

import cn.gobon.pojo.Department;
import cn.gobon.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @version V1.0
 * @ClassName: ValidateActionJson
 * @Description: TODO
 * @Auther: Jianxiong Yi
 * @Date: 2018/8/11 15:14
 */
@RestController
public class DepartmentController {

    //注入service
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/findAllDepartment")
    public Object findAllDepartment(){
        return departmentService.findAll();
    }

    @RequestMapping("/update")
    public String update(){
        Department department = new Department();
        department.setId(1);
        department.setName("生产部");
        departmentService.update(department);
        return "success";
    }


}

        4.启动Application.java测试

687558778101cb3cc184b1474f8ff170de0.jpg

    1.4springboot事务的支持

        1.在Application.java配置注解

package cn.gobon;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @version V1.0
 * @ClassName: ValidateActionJson
 * @Description: springboot启动类
 * @Auther: Jianxiong Yi
 * @Date: 2018/8/11 15:17
 */
@SpringBootApplication
@MapperScan(basePackages = "cn.gobon.mapper") //
@EnableTransactionManagement//启动springboot事务的支持
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

        2.在DepartmentImpl.java实现类方法配置注解

package cn.gobon.service.impl;

import cn.gobon.mapper.DepartmentMapper;
import cn.gobon.pojo.Department;
import cn.gobon.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @version V1.0
 * @ClassName: ValidateActionJson
 * @Description: TODO
 * @Auther: Jianxiong Yi
 * @Date: 2018/8/11 15:13
 */
@Service
public class DepartmentImpl implements DepartmentService {

    //注入mapper对象
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> findAll() {
        return departmentMapper.findAll();
    }

    @Transactional
    @Override
    public void update(Department department) {
        departmentMapper.updateByPrimaryKey(department);
        //抛出异常,测试事务
        int i = 10 / 0;
    }
}

        3.修改controller update方法  

package cn.gobon.controller;

import cn.gobon.pojo.Department;
import cn.gobon.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @version V1.0
 * @ClassName: ValidateActionJson
 * @Description: TODO
 * @Auther: Jianxiong Yi
 * @Date: 2018/8/11 15:14
 */
@RestController
public class DepartmentController {

    //注入service
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/findAllDepartment")
    public Object findAllDepartment(){
        return departmentService.findAll();
    }

    @RequestMapping("/update")
    public String update(){
        Department department = new Department();
        department.setId(1);
        department.setName("保安部");
        departmentService.update(department);
        return "success";
    }


}

        4.启动访问,抛出/ by zero异常,数据库表中对应的数据没有改变,说明事务已经生效

    这里一定要注意在pom.xml加入resources指定编译后xml的位置,否则会报500错误,找不到mapper下的方法

    本人是初学者,如有错误,欢迎指点,谢谢!

转载于:https://my.oschina.net/u/3794524/blog/1926298

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值