博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot--整合MyBatis(注解方式)
阅读量:2442 次
发布时间:2019-05-10

本文共 9026 字,大约阅读时间需要 30 分钟。

整合MyBatis(注解方式)

Users表结构

CREATE TABLE `users` (  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',  `username` varchar(32) DEFAULT NULL COMMENT '用户名',  `password` varchar(32) DEFAULT NULL COMMENT '密码',  `sex` varchar(32) DEFAULT NULL,  `nick_name` varchar(32) DEFAULT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `username` (`username`) USING HASH) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;

添加pom文件

4.0.0
com.lynch.springboot
spring-boot-mybatis-annotation
0.0.1-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
1.5.10.RELEASE
UTF-8
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
com.github.pagehelper
pagehelper-spring-boot-starter
1.1.1
mysql
mysql-connector-java
org.springframework.boot
spring-boot-devtools
true
org.springframework.boot
spring-boot-maven-plugin

application.properties 添加相关配置

#mybatis.type-aliases-package=com.lynch.entityspring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://192.168.1.149:3306/aa?useUnicode=true&characterEncoding=utf-8&useSSL=falsespring.datasource.username = rootspring.datasource.password = attack

springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对于开发人员不用管,直接拿来使用即可。

在启动类中添加对mapper包扫描@MapperScan

package com.lynch;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.lynch.mapper")public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args); }}

或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种,不然每个mapper加个注解也挺麻烦的。

Mapper

package com.lynch.mapper;import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.InsertProvider;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.SelectProvider;import org.apache.ibatis.annotations.Update;import org.apache.ibatis.annotations.UpdateProvider;import com.lynch.entity.UserEntity;import com.lynch.enums.SexEnum;public interface UserMapper {
@Select("SELECT * FROM users") @Results({
@Result(property = "sex", column = "sex", javaType = SexEnum.class), @Result(property = "nickName", column = "nick_name") }) List
getAll(); @Select("SELECT * FROM users WHERE id = #{id}") @Results({
@Result(property = "sex", column = "sex", javaType = SexEnum.class), @Result(property = "nickName", column = "nick_name") }) UserEntity getOne(Long id); @Insert("insert into users(username,password,sex) values(#{username}, #{password}, #{sex})") int insert(UserEntity user); @Update("UPDATE users SET userName=#{username},nick_name=#{nickName} WHERE id =#{id}") void update(UserEntity user); @Delete("DELETE FROM users WHERE id =#{id}") void delete(Long id); @InsertProvider(type=UserProvider.class, method = "batchInsert") int batchInsert(@Param("userList")List
userList); @SelectProvider(type = UserProvider.class, method = "queryUser") @Results({
@Result(property = "sex", column = "sex", javaType = SexEnum.class), @Result(property = "nickName", column = "nick_name") }) public List
queryUser(UserEntity user); @UpdateProvider(type = UserProvider.class, method = "updateUser") public int updateUser(@Param("U")UserEntity user);}
package com.lynch.mapper;import java.util.List;import java.util.Map;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.jdbc.SQL;import com.github.pagehelper.util.StringUtil;import com.lynch.entity.UserEntity;/** * 利用@Provider实现动态SQL *  * @author Lynch * */public class UserProvider {
public String queryUser(UserEntity user) {
StringBuffer sql = new StringBuffer("select * from users where 1=1 "); if(StringUtil.isNotEmpty(user.getUsername())) {
sql.append(String.format("and username like '%s'", "%"+user.getUsername()+"%")); } return sql.toString(); } public String batchInsert(Map map) {
List
userList = (List
)map.get("userList"); StringBuffer sql = new StringBuffer("insert into users (username,password) values "); for(UserEntity user : userList) {
sql.append(String.format("('%s', '%s'),", user.getUsername(), user.getPassword())); } sql = sql.deleteCharAt(sql.length() -1); System.out.println(sql.toString()); return sql.toString(); } public String updateUser(@Param("U")UserEntity user) {
SQL sql = new SQL(){
{
UPDATE("users"); if (StringUtil.isNotEmpty(user.getNickName())){
SET("nick_name = #{U.nickName}"); } WHERE("id = #{U.id}"); }}; return sql.toString(); } }

注意,使用#符号和$符号的不同:

// This example creates a prepared statement, something like select * from teacher where name = ?;@Select("Select * from teacher where name = #{name}")Teacher selectTeachForGivenName(@Param("name") String name);// This example creates n inlined statement, something like select * from teacher where name = 'someName';@Select("Select * from teacher where name = '${name}'")Teacher selectTeachForGivenName(@Param("name") String name);

单元测试

package com.lynch.mapper;import java.util.ArrayList;import java.util.List;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 com.lynch.entity.UserEntity;import com.lynch.enums.SexEnum;@RunWith(SpringRunner.class)@SpringBootTestpublic class UserMapperTest {
@Autowired private UserMapper userMapper; @Test public void insert() throws Exception {
int result = 0; try {
result = userMapper.insert(new UserEntity("lisi", "123456", SexEnum.MAN)); } catch (Exception e) {
System.out.println(e.getMessage().indexOf("ConstraintViolationException")); } System.out.println("result=" + result); } @Test public void batchInsert() throws Exception {
List
userList = new ArrayList
(); userList.add(new UserEntity("a","a",SexEnum.MAN)); userList.add(new UserEntity("c","b",SexEnum.MAN)); userList.add(new UserEntity("b","b",SexEnum.WOMAN)); System.out.println("result=" + userMapper.batchInsert(userList)); } @Test public void getAll() throws Exception {
List
users = userMapper.getAll(); System.out.println(users.toString()); } @Test public void testUpdate() throws Exception {
UserEntity user = userMapper.getOne(45L); System.out.println(user.toString()); user.setNickName("neo"); user.setSex(SexEnum.WOMAN); userMapper.update(user); } @Test public void queryUser() throws Exception {
UserEntity user = new UserEntity(); user.setUsername("l"); System.out.println(userMapper.queryUser(user)); } @Test public void updateUser() throws Exception {
UserEntity user = new UserEntity(); user.setId(45L); user.setNickName("aaa"); System.out.println(userMapper.updateUser(user)); }}

转载地址:http://zzpqb.baihongyu.com/

你可能感兴趣的文章
如何在Nintendo Switch上禁用锁定屏幕
查看>>
word文档属性自定义_如何在Word文档中插入内置和自定义高级属性
查看>>
ucos在pc上运行_这是什么过程,为什么要在我的PC上运行?
查看>>
mac快速预览文件_教快速外观以预览Mac上不支持的视频和其他文件
查看>>
android wi-fi_如何使Android Auto更依赖弱Wi-Fi(就像在车道上一样)
查看>>
imac pro 接显示器_您应该购买iMac Pro,还是等待模块化Mac Pro重新设计?
查看>>
如何在Nintendo交换机上显示电池百分比
查看>>
connect by 循环_如何与Connect一起循环或链接多个String化流
查看>>
hue添加hbase_如何将Philips Hue小部件添加到Android主屏幕
查看>>
linux窗口切换快捷键_分配快捷键以在Linux上激活打开的应用程序窗口
查看>>
网件路由器usb存储共享_如何共享对Netgear Arlo相机的访问权限
查看>>
ios 获取语言_如何获取iOS的自动更正以多种语言工作
查看>>
如何在VMware中的预分配磁盘和可增长磁盘之间转换
查看>>
鼠标无边界设置方法_如何在无边界鼠标的多台计算机上使用一个鼠标和键盘
查看>>
synology nfs_如何备份和还原Synology NAS配置
查看>>
如何检查iPhone或iPad是否存在无法在iOS 11上运行的32位应用程序
查看>>
在Windows 7、8、10或Vista中打开远程桌面
查看>>
instagram滤镜pc_如何使用Instagram新面Kong滤镜
查看>>
中画幅相机焦距水平视角_摄影中的“中画幅”是什么?
查看>>
macbook 触控栏fn_遇到问题时,如何重置MacBook的触控栏
查看>>