arjacsoh
arjacsoh

Reputation: 9232

Hibernate "mappedBy" use

I have read several examples about creating associations between tables with Hibernate and I have got a little bit confused. I want initilaly to know how many tables will be created in the database without specifying any annotation on the other side as with the code:

@Entity
public class Flight implements Serializable {
    @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
    @JoinColumn(name="COMP_ID")
    public Company getCompany() {
        return company;
    }
    ...
} 

I suspect two tables Flight, Company and the Flight contains a foreign key Company_Id. AM I right? What is the difference if I add the "mappedBy" on the other side as:

@Entity
public class Company {
    @OneToMany(mappedBy="company")
    public Set<Flight> getFlights() {
        ...
    }
}

How many tables will be created by the second approach? I suppose the second approach establishes a bidirectional association. What is practical difference between the two cases? What is going on also with the "mappedBy" annotation in the @ManyToMany association?

Upvotes: 0

Views: 2499

Answers (2)

Kanagaraj M
Kanagaraj M

Reputation: 966

When your are using bidirectional relationship there is a change to store relationship in both tables by using mappedby you can avoid it. From your example if you remove mappedby, flight and company both tables will have relationship field.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

If you didn't put any annotation on the flights property, the default mapping would apply, which is @Basic. That means that the whole contents of the list would be serialized and stored in a column named flights.

This is obviously not what you want. What you want is to make it the inverse side of the ManyToOne association defined in Flight. That's what @OneToMany(mappedBy = "company") does.

Other than that, your assumption is correct. A ManyToOne is mapped by default using a join column in the table of the entity. Using the JoinColumn annotation allows specifying a name other than the default one for the join column (as well as other properties of this join column).

Upvotes: 1

Related Questions