Skip to content

Spring Data JPA(二)

sqmax edited this page Jun 10, 2018 · 1 revision

项目中的与数据表对应的实体类都放在com.imooc.dataobject下,它们都使用了@Entity这个注解(这个注解的来源于javax.persistence包),类名按照驼峰式的写法和数据表对应,当然我们也可以使用@Table注解指定。如下:

@Entity
@DynamicUpdate
@Data
//@Table(name = "product_category")
public class ProductCategory {
    /**类目id.**/
    @Id
    @GeneratedValue
    private Integer categoryId;
    /**类目名字**/
    private String categoryName;
    /** 类目编号**/
    private Integer categoryType;

    private Date createTime;

    private Date updateTime;
}

同时各主键又使用了@Id注解。可以看到类上还使用了@DynamicUpdate注解。建表语句如下:

create table `product_category` (
	`category_id` int not null auto_increment,
	`category_name` varchar(64) not null comment '类目名字',
	`category_type` int not null comment '类目编号',
	`create_time` timestamp not null default current_timestamp comment '创建时间',
	`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
	primary key (`category_id`)
);

可以看到update_time列有on update current_timestamp,所以当我们使用下面方式

ProductCategory productCategory =repository.findOne(2);
productCategory.setCategoryType(5);
ProductCategory result=repository.save(productCategory);
        

更新数据时,在数据库中该列就会自动更新。

Clone this wiki locally