ManyToOne relationship without list / set using JPA

I have a new JPA project using hibernate and am having difficulty reading its code. I have seen:

@Entity
public class Product {

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

...
}

      

and another object

@Entity
public class Manufacturer{

 private ManufacturerId manufacturerId;

    private String name;

    private Manufacturer() {
    }
...

      

Why is there no list / set with a Product in the "Manufacturer" class? Is a ManyToOne relationship bidirectional? Why is this possible? How does the manufacturer know about their products, how will it be stored in the database table?

+3


source to share


2 answers


Multiparty communication from one to the other is optional. You can implement it if you like, or skip it if not needed or even risky. A manufacturer may have many thousands of products. Than it is pointless to take all at once. Better to load by request and use swap. Of course, you could add a product collection to your manufacturer if you think it will help you.



  • Why is there no list / set with the product (s) in the manufacturer's class?

    Either because it is not needed, or it is considered risky.

  • Is a ManyToOne relationship bi-directional?

    Of course yes. Even if the link fails, it still exists.

  • Why is this possible? How will this be stored in the DB table?

    OneToMany relationships are always implemented with id on one side. (Producer in products in this case. Nothing else is required. Even if you implement a collection of products, it will not affect how it is stored.

  • How does a manufacturer know about their products?

    This is not true. But, of course, you can query the database.

+2


source


If you look at the DB level, the table Product

will have something like manufacturer_id

which is a foreign key in the table Manufacturer

. The structure of the table remains unchanged in both unidirectional and bidirectional cartographic cases.



The manufacturer will know their product by querying the table Product

with manufacturer_id = <its id>

. At the JPA layer, in the case of a unidirectional mapping, you can request it from Product p where p.manufacturer.id = :man_id

. In case of bi-directional matching, you could just do it manufacturer.getProducts()

, but it would translate the same SQL.

+1


source







All Articles