springBoot 入门(五)—— 使用 纯注解方式 的springboot+ mybatis+junit4 整合

配置pom.xml依赖


<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.0modelVersion>

    <groupId>com.wqgroupId>
    <artifactId>beautyartifactId>
    <version>1.0-SNAPSHOTversion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.4.0.RELEASEversion>
        <relativePath/> 
    parent>
    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>com.sun.mailgroupId>
            <artifactId>javax.mailartifactId>
            <version>1.5.2version>
        dependency>
        
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.2.0version>
        dependency>
        
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>tk.mybatisgroupId>
            <artifactId>mapper-spring-boot-starterartifactId>
            <version>1.1.0version>
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

User.java

public class User {
    private Long id;
    private String userName;
    private String userSex;
    private int userAge;

    public User() {

    }

    public User(String userName, String userSex, int userAge) {
        super();
        this.userName = userName;
        this.userSex = userSex;
        this.userAge = userAge;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }

}

UserMapper.java

package mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import pojo.User;


public interface UserMapper {
    /**
     * 查询所有用户信息
     *
     * @return
     */
    @Select("select * from user")
    @Results(value = { @Result(property = "userSex", column = "user_sex", javaType = String.class),
            @Result(property = "userName", column = "user_name"), @Result(property = "userAge", column = "user_age") })
    List findList();

    /**
     * 通过ID查询
     *
     * @param id
     * @return
     */
    @Select("select * from user u where u.id=#{id}")
    User findOne(@Param("id") Long id);

    /**
     * 新增一个
     *
     * @param user
     */
    @Insert("insert into user (user_name,user_sex,user_age) values(#{userName},#{userSex},#{userAge})")
    void insert(User user);

    /**
     * 修改
     *
     * @param user
     */
    @Update("update user u set u.user_name=#{userName},u.user_sex=#{userSex},u.user_age=#{userAge} where u.id=#{id}")
    void update(User user);

    /**
     * 删除
     *
     * @param id
     */
    @Delete("delete from user where id=#{id}")
    void delete(@Param("id") Long id);
}

UserController.java

package Controller;

import java.util.List;

import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pojo.User;


@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;

    /**
     * index
     *
     * @return
     */
    @RequestMapping("/db")
    public String index() {
        return "User Info By Mybaties";
    }

    @RequestMapping("/user/listAllUsers")
    public Object allUsers() {
        List users = userMapper.findList();
        return users;
    }

}

Application.java

package Controller;

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

@SpringBootApplication
@MapperScan(basePackages = {"mapper"}) // 自动扫描mapper
@EnableTransactionManagement//启用事物管理,在service上使用@Transactional(注意是spring的 注解)
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        System.out.println("spring boot 启动成功!");
    }
}

application.properties

#修改tomcat的默认的端口号,将8080改为8889
server.port=8889

#启用shutdown endpoint的HTTP访问
endpoints.shutdown.enabled=true 

#不需要用户名密码验证
endpoints.shutdown.sensitive=false

#默认curvar值
curvar=default.curvar

#切换配置文件
spring.profiles.include: prd,prddb


#==================DataSource Config Start==================
#name
#url
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
#DriverClass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#DB username
spring.datasource.username=root
#DB password
spring.datasource.password=root
#==================DataSource Config End==================

#==================mybaties Config Start==================
#ORM Bean Package
mybatis.type-aliases-package=pojo
mybatis.mapper-locations=classpath:/mapper/*.xml
#打印mybatiesSql语句
logging.level.com.example.mapper=DEBUG
#==================mybaties Config End  ==================

UserMapperTest.java

import java.util.List;

import mapper.UserMapper;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import pojo.User;


@SpringBootTest
public class UserMapperTest extends BaseTest{
    @Autowired
    private UserMapper userMapper;

    public void testInsert() {
        try {
            userMapper.insert(new User("man1", "男", 26));
            userMapper.insert(new User("man2", "男", 23));
            userMapper.insert(new User("man2", "男", 27));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testUpdate() {
        try {
            User user = new User("测试0000", "男", 23);
            user.setId(1l);
            userMapper.update(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testQuery() {
        try {
            List users=userMapper.findList();
            for(User u:users){
                System.out.println("ID:"+u.getId()+" Name:"+u.getUserName()+" Sex:"+u.getUserSex()+" Age:"+u.getUserAge());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testDelete(){
        try {
            userMapper.delete(1l);
            testQuery();
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}

test数据库的user表在运行前状态:
springBoot 入门(五)—— 使用 纯注解方式 的springboot+ mybatis+junit4 整合_第1张图片

通过 junit进行插入3条记录:

import java.util.List;

import Controller.Application;
import mapper.UserMapper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import pojo.User;

@SpringBootTest(classes = {Application.class})
public class UserMapperTest extends BaseTest{
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testInsert() {
        try {
            userMapper.insert(new User("man1", "男", 26));
            userMapper.insert(new User("man2", "男", 23));
            userMapper.insert(new User("man2", "男", 27));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void testUpdate() {
        try {
            User user = new User("测试0000", "男", 23);
            user.setId(11l);
            userMapper.update(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void testQuery() {
        try {
            List users=userMapper.findList();
            for(User u:users){
                System.out.println("ID:"+u.getId()+" Name:"+u.getUserName()+" Sex:"+u.getUserSex()+" Age:"+u.getUserAge());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void testDelete(){
        try {
            userMapper.delete(11l);
            testQuery();
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}

springBoot 入门(五)—— 使用 纯注解方式 的springboot+ mybatis+junit4 整合_第2张图片

测试update

springBoot 入门(五)—— 使用 纯注解方式 的springboot+ mybatis+junit4 整合_第3张图片

测试 query all

springBoot 入门(五)—— 使用 纯注解方式 的springboot+ mybatis+junit4 整合_第4张图片

测试delete

这里写图片描述

最后,启动spring boot
测试Controller
springBoot 入门(五)—— 使用 纯注解方式 的springboot+ mybatis+junit4 整合_第5张图片

测试成功!

你可能感兴趣的:(spring,boot)