inverse=true in JPA annotations
Asked Answered
P

3

27

In my application I use JPA 2.0 with Hibernate as the persistence provider. I have a one-to-many relationship between two entities (using a @JoinColumn and not @JoinTable). I wanted to know how could I specify inverse=true (as specified in hbm.xml) in JPA annotations to reverse the relationship owner.

Thank you.

Peroxide answered 1/2, 2011 at 16:39 Comment(2)
What exactly do you want to achive?Falsework
As you know inverse controls which entity in the relationship updates the foreign key. #4440256. In my one-to-many relationship I want to specify this.Peroxide
P
46

I found an answer to this. The mappedBy attribute of @OneToMany annotation behaves the same as inverse = true in the xml file.

Peroxide answered 2/2, 2011 at 15:59 Comment(1)
Also, this question has more information: https://mcmap.net/q/63958/-jpa-joincolumn-vs-mappedby.Craven
H
4

The attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the other entity. Other entity will be having @JoinColumn annotaion and @ManyToOne relationship. Hence I think inverse = true is same as @ManyToOne annotation.

Also inverse=”true” mean this is the relationship owner to handle the relationship.

Hetaerism answered 9/1, 2017 at 6:48 Comment(0)
A
3

by using mappedBy attribute of @OneToMany or @ManyToMany we can enable inverse="true" in terms of annotation. For example Branch and Staff having one-to-many relationship

@Entity
@Table(name = "branch")
public class Branch implements Serializable {
    @Id
    @Column(name = "branch_no")
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected int branchNo;
    @Column(name = "branch_name")
    protected String branchName;
    @OneToMany(mappedBy = "branch") // this association is mapped by branch attribute of Staff, so ignore this association
    protected Set<Staff> staffSet;
    
    // setters and getters
}
@Entity
@Table(name = "staff")
public class Staff implements Serializable {
    @Id
    @Column(name = "staff_no")
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected int staffNo;
    @Column(name = "full_name")
    protected String fullName;
    @ManyToOne
    @JoinColumn(name = "branch_no", nullable = true)
    protected Branch branch;

    // setters and getters
}
Arthurarthurian answered 12/7, 2020 at 18:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.