简体   繁体   中英

jpa hibernate one-to-one update

I'm working on an apartment management software and I'm having an issue.

There is two entities I have :

@Entity
public class Tenant extends AbstractEntity { //AbstractEntity contains the id
    @Column(nullable = false)
    private int number;
    @OneToOne
    private Apartment apartment;
}

and

@Entity
public class Apartment extends AbstractEntity { //AbstractEntity contains the id
    @Column(nullable = false)
    private int number;
    @OneToOne
    private Tenant tenant;
}

But when I do

EntityManager em = emProvider.get();
em.getTransaction().begin();

em.merge(apartment);
em.flush();

em.getTransaction().commit();

It only save the Tenant into the Apartment but I would like it also update the Apartment into the Tenant.

Do I really need to set the apartment field into the tenant or there is a way to fix it simply? Thanks

Cordially, Baskwo

You need to declare CascadeType.ALL in your Apartment entity. See sample

@OneToOne(cascade = CascadeType.ALL)
private Tenant tenant;

CascadeType.ALL is for all CRUD operation. Adjust CascadeType depends on your application needs.

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