spring boot 整合mybatis 通用mapper與分頁外掛
阿新 • • 發佈:2019-01-29
之前開發的時候一直使用mybatis程式碼生成器生成單表crud,一旦資料庫表字段出現修改就要重新生成一次xml或者手動修復,容易出現錯誤以及麻煩。新專案就換了個方式程式碼生成器只生成xml以及整合對映,crud改用通用mapper並使用pagehelper做分頁。
yml
mybatis: mapper-locations: classpath:com/api/web/**/mapper/*.xml configuration: callSettersOnNulls: true defaultStatementTimeout: 180 mapper: mappers:com.api.util.mapper.MyMapper not-empty: false identity: ORACLE pagehelper: helperDialect: oracle reasonable: true supportMethodsArguments: true params: count=countSql
pom
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.1.4</version> </dependency>
程式碼
public class BaseEntity { @Id @Column(name = "Id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Transient private Integer page = 1; @Transient private Integer rows = 10; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getRows() { return rows; } public void setRows(Integer rows) { this.rows = rows; } }
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> { }
這裡注意,MyMapper<T>不能被springboot掃描到。
entity
Table指定資料庫表面 @id主鍵 屬性名預設就是開啟駝峰的
@Data
@Table(name ="TB_KS_PUNISH_LOG") public class PunishLog { @Id private String plushId; private String areaCode; private String netbarWacode;}
dao
簡單繼承MyMapper類即可
/** * @author lcc */ public interface PunishLogMapper1 extends MyMapper<PunishLog> {}
service
分頁外掛非常方便,攔截mybatis sql 執行前加入分頁的sql
PageHelper.startPage(page, rows); Example example = new Example(PunishLog.class); example.createCriteria().orEqualTo("netbarWacode", punishLogAttach.getNetbarWacode());