我有一个状态值很少的枚举
新增,已审核,已发布,待处理,已更新,垃圾邮件,重复项,无关紧要,未发布
我不想像枚举那样使用它们,因此为此创建了一个实体.为了方便起见,我想在实体中保留一列以从枚举中初始化状态并将该枚举值转换为状态实体的对象.为了这..
我有两个实体.我想引用具有来自另一个实体的值的列.
基本上我想用公式初始化一个对象.
实体是
@Entity
@Table(name = "event_status")
public class EventStatus {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="eventStatusId")
private Integer eventStatusId;
@Enumerated(EnumType.STRING)
@Column(unique = true,name="eventStatusType")
private EventStatusType eventStatusType;
public EventStatus() {
this(EventStatusType.NEW);
}
public EventStatus(EventStatusType eventStatusType) {
super();
this.eventStatusType = eventStatusType;
}
public Integer getEventStatusId() {
return eventStatusId;
}
public EventStatusType getEventStatusType() {
return eventStatusType;
}
public void setEventStatusId(Integer eventStatusId) {
this.eventStatusId = eventStatusId;
}
public void setEventStatusType(EventStatusType eventStatusType) {
this.eventStatusType = eventStatusType;
}
}
我有另一个实体,我在其中引用该实体的对象
@Entity
@Table(name = "event_")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Event implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id_")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Transient
public EventStatusType eventStatusType = EventStatusType.NEW;
@ManyToOne(fetch = FetchType.EAGER, targetEntity = EventStatus.class)
@Formula("select * from event_status where eventStatusId= 1")
private EventStatus status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public EventStatus getStatus() {
System.out.println("Event.getStatus() " + status);
return status;
}
public void setStatus(EventStatus status) {
System.out.println("Event.setStatus()");
this.status = status;
}
}
这不会产生任何异常,但不会初始化此值.
是否可以在事件实体中使用eventStatusType的值初始化此EntityStatus
解决方法:
Sometimes, you want the Database to do some computation for you rather than in the JVM, you might also create some kind of virtual column. You can use a SQL fragment (aka formula) instead of mapping a property into a column. This kind of property is read only (its value is calculated by your formula fragment).
@Formula("obj_length * obj_height * obj_width")
public long getObjectVolume()
The SQL fragment can be as complex as you want and even include subselects.
…
…
Note
You can use a SQL fragment to simulate a physical join column using the @JoinColumnOrFormula / @JoinColumnOrformulas annotations (just like you can use a SQL fragment to simulate a property column via the @Formula annotation).
@Entity
public class Ticket implements Serializable {
@ManyToOne
@JoinColumnOrFormula(formula="(firstname + ' ' + lastname)")
public Person getOwner() {
return person;
}
...
}
另外,我们应该使用insertable = false,可更新= false,因为这样的映射不可编辑
标签:jpa,hibernate,java
来源: https://codeday.me/bug/20191121/2050828.html