Question

I am still not totally clear about entity states and I have unsuccessfully tried several things regarding the following situation:

@Entity
public class Foo {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", nullable = false)
    private long id;
    /* other fields */
    @NotNull
    @ManyToOne
    @JoinColumn(name = "related_bar", nullable = false)
    private Bar bar;
    /* getters & setters */
}

@Entity
public class Bar {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", nullable = false)
    private long id;
    /* other fields & methods*/
}

Typically, when data is sent from a Foo creation form, the ID of the related bar will be sent (but not its other attributes, they'd serve no use there). Is there any automatic way to tell the Entity Manager to attach (and not persist) a Bar instance whose ID is set when persisting a new Foo?

Thanks in advance for your help!

Rolf

Was it helpful?

Solution

Bar bar = em.getReference(Bar.class, barId);
foo.setBar(bar);

getReference() doesn't even goes to the database: it returns a proxy to the actual Bar. If it doesn't exist, an error will be thrown at flush time, due to a foreigk key reference error. If you want to check that the entity exists:

Bar bar = em.find(Bar.class, barId);
if (bar == null) {
    throw someException();
}
foo.setBar(bar);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top