Issue
I am trying to create a relation between category and product classes. I thought many to many relationship would be the best fit. However when I run the application I got org.hibernate.MappingException: property-ref [_com_eCommerce_ecommerce_model_Product_listOfCategories] not found on entity [com.eCommerce.ecommerce.model.Product]
error. What could be the problem ?
Here is my Product class.
package com.eCommerce.ecommerce.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@NoArgsConstructor
@Entity
@Getter
@Setter
@Table(name="Product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int productId;
private int stockNumber;
@ManyToMany
@JoinTable(name = "products_categories",
joinColumns = {
@JoinColumn(name = "product",referencedColumnName = "productId",nullable = false,updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "category",referencedColumnName = "categoryName",nullable = false,updatable = false)
})
Set<Category> listOfCategories = new HashSet<>();
}
Category Class
package com.eCommerce.ecommerce.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Data
@NoArgsConstructor
@Entity
@Table(name = "Category")
public class Category {
private int categoryParentNumber;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int categoryId;
private String categoryName;
@ManyToMany(mappedBy = "listOfCategories",fetch = FetchType.LAZY)
private Set<Product> listOfProducts = new HashSet<>();
}
Solution
The problem is the column naming.
Column name is not productId
it is product_id
, and to be able to use referencedColumnName
you have to use @Column(name = "product_id")
naming.
Also referenced column must be @Id
and categoryName is not @Id
.
Working example:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "product_id", nullable = false)
private int productId;
private int stockNumber;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "products_categories_j",
joinColumns = {
@JoinColumn(name = "product_id", referencedColumnName = "product_id", nullable = false,updatable = false)
},
inverseJoinColumns = { @JoinColumn(name = "category_id", referencedColumnName = "category_id", nullable = false, updatable = false) }
)
private Set<Category> listOfCategories = new HashSet<>();
}
@Entity
public class Category {
private int categoryParentNumber;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "category_id", nullable = false)
private int categoryId;
@Column(name = "category_name", nullable = false)
private String categoryName;
@ManyToMany(mappedBy = "listOfCategories", fetch = FetchType.LAZY)
private Set<Product> listOfProducts = new HashSet<>();
}
Answered By - Gergo
Answer Checked By - Katrina (JavaFixing Volunteer)