zoukankan      html  css  js  c++  java
  • spring boot JPA中实体类常用注解

    spring boot jpa中的注解很多,参数也比较多。没必要全部记住,但是经常查看官方文档也比较麻烦,记录一下一些常用的注解。通过一些具体的例子来帮助记忆。

    @Entity
    @Table(name = "flow")
    @SQLDelete(sql = "update flow set deleted = 1 where id = ?")
    @Where(clause = "deleted = 0")
    public class Flow {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    @Column(updatable = false)
    private Date createTime;
    private Date operateTime;
    @PrePersist
    protected void onCreate() {
    createTime = new Date();
    }
    @PreUpdate
    protected void onUpdate() {
    operateTime = new Date();
    }
    @Column(columnDefinition = "TEXT")
    private String message;
    private deleted = 0;
    }

      

    1、Entity 表示这个类是一个实体类,对应数据库中的一个表

    2、@Table 指定这个类对应数据库中的表名。如果这个类名的命名方式符合数据库的命名方式,可以省略这个注解。如FlowType类名对应表名flow_type。

    3、@Id 指定这个字段为表的主键

    4、@GeneratedValue(strategy=GenerationType.IDENTITY) 指定主键的生成方式,一般主键为自增的话,就采用GenerationType.IDENTITY的生成方式

    5、@Column(updatable = false) @Columun 注解针对一个字段,对应表中的一列。有很多参数,name表示对应数据表中的字段名。insertable 表示插入式是否更新。updateable,表示update的时候是否更新;columnDefinition表示字段类型,当使用jpa自动生成表的时候比较有用。

    6、@PrePersist 表示持久化之前执行

    7、@PreUpdate 表示执行Update操作之前执行。

    8、SQLDelete表示当执行jpa中的delete操作时,执行的语句

    9、@Where 当执行查询语句时,会附带这个条件。这个和上面的一起使用,可以实现软删除

    上述代码表示数据库中有一个表名为flow的表。主键为id,为自增。createTime为创建时间,当第一次插入的时候产生时间,后续不会随着update变动。而operateTime仅在Update的时候更新。message是String类型,默认创建的字段为Varchar类型,这里指定为TEXT。

    我们创建数据库的时候,推荐每个表都要有创建时间和更新时间,但是没必要每个表都写重复的代码,可以用下面的注解来解决

    @MappedSuperclass
    public class BaseEntity implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        protected Long id;
    
        @Column(updatable = false)
        private Date createTime;
        private Date updateTime;
    
        @PrePersist
        protected void onCreate() {
            createTime = new Date();
        }
    
        @PreUpdate
        protected void onUpdate() {
            updateTime = new Date();
        }
    

      

    10、@MappedSuperclass 表示一个这是一个父类,不会被当成一个实体类。在这里定义一些表中的通用字段。然后其他实体类继承这个类就可以了,避免写重复代码。

  • 相关阅读:
    Ubuntu 系统下载
    Shell 变量自增实现方法
    shell 单引号以及双引号
    A look at WeChat security
    利用HTTP Cache来优化网站
    require.js 简洁入门
    Nginx rewrite URL examples with and without redirect address
    页面制作部分之PS切图
    Joda-Time 简介
    [官方摘要]Setup And Configuration memcached with Tomcat
  • 原文地址:https://www.cnblogs.com/lilinwei340/p/9868044.html
Copyright © 2011-2022 走看看