Reputation: 17289
I have models like this:
@Table(name="EMPLOYEE")
public class Employee {
@Column(name="firstname")
private String firstname;
// and others
@ManyToOne( targetEntity = Employee.class,
fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="department_id",
insertable=false, updatable=false,
nullable=false)
private Department department;
=============================================================================
@Table(name="DEPARTMENT")
public class Department {
@Column(name="DEPARTMENT_ID")
private Long departmentId;
@OneToMany( targetEntity = Employee.class,
fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="department_id")
@IndexColumn(name="idx")
private List<Employee> employees;
and my DepartmentDaoImpl is
public class DepartmentDaoImpl implements DepartmentDao{
@Autowired
private SessionFactory sessionFactory;
@Transactional
public void addDepartment(Department department) {
sessionFactory.getCurrentSession().save(department);
}
when i run project this exception appear in output
org.hibernate.MappingException: Unknown entity: org.springmvc.form.Department
what is this problem and how solved it?
Department department = new Department();
department.setDepartmentName("Sales");
department.setDepartmentId(90);
Employee emp1 = new Employee("reza", "Mayers", "101",department.getDepartmentId());
// Employee emp2 = new Employee("ali", "Almeida", "2332");
department.setEmployees(new ArrayList<Employee>());
department.getEmployees().add(emp1);
Upvotes: 0
Views: 180
Reputation: 691635
Many problems in this code.
First problem: Unknown entity: org.springmvc.form.Department. This means that Department is not annotated with @Entity and/or is not listed in the entities in the hibernate configuration file.
Second problem:
@ManyToOne( targetEntity = Employee.class)
private Department department;
This doesn't make sense. The target entity is obviously Department, not Employee. targetEntity is useless unless the type of the field is an abstract class or interface, and you need to tell Hibernat what it should use as concrete entity class. Otherwise, Hibernate know the target entity from the type of the field.
Third problem:
@OneToMany( targetEntity = Employee.class,
fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="department_id")
This OneToMany is the inverse side of the bidirectional association that you have already declared and mapped in Employee. So you MUST NOT repeat the mapping here. Instead, you MUST declare it as the inverse side, using the mappedBy
attribute:
@OneToMany(mappedBy = "department", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@IndexColumn(name="idx")
private List<Employee> employees;
Using eager fetching for a toMany association is a really bad idea as well. You really don't want to load the 200 employees of a department every time you load a department. That will kill the performance of your application.
Upvotes: 3