Mybatis-Plus中怎么實現(xiàn)自動填充,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
1、為需要自動填充的屬性添加注解 @TableField
提供了4種自動填充策略:DEFAULT,默認(rèn)不處理。INSERT,插入填充字段。UPDATE,更新填充字段。INSERT_UPDATE,插入和更新填充字段。
@Datapublic class User { private Long id; private String name; private Integer age; private String email; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime;}
2、實現(xiàn)字段填充控制器,編寫自定義填充規(guī)則
實現(xiàn) MetaObjectHandler 接口,實現(xiàn) insertFill 和 updateFill 方法,此處的 create_time 和update_time字段需要插入時填充值, 只有 update_time 字段在修改時需要填充,所以策略如下。
//需要將自定義填充控制器注冊為組件@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler { private static final Logger LOGGER= LoggerFactory.getLogger(MyMetaObjectHandler.class); //insert操作時要填充的字段 @Override public void insertFill(MetaObject metaObject) { LOGGER.info("start insert fill ..."); //根據(jù)屬性名字設(shè)置要填充的值 this.setFieldValByName("createTime",new Date(),metaObject); this.setFieldValByName("updateTime",new Date(),metaObject); } //update操作時要填充的字段 @Override public void updateFill(MetaObject metaObject) { LOGGER.info("start insert fill ..."); this.setFieldValByName("updateTime",new Date(),metaObject); }}
3、插入數(shù)據(jù)測試
@RunWith(SpringRunner.class)@SpringBootTestpublic class CRUDTest { @Autowired private UserMapper userMapper; @Test public void testInsert(){ User user = new User(); user.setName("jack11"); user.setAge(20); user.setEmail("4849111@qq.com"); int result= userMapper.insert(user); System.out.println(result); System.out.println(user); } }
4、修改數(shù)據(jù)測試
@Testpublic void testUpdate(){ User user = new User(); user.setId(2L); user.setName("Jackie"); int result = userMapper.updateById(user); System.out.println(result);}
一次插入數(shù)據(jù)后,create_time和update_time都被填充了設(shè)置的時間,做update操作后只有update_time的進(jìn)行了填充修改。
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,的支持。
網(wǎng)站題目:Mybatis-Plus中怎么實現(xiàn)自動填充-創(chuàng)新互聯(lián)
文章出自:http://www.rwnh.cn/article10/cechgo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、網(wǎng)站收錄、外貿(mào)建站、網(wǎng)站設(shè)計公司、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容