[英]How to set default NULL value for a field via Hibernate merge
@Entity
@Table(name = "account")
public class PrepaidAccount implements Account, Serializable {
protected Integer pre_notif_interval;
public Integer getPreNotifInterval() {
return pre_notif_interval;
}
public void setPreNotifInterval(Integer pre_notif_interval) {
this.pre_notif_interval = pre_notif_interval;
}
I need to set NULL (default value against this field). 我需要设置NULL(此字段的默认值)。
How do I do it? 我该怎么做?
From the service where I call, I have some integer value setting working fine - 从我调用的服务中,我可以进行一些整数设置,效果很好-
account.setPreNotifInterval(2);
em.persist(account);
Db schema is - DB模式是-
`pre_notif_interval` tinyint(1) DEFAULT NULL;
1 Object value is null
by default 1对象值默认为null
2 Set field value explicitly protected Integer pre_notif_interval = null;
2设置显式protected Integer pre_notif_interval = null;
字段值protected Integer pre_notif_interval = null;
3 Use Listener like this to set default values: 3像这样使用Listener来设置默认值:
public class EntityListener {
@PrePersist
void prePersistActions(PrepaidAccount account) {
account.setPreNotifInterval(null);
}
@PreUpdate
void preUpdateActions(PrepaidAccount account) {
//some code
}
}
and then 接着
@Entity
@Table(name = "account")
@EntityListeners(EntityListener.class)
public class PrepaidAccount implements Account, Serializable {
protected Integer pre_notif_interval;
public Integer getPreNotifInterval() {
return pre_notif_interval;
}
public void setPreNotifInterval(Integer pre_notif_interval) {
this.pre_notif_interval = pre_notif_interval;
}
}
In order the database will use the default value, that column shouldn't be specified during INSERT
(or a special DEFAULT
keyword shoud be used). 为了使数据库使用默认值,不应在INSERT
期间指定该列(或应使用特殊的DEFAULT
关键字)。 Unfortunately JPA does not support neither approach. 不幸的是,JPA不支持这两种方法。 So a native SQL should be sent, which can be done using FluentJPA : 因此,应该发送本机SQL,可以使用FluentJPA完成:
default PrepaidAccount insertWithDefaults(String required1,
int required2) {
FluentQuery query = FluentJPA.SQL((PrepaidAccount p) -> {
INSERT().INTO(viewOf(p, PrepaidAccount ::getRequired1, Person::getRequired2));
VALUES(row(required1, required2));
// RETURNING(p); //PostgreSQL
// Person inserted = INSERTED(); //SQL Server
// OUTPUT(inserted);
});
// works in MySQL, H2
int nOfUpdated = query.createQuery(getEntityManager()).executeUpdate();
if (nOfUpdated <= 0)
return null;
query = FluentJPA.SQL((PrepaidAccount p) -> {
SELECT(p);
FROM(p);
WHERE(p.getId() == LAST_INSERT_ID());
});
PrepaidAccount prepaid = query.createQuery(getEntityManager(), PrepaidAccount.class)
.getSingleResult();
return prepaid;
}
Note that returning the inserted row or id is vendor specific. 请注意,返回插入的行或ID是特定于供应商的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.