Reputation: 1019
I'm learning Spring Data JPA and having some trouble establishing the relationship between these two tables:
A product can have only one type. A type can be associated with many products.
Where would I use the @OnetoMany and @ManytoOne annotations in my entity classes?
Upvotes: 0
Views: 818
Reputation: 130917
For the situation you mentioned in your question, your entities should be like:
@Entity
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne
private ProductType type;
// Getters and setters
}
@Entity
public class ProductType {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "type")
private List<Product> products;
// Getters and setters
}
Upvotes: 2
Reputation: 352
Cassio Mazzochi Molin's answer should work for you after correcting the little mistake he made in the inverse entity (I.e. ProductType class). The @OneToMany should be mapped to the variable type in the owning entity (i.e. Product class) and not productType. So that line should be
@OneToMany(mappedBy = "type")
I will also suggest you pick up a good tutorial book on jpa 2 and study, specially the relationship part because there's lot of rules to it which you can only learn by studying on your own else you will keep asking questions here, trust me.
Pro JPA 2 : Mastering the JAVA persistence API by Apress is a very nice tutorial book that can help you.
Upvotes: 0
Reputation: 395
Entity Product should have field ProductType with annotation @ManyToOne. Entity ProductType should have field Set with annotation @OneToMany(mappedBy = 'productType')
Upvotes: 0