Xelian
Xelian

Reputation: 17198

ManyToOne relation without list/set using JPA

I have new JPA project using hibernate and I run into a difficulty while reading its code. I saw:

@Entity
public class Product {

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private Manufacturer manufacturer;

...
}

and another Entity

@Entity
public class Manufacturer{

 private ManufacturerId manufacturerId;

    private String name;

    private Manufacturer() {
    }
...

Why there is not List/Set with Product(s) in the Manufacturer Entity class? ManyToOne relationship is Bidirectional? Why is this possible? How Manufacturer knows about its products, how this will be persisted on the DB table?

Upvotes: 4

Views: 1071

Answers (2)

Bernd Ebertz
Bernd Ebertz

Reputation: 1327

The many-side of an one to many association is optional. You can implement it if intended or skip it if not needed or even risky. A manufacturer could have many thousand of products. Than it makes no sense to fetch all of them at once. It's better to load via a query and use paging. Of course you could add the collection of products to your Manufacturer if you think this helps you.

  • Why there is not List/Set with Product(s) in the Manufacturer Entity class?

    Either because not needed or as considered risky.

  • ManyToOne relationship is Bidirectional?

    Of course yes. Even if the relationship is not impletemented it still exists.

  • Why is this possible? How this will be persisted on the DB table?

    A OneToMany relationship is always implemented by an id on the one side. (ManufacturerId in Products in this case. Nothing else is needed. Even if you implement the products collection. This will not impact the way it's persisted.

  • How Manufacturer knows about its products?

    It doesn't. But of course it's possible to query the database.

Upvotes: 2

Predrag Maric
Predrag Maric

Reputation: 24403

If you look at it at DB level, table Product will have something like manufacturer_id which is a foreign key to Manufacturer table. The table structure remains the same in both unidirectional and bidirectional mapping case.

Manufacturer will know its product by querying table Product with manufacturer_id = <its id>. On JPA level, in case of unidirectional mapping you could query it by from Product p where p.manufacturer.id = :man_id. In case of bidirectional mapping you could just do manufacturer.getProducts(), but it would translate to the same SQL.

Upvotes: 1

Related Questions