我有一个带有多个参数的 JPA/EclipseLink 模型,这些参数的值由 PostgreSQL 数据库设置为默认值。具体来说,我有:
SERIAL
类型的id
列,在添加新行时自动递增- 类型为
TIMESTAMP
的created_at
列,默认为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
}
当我尝试在 javax.persistence.EntityManager
中使用 persist()
插入一行时,插入失败,因为 NULL
值为为 created_at
列设置。我不想插入 NULL
,而是不想在该列中插入任何内容,并允许 PostgreSQL 将其设置为 now()
。本质上,我想在 createdAt
上使用 @GeneratedValue
,但该注释仅用于主键,不能用于多个属性。我可以使用另一个注释来完成此操作吗?
最佳答案
您可能希望在 Column
注释中使用 insertable=false
:
@Column(name="created_at", insertable=false)
private java.sql.Timestamp createdAt;
发件人:http://docs.oracle.com/javaee/5/api/javax/persistence/Column.html
boolean insertable (Optional) Whether the column is included in SQL INSERT statements generated by the persistence provide
关于java - 使用 JPA 跳过有关 INSERT 的专栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939475/