简体   繁体   中英

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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