JPA newbie - do not persist existing member each time containing entity is persisted

StackOverflow https://stackoverflow.com/questions/9553876

  •  05-12-2019
  •  | 
  •  

質問

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

役に立ちましたか?

解決

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);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top