學習springboot整合mybatis並編寫測試類


報名立減200元。暑假直降6888。

邀請鏈接:http://www.jnshu.com/login/1/20535344

邀請碼:20535344

遇到的問題:

1.原因是在啟動類上只有一個@MapperScan注解。需要配置這個注解的basePackages。

@MapperScan(basePackages = {"com.chenxin.springboot_0702"})

之后刪除掉@EnableAutoConfiguration和@ComponentScan(basePackages = {"com.chenxin.springboot_0702"})也照樣運行成功。

 第二個問題:測試類 里面用@Autowired注解自動裝配UserMapper時會有提示報錯,但是執行起來沒有問題,可以通過。

改成@Resource注解則沒有紅線了。

      

 

 

首先配置pom.xml文件。springboot的項目都是jar包,不是war包。還有就是依賴模塊spring-boot-starter-jdbc不需要,因為在mybatis-spring-boot-starter中已經包含了。

<?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>com.chenxin</groupId>
    <artifactId>springboot_0702</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_0702</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Junit依賴 -->
        <!--junit不需要springboot已經自動加載了。-->
     <!--spring-boot-starter-jdbc已經包含在了mybatis-spring-boot-starter中了。-->
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.5</version> </dependency> <!--引入mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <!--mybatis分頁插件--> <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

application.properties

#配置mysql的連接配置
spring.datasource.url=jdbc:mysql://localhost:3306/testx
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

接着是model類。

| users | CREATE TABLE `users` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(45) NOT NULL,
  `password` varchar(145) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `courseId` int(11) DEFAULT NULL,
  `image` varchar(150) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `createdAt` bigint(20) DEFAULT NULL,
  `updatedAt` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`) USING HASH
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 |

import java.io.Serializable;

public
class User implements Serializable { private long id; private String userName; private String password; private String name; private int courseId; private String image; private String email; private String address; private String phone; private long createdAt; protected long updatedAt; public User() { } //其他getter和setter
   //toString方法
}

然后是mapper類。

import com.chenxin.springboot_0702.model.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.StatementType;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper {

    @Select("select * from users")
    public List<Map> findAll();

}

接着說springboot啟動類。最開始提過了在這里只用了springboot整合mybatis和mysql。所以@ComponentScan和@EnableAutoConfiguration。

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

@SpringBootApplication
//開啟通用注解掃描
//@ComponentScan(basePackages = {"com.chenxin.springboot_0702"})
@MapperScan(basePackages = {"com.chenxin.springboot_0702"})
//@EnableAutoConfiguration
public class Run {

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

 測試類

import com.chenxin.springboot_0702.dao.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Run.class)
@EnableAutoConfiguration
public class RunTests {
    @Resource
    private UserMapper userMapper;

    @Test
    public void contextLoads() {
    }


    @Test
    public void G() {
        System.out.println(userMapper.findAll());
    }
}

 

接下來是其他的增刪改查。其中更新使用的@Update注解,貌似可以自動判斷是否為空,只要為空就不更新了。

import com.chenxin.springboot_0702.model.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.StatementType;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper {

    //查詢
    @Select("select * from users where id = #{id}")
    public User findById(@Param("id") long id) throws Exception;

    @Select("select * from users")
    public List<User> findAll() throws Exception;

    @Select("select * from users where phone=#{phone}")
    public List<User> findByPhone(@Param("phone") String phone) throws Exception;

    //新增
    @Insert("INSERT INTO users(id,username,password,name,courseId,image,email,address,phone,createdAt,updatedAt) VALUES (#{id},#{username},#{password},#{name},#{courseId},#{image},#{email},#{address},#{phone},#{createdAt},#{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    public int add(User user) throws Exception;

    //刪除
    @Delete("delete from users where id = #{id}")
    public boolean delete(@Param("id") long id) throws Exception;

    //更新
    @Update("update users set username=#{username}, password=#{password}, name=#{name}, courseId=#{courseId}, image=#{image}, email=#{email}, address=#{address}, phone=#{phone}, updatedAt=#{updatedAt} where id=#{id}")
    public boolean update(User user) throws Exception;
}

測試單元

import com.chenxin.springboot_0702.dao.UserMapper;
import com.chenxin.springboot_0702.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Run.class)
@EnableAutoConfiguration
public class RunTests {
    
    @Resource
    private UserMapper userMapper;
    
    @Test
    public void G() throws Exception {
        System.out.println(userMapper.findAll());
    }
    @Test
    public void g1() throws Exception {
        System.out.println(userMapper.findById(12L));
    }
    @Test
    public void g3() throws Exception {
        User user = new User();
        user.setName("無極");
        user.setUsername("六六qijiu");
        user.setPassword("12443345");
        userMapper.add(user);
        System.out.println(user.getId());
    }
    @Test
    //刪除
    public void g4() throws Exception{
        long id = 14;
        System.out.println(userMapper.delete(id));
    }

    @Test
    //更新
    public void g5() throws Exception{
        User user = userMapper.findById(16);
        user.setUsername("七七七");
        System.out.println(userMapper.update(user));
    }
    @Test
    public void g6() throws Exception{
        List<User> users = userMapper.findByPhone("13101436674");
        for (User user : users)
            System.out.println(user.getId() + "***" + user.getPhone());
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM