简体   繁体   English

使用JPA插入记录,该记录具有一个字段作为另一个表的外键

[英]insert record with JPA having a field as an foreign key to another table

I am trying to insert data into a table and one of the fields is an FK to a different table. 我正在尝试将数据插入表中,并且其中一个字段是另一个表的FK。 The problem is that using JPA and Criteria to perform the operations I would like to avoid having to fill out the entire child object to do so. 问题是使用JPA和Criteria执行操作,我想避免必须填写整个子对象。 Example: 例:

@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);

If sensor is mapped in Measure like in your example: 如果像示例中那样将传感器映射到“测量”中:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="SENSOR_ID", nullable=false, updatable=false)
private Sensor sensor;

You need to fill sensor instance. 您需要填充传感器实例。 Sensor is not saved with measure because by default no operations are cascaded. 传感器不保存度量值,因为默认情况下不会级联任何操作。 It must be saved before calling this. 调用之前必须先保存它。

To not fill whole sensor, use sensor_id FK instead of Sensor in Measure class. 要不填充整个传感器,请在Measure类中使用sensor_id FK代替Sensor。

@Column(nullable = true)
private Long sensor_id;

To use both one must be read only: 要同时使用两者,则必须是只读的:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="SENSOR_ID", updatable=false, insertable = false)
private Sensor sensor;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM