pom引入依赖:
<dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>2.1.5</version></dependency><dependency><groupId>tk.mybatis</groupId><artifactId>mapper</artifactId><version>4.1.5</version></dependency>
定义通用mapper基类
import tk.mybatis.mapper.common.ConditionMapper;
import tk.mybatis.mapper.common.Mapper;/*** description 定制版MyBatis Mapper插件接口,如需其他接口参考官方文档自行添加。** @author ceshi* @version 1.0*/
public interface TkMapper<T>extends Mapper<T>,ConditionMapper<T> {
}
properties文件配置
#配置实体类所在包
mybatis.type-aliases-package=com.ceshi.account.pojo
#配置xml文件路径
mybatis.mapper-locations=classpath:com/ceshi/account/mapping/*Mapper.xml
#配置Mapper基类全路径
mapper.mappers =com.ceshi.account.config.TkMapper
#配置数据库类型
mapper.identity=PostgreSql
修改启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;@SpringBootApplication
//通用mapper扫描
@MapperScan("com.ceshi.account.mapper")
public class AccountApplication {public static void main(String[] args) {SpringApplication.run(AccountApplication.class, args);}}
注:此处MapperScan为tk.mybatis.spring.annotation.MapperScan,非org.mybatis.spring.annotation.MapperScan;
定义实体类
@Getter
@Setter
@Table(name = "p_menu")
public class TmpMenu {@GeneratedValue(strategy = GenerationType.IDENTITY)private String id;private String code;@Column(name = "menu_name")private String menuName;@Column(name = "parent_id")private String parentId;private String icon;private String url;@Column(name = "sort_number")private Integer sortNumber;private String remark;@Column(name = "create_user")private String createUser;@Column(name = "create_time")private Date createTime;@Column(name = "update_user")private String updateUser;@Column(name = "update_time")private Date updateTime;
}
注:如果bean实体中含有数据表中不存在的字段,使用@Transient注解
定义mapper
import com.ceshi.account.config.TkMapper;
import com.ceshi.account.pojo.PackingdataMenu;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;import java.util.List;/*** description 菜单表字段DAO** @author szc* @date 2022/05/13*/
@Repository
public interface TmpMenuMapper extends TkMapper<TmpMenu> {/*** 注解sql* @return*/@Select("select * from stream_line")List<PackingdataMenu> getAll();/*** xml定义语句*/PackingdataMenu getById(@Param("mid") String mid);
}
注:mapper中已经继承了TkMapper里面的所有单表操作的增删改查方法,上面的两个方法getAll与getById是我们自定义的方法,一种通过注解定义,另外一种是我们常用的在xml文件里面写方法。