Hi All,
I am learning Hibernate and currently stuck and need some help to figure out what I have done wrong.
Tables:
employee(
emp_id,firstname,lastname
)
project(
proj_id, name
)
empproj(
projectid,employeeid, projectlead
)
Emplyee.javaCode:
@Entity
@Table(name="employee")
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="emp_id")
private Integer employeeId;
private String firstName;
private String lastName;
@OneToMany(mappedBy = "pk.project",fetch=FetchType.LAZY,cascade=CascadeType.ALL)
private List<ProjectAssociation> projects = new ArrayList<ProjectAssociation>();
...
}
Project classCode:
@Entity
@Table(name="project")
public class Project implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="proj_id")
private Integer projectId;
@Column(name="name")
private String projectName;
@OneToMany(mappedBy = "pk.project",fetch=FetchType.LAZY)
private List<ProjectAssociation> employees =new ArrayList<ProjectAssociation>();
...
}
ProjectAssociation with additional attributeCode:
@Entity(name="projemp")
@AssociationOverrides({
@AssociationOverride(name = "pk.employee", joinColumns = @JoinColumn(name = "employeeId")),
@AssociationOverride(name = "pk.project", joinColumns = @JoinColumn(name = "projectId"))})
public class ProjectAssociation implements Serializable {
@EmbeddedId
private ProjectAssociationId pk = new ProjectAssociationId();
@Transient
@ManyToOne(optional=false)
private Employee employee;
@Transient
@ManyToOne(optional=false, fetch=FetchType.EAGER)
private Project project;
@Basic
private boolean projectLead;
...
}
ProjectAssociationIdCode:
@Embeddable
public class ProjectAssociationId implements Serializable {
@ManyToOne
private Employee employee;
@ManyToOne
private Project project;
My current issues- insert operation works fine as expected
-
Select not working correctlyProjectAssociation is always empty, The database has correct links between employee, progemp, and project.
Sql generated when emp.getProjects() is called is :
Code:
select projects0_.projectId as projectId1_, projects0_.employeeId as employeeId1_, projects0_.employeeId as employeeId4_0_, projects0_.projectId as projectId4_0_, projects0_.projectLead as projectL1_4_0_ from projemp projects0_ where projects0_.projectId=?
What am I doing wrong, When I call emp.getProjects() I want to get all the projects this employee is working onCode:
Employee emp = em.find(Employee.class, 20);
System.out.println("emp= " + ReflectionToStringBuilder.toString(emp));
List<ProjectAssociation> projs = emp.getProjects();
for(ProjectAssociation pj: projs){
Project p = pj.getProject();
System.out.println("proj = " + ReflectionToStringBuilder.toString(p));
}