Aliuk
Aliuk

Reputation: 1359

JPA persist an entity without related entities

Supposing the following case:

    @Entity
    ...
    public class A {
        @Id
        @Column(name="ID")
        ...
        private Long id;

        @Column(name="TEXT", length=120)
        private String text;

        @ManyToOne
        @JoinColumn(name="B_ID")
        private B b;

        ...
    }

    @Entity
    ...
    public class B {
        @Id
        @Column(name="ID")
        ...
        private Long id;

        @Column(name="TEXT", length=120)
        private String text;

        ...
    }

Supposing that I want to persist an A entity associating it to an existing B entity in the database:

How can I persist the entity A without persisting the entity B? I mean, I want to persist all the fields in A but only the B id in the A table, not the text of B in the B table.

Upvotes: 0

Views: 289

Answers (1)

JB Nizet
JB Nizet

Reputation: 691625

You get a reference to the existing B (using em.getReference() or em.find()), and set A.b to this reference. Then you persist A.

Upvotes: 1

Related Questions