使用 JPA 在 INSERT 上跳过一列

Ecl*_*ica 6 java postgresql jpa eclipselink

我有一个带有多个参数的 JPA/EclipseLink 模型,其值由 PostgreSQL 数据库设置为默认值。具体来说,我有:

  • 添加新行时自动递增的id列类型SERIAL
  • created_at类型的柱TIMESTAMP,默认为now()

我的模型看起来像这样:

import javax.persistence.*;

@Entity
@Table(name="entity")
@NamedQuery(name="Entity.findAll", query="SELECT e from Entity e")
public class Entity {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    @Column(name="created_at")
    private java.sql.Timestamp createdAt;

    // constructor, getters, and setters
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用persist()in插入一行时javax.persistence.EntityManager,插入失败,因为NULL正在为该created_at列设置一个值。NULL我不想插入,而是不想在该列中插入任何内容并允许 PostgreSQL 将其设置为now(). 本质上,我想使用@GeneratedValueon createdAt,但该注释仅适用于主键,不能用于多个属性。我可以使用另一个注释来实现这一点吗?

Gle*_*enn 8

您可能希望insertable=falseColumn注释中:

@Column(name="created_at", insertable=false)
private java.sql.Timestamp createdAt;
Run Code Online (Sandbox Code Playgroud)

来自:http : //docs.oracle.com/javaee/5/api/javax/persistence/Column.html

boolean insertable (Optional) 该列是否包含在持久化提供的 SQL INSERT 语句中