我有一个如下所示的实体结构:
@Entity
public class Event {
@Id
private Long id;
@ManyToOne
private Device device;
@Column
private Severity severity;
... getters/setters/other attrs ...
}
@Entity
public class Device {
@Column
private Impact impact;
@ManyToOne
private PriorityMatrix priorityMatrix;
... getters/setters/other attrs ...
}
@Entity
public class Priority {
@EmbeddedId
private PriorityId id;
@Column
private Long value;
... getters/setters ...
}
@Embeddable
public class PriorityId {
@Column
private Severity severity;
@Column
private Impact impact;
@ManyToOne
private PriorityMatrix matrix;
... getters/setters ...
}
影响和严重性是具有固定值的枚举。
我可以向按设备影响和优先级矩阵以及事件严重性映射的事件实体添加“ transient ”属性“优先级”吗?如果是,怎么办?
在 SQL 中,这将是一些连接,例如
SELECT priority_matrix.priority_value,
-- event attributes
-- device attributes
FROM event
INNER JOIN device ON { -- event x device join }
INNER JOIN priority_matrix ON {
device.priority_matrix_id = priority_matrix.id
AND device.impact = priority_matrix.impact
AND event.severity = priority_matrix.severity
}
我想这样做是因为优先级矩阵可以由不同设备更新和共享,因此在获取事件时必须始终获取优先级值,但我想在加载事件时加载优先级值。
最佳答案
你可以有 transient 对象,但它不会对你的数据库生效,例如在生成的sql中。
//Event class:
@Transient
private Priority priority;
//setter
public void setPriority(Priority p){
//if you need to change/update the persistent object when setting a Priority,
//you could set the mapped fields in this setter
this.device.setImpact(p.getId().getImpact());
this.setServerity(p.getId().getSeverity());
}
//getter
public Priority getPriority(){
//since annotated by Transient annotation,this will NOT return persistent object.
// but you could get the transient Priority object and then load it in future
Priority p = new Priority();
//create a PriorityId object
priorityId.set(..this.device..this.severity..)
p.setPriorityId(priorityId);
p.setValue(...);
...
return p; //transient object!
}
上面的代码不是用IDE编写的,可能有错别字,但它表达了想法。
关于java - 实体属性可以被同一实体的其他属性映射吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9739905/