[英]JPA default value if Entity not found
Is there a way to set some (default) value if the entity not found (only if the entity not found - EntityNotFound exception)?如果未找到实体(仅当未找到实体时 - EntityNotFound 异常),有没有办法设置一些(默认)值? If there is a null value in DB, the field must be null.
如果 DB 中有空值,则该字段必须为空。 For example, I have an entity First with relationship to an entity Second:
例如,我有一个实体 First 与实体 Second 有关系:
class First {
...
@ManyToOne @JoinColumn(name="second", nullable=true)
@NotFound(action = NotFoundAction.IGNORE)
Second second;
...
}
if column "second" in DB (Table "First") is null, then first.second must be null.如果 DB 中的列“second”(表“First”)为空,则 first.second 必须为空。 If column "second" in DB (Table "First") is 5 (second id = 5) and there isn't exist row in table "Second" with id == 5 then firts.second should be some default value (entity), for example entity Second with id = 1 or new Second(params);
如果 DB 中的列“second”(表“First”)是 5(第二个 id = 5)并且表“Second”中不存在 id == 5 的行,那么 firts.second 应该是一些默认值(实体) ,例如 id = 1 的实体 Second 或 new Second(params);
I hope you access your fields by pair of get/set methods.我希望您通过一对 get/set 方法访问您的字段。 Just make null-checking logic inside getter:
只需在 getter 中进行空检查逻辑:
public Second getRelated(){
if( second == null )
return defaultValue;
}
Please also see this answer https://stackoverflow.com/a/757330/149818另请参阅此答案https://stackoverflow.com/a/757330/149818
class First {
...
@ManyToOne @JoinColumn(name="second", nullable=true)
@NotFound(action = NotFoundAction.IGNORE)
Second second;
@Column(name = "second", insertable = false, updatable = false)
private Long secondId;
public Second getSecond(){
if (second == null && secondId != null) {
return defaultSecond;
}
return second;
}
}
If you want to change the second
field itself to the default value, then you could add the @PostLoad
callback:如果要将
second
字段本身更改为默认值,则可以添加@PostLoad
回调:
public Second getSecond(){
return second;
}
@PostLoad
private void postLoad() {
if (second == null && secondId != null) {
this.second = defaultSecond;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.