SpringBoot整合通用Mapper

使用通用mapper可以不再写基础的增删改查语句,让mapper.xml只专注复杂的SQL不受大量的基础增删改查语句干扰

pom.xml引入依赖



	tk.mybatis
	mapper-spring-boot-starter
	RELEASE

 

配置文件application.yml,BaseMapper

mybatis:
   type-aliases-package: com.sb.example.*.model
   mapper-locations: classpath:mapper/*.xml
   mappers: com.sb.example.common.util.BaseMapper
   not-empty: false
   identity: MYSQL
package com.sb.example.common.util;

import org.springframework.stereotype.Component;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

@Component
public interface BaseMapper extends Mapper, MySqlMapper {

}

 

mappers 是指向自定以的基础通用mapper接口,该接口不能和普通接口放在一起,推荐放在工具包里,这里要注意Mapper,MySqlMapper都是tk包下的,Mapper提供了基础的增删改查功能,MySqlMapper提供了批量新增的功能,然后使用我们去继承这个mapper就有CRUD的功能

package com.sb.example.flyway.mapper;

import com.sb.example.common.util.BaseMapper;
import com.sb.example.flyway.model.User;

public interface UserMapper extends BaseMapper {

}

然后在启动类上加上MapperScan注解,这个也是tk包下面的,扫描我们的mapper

package com.sb.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import tk.mybatis.spring.annotation.MapperScan;

@MapperScan( basePackages = "com.sb.example.*.mapper")
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
		
	}
}

实体类,使用了lombak插件,可以参考

package com.sb.example.flyway.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@Entity
@Table(schema = "example", name = "user")
@EqualsAndHashCode(callSuper = true)
public class User extends BaseModel {
	private static final long serialVersionUID = 1L;

	@Column(columnDefinition = "varchar(50) COMMENT '姓名'")
	private String name;
	
}

 

你可能感兴趣的:(集成之路)