Java笔记-jpa中数据存储及更新应该注意的问题

140 篇文章 4 订阅
47 篇文章 1 订阅

本次源码是基于此篇博文的: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 +
                '}';
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值