Arian
Arian

Reputation: 7719

OneToMany relation is not reflected in the db using Hibernate

I have two objects, which are referring each other. A User that owns a list of groups, and a Group which has one admin:

@Entity
@Table(name="User")
class User {
    @OneToMany(mappedBy="admin")
    List<Group> ownedGroups;
}

@Entity
@Table(name="\"Group\"") // Group is a reserved word, use \" as a work-around
public class Group implements Serializable {
    @NotNull
    @ManyToOne
    @JoinColumn(name = "admin_id", referencedColumnName = "id")
    private User admin;
    User admin;
}

There's a Group controller which I'm writing a bunch of end to end tests for it. In one of the tests, I create a group and tests that the admin is the user I expect.

Assert.assertEquals("wrong number of groups created for the admin", 1, user.getOwnedGroups().size());

While playing around with the db, I found out that there's no owneddGroups field in the User table, and there's no User_Group table created for this relation. I wonder how this field is persisted in the db then?

Upvotes: 2

Views: 74

Answers (1)

Guillaume F.
Guillaume F.

Reputation: 6473

You will find an admin_id column in your table group.
This column contains an id from the table user.
This is your physical link between the two tables.

ownedGroups in the User entity is a slave field. It it only used for convenience, not for persistence, unless you reconfigure it.

when you call group.getAdmin(). Hibernate will SELECT * FROM User WHERE id=<admin_id>;.
This will return only one User.

when you call user.getOwnedGroups(). Hibernate will SELECT * FROM Group WHERE admin_id=<id>.
This will return a List of Groups.

Upvotes: 1

Related Questions