之前介绍过SSM的简单demo,当中是自己编写sql statement,还有一种方式是使用封装好的框架忙我们完成常用的CURD操作,就是使用tk.mybatis。
第1步,引入依赖
<dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency>
第2步,添加映射实体
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Id; import javax.persistence.Table; import java.math.BigDecimal; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor @Table(name = "book") public class BookInfo { @Id //标识主键,否则查不数据 private Integer bookId; private String bookName; private String bookAuthor; private BigDecimal bookPrice; private Date bookDate; }
第3步,创建interface所有mapper基类 BaseMapper.java
import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; /** * 项目中所有Mapper类的父类 * @param <T> */ public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> { }
同时,在application.yml中添加mapper的基类
mapper: identity: MYSQL mappers: - tk.mybatis.mapper.common.Mapper - tk.mybatis.mapper.common.MySqlMapper not-empty: true
第4步,添加@MapperScan注解,指定mapper的包路径。
import com.mike.boot.boot.bootssmtkmybatis.domain.BookInfo; import com.mike.boot.boot.bootssmtkmybatis.mapper.BookMapper; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication @MapperScan("com.mike.boot.boot.bootssmtkmybatis.mapper")//指定Mapper扫描的包,支持扫描多个包 public class BootSsmTkMybatisApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(BootSsmTkMybatisApplication.class, args); BookMapper bookMapper = context.getBean(BookMapper.class); BookInfo bookInfo = bookMapper.selectByPrimaryKey(2); System.out.println(bookInfo); context.close(); } }
tk_mapper封装了大量的操作方法,可以直接拿过来使用。
标签:mapper,boot,private,SSM,TK,整合,mybatis,import,tk From: https://www.cnblogs.com/lfhappy/p/17422063.html