学习springboot整合mybatis并编写测试类
遇到的问题:
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 {@Resourceprivate UserMapper userMapper;@Testpublic void contextLoads() {}@Testpublic 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 {@Resourceprivate UserMapper userMapper;@Testpublic void G() throws Exception {System.out.println(userMapper.findAll());}@Testpublic void g1() throws Exception {System.out.println(userMapper.findById(12L));}@Testpublic 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));}@Testpublic void g6() throws Exception{List<User> users = userMapper.findByPhone("13101436674");for (User user : users)System.out.println(user.getId() + "***" + user.getPhone());} }
原文地址:https://www.cnblogs.com/JasonChen92/p/9259629.html
转载于:https://www.cnblogs.com/jpfss/p/11375538.html
学习springboot整合mybatis并编写测试类相关推荐
- SpringBoot整合Mybatis超详细流程
SpringBoot整合Mybatis超详细流程 文章目录 SpringBoot整合Mybatis超详细流程 前言 详细流程 0.引入Mybatis 1.创建数据 2.创建程序目录 3.理解后台访问流 ...
- SpringBoot整合Mybatis(高级)
SpringBoot整合Mybatis(高级) 文章目录 SpringBoot整合Mybatis(高级) 前言 基础环境配置 增删改查 ResultMap 复杂查询 多对一 一对多 动态SQL if ...
- 【SpringBoot整合Mybatis】数据库某字段值为空时,接口未返回该字段 解决办法
[SpringBoot整合Mybatis]数据库字段为空时,接口不返回该字段 解决办法 问题描述: 排查问题: 解决问题: 测试: 参考资料: 今天整合项目的时候,发现了SpringBoot整合Myb ...
- (一)SpringBoot 整合 MyBatis
一.工具 IDE:idea.DB:mysql 二.创建SpringBoot工程 在Idea中使用SpringInitializr模板创建SpringBoot工程,依赖选择如下: 这里也可以不选JDBC ...
- springboot整合mysql5.7_详解SpringBoot整合MyBatis详细教程
1. 导入依赖 首先新建一个springboot项目,勾选组件时勾选Spring Web.JDBC API.MySQL Driver 然后导入以下整合依赖 org.mybatis.spring.boo ...
- springboot整合Mybatis例子
上一篇介绍了使用spring-data-jpa来实现数据的持久化及展示,现在使用比较流行的Mybatis来整合springboot,这里通过一个完整的例子来展示.实现数据的录入,展示以及按条件查询,同 ...
- SpringBoot(二):详细讲解SpringBoot整合MyBatis
IDEA版SpringBoot整合MyBatis 整合mybatis需要的jar包 <dependency><groupId>org.projectlombok</gro ...
- springboot整合mybatis
3.springboot整合mybatis 首先新建一个项目,勾选上我们需要的 1.springboot配置数据库连接池druid druid学习地址 https://github.com/aliba ...
- SpringBoot整合Mybatis演示
SpringBoot整合Mybatis演示 1.环境准备 JDK 1.8 MySQL 5.7 Maven 3.6.3 Idea 2020.1.1 数据库模拟数据准备: CREATE DATABASE ...
- Springboot整合mybatis plus生成代码
一.Springboot整合mybatis plus生成代码 1.介绍 1.1.前言 从零开始搭建一个项目骨架,最好选择合适熟悉的技术,并且在未来易拓展,适合微服务化体系等.所以一般以Springbo ...
最新文章
- 多版本号并发控制(MVCC)在分布式系统中的应用
- linux文件目录详细介绍
- mysql数据库存储数据的过程_[数据库]MySql存储过程总结
- objective-C 自定义对象归档的实现
- Linux查看系统信息的一些命令及查看已安装软件包的命令
- WPF在不同.Net版本间的兼容性问题
- 南京软件测试自学英语,南京软件测试门槛高吗?南京软件测试学哪些
- 【WCF】WCF简介
- matlab 运行 释放内存,怎么能释放已经使用的内存
- [转贴]Linux新增用户和组
- rcmd–App Switcher for Mac快速切换应用程序
- Centos 6.3中安装KVM
- perl python json_JSON Perl
- 使用模板文件流形式导出文件破损或xxx中的部分内容有问题。解决
- usb驱动错误导致的键盘鼠标失灵
- 天地图三维帮助文档(Cesium)
- 使用Selenium对QQ邮箱登录页面进行自动化测试
- 用数学思想演绎的一些系统概念
- gbk英文占几个字节
- python人脸特征提取_Python实现识别人脸特征并打印出来