本次源码是基于此篇博文的:https://blog.csdn.net/qq78442761/article/details/95938406
这里要注意的问题是:
当数据库表结构是这样的!
这里就是update_time的默认值为CURRENT_TIMESTAMP
并且还设置了on update属性。也就是当修改数据后,这个属性会被更新。
检索的例子:
@Test
public void findOneTest(){
ProductCategory productCategory = repository.findOne(1);
System.out.println(productCategory);
}
这里是个存储的例子:
@Test
public void saveTest(){
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryName("男生最爱");
productCategory.setCategoryType(1);
repository.save(productCategory);
}
这个是更新操作:
@Test
public void updateTest(){
ProductCategory productCategory = repository.findOne(2);
productCategory.setCategoryType(11);
repository.save(productCategory);
}
这里要注意:
通过这个DynamicUpdate注解,可以实现当某个字段是on update时可以完成更新。
ProductCategory.java
package selldemo.demo.dataobject;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;
@Entity
@DynamicUpdate
public class ProductCategory {
@Id
@GeneratedValue
private Integer categoryId;
private String categoryName;
private Integer categoryType;
private Date createTime;
private Date updateTime;
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Integer getCategoryType() {
return categoryType;
}
public void setCategoryType(Integer categoryType) {
this.categoryType = categoryType;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "ProductCategory{" +
"categoryId=" + categoryId +
", categoryName='" + categoryName + '\'' +
", categoryType=" + categoryType +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
}