我正在尝试将数据插入表中,其中一个字段是FK到另一个表。问题是使用JPA和Criteria来执行操作我想避免必须填写整个子对象来执行此操作。 例如:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="SENSOR_ID", nullable=false, updatable=false)
private Sensor sensor;
public Sensor getSensor() {
return sensor;
}
public void setSensor(Sensor sensor) {
this.sensor = sensor;
}
em.getTransaction().begin();
Measure m = new Measure();
m.setDeformation(measure.getDeformation());
m.setMoment(timestamp);
m.setTemperature(measure.getTemperature());
m.setTension(measure.getTension());
m.setSensorId(measure.getSensorId()); // I would like to do it like this and not having to use m.setSensor();
em.persist(m);
答案 0 :(得分:4)
如果传感器映射在Measure中,如示例所示:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="SENSOR_ID", nullable=false, updatable=false)
private Sensor sensor;
您需要填充传感器实例。传感器未通过度量保存,因为默认情况下不会级联任何操作。在调用它之前必须保存它。
要不填充整个传感器,请在Measure类中使用sensor_id FK而不是Sensor。
@Column(nullable = true)
private Long sensor_id;
要使用两者,必须是只读的:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="SENSOR_ID", updatable=false, insertable = false)
private Sensor sensor;