I am using spring 4.0 with Hibernate 3.6.10 and have a very peculiar situation for which I have not been able to find a solution yet.
I have a table for Users in my database and have two common columns user_created and user_modified in all tables. These common columns as mapped using many-to-one association in one direction only. I am doing that because I have 50 tables and do not want to have a Set for each table in Users entity.
Code:
@Entity
@Table(name = "users")
public class UsersData{
@Id
@GeneratedValue
@Column(name = "user_id")
public int userId; //Primary Key
@Column(name = "username")
public String username;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_created", referencedColumnName = "user_id")
public UsersData userCreated;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_modified", referencedColumnName = "user_id")
public UsersData userModified;
}
Another example table:
Code:
@Entity
@Table(name = "employees")
public class EmployeesData{
@Id
@GeneratedValue
@Column(name = "emp_id")
public int empId; //Primary Key
@Column(name = "first_name")
public String firstName;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_created", referencedColumnName = "user_id")
public UsersData userCreated;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_modified", referencedColumnName = "user_id")
public UsersData userModified;
}
I am using the following code to find Users but do not get any results back when I know for sure that a user row exists with provided userId:
Code:
Criteria criteria = getSession().createCriteria(UsersData.class).add(Restrictions.eq("userId", userId));
UsersData usersData = (UsersData)criteria.uniqueResult();
On further debugging, I saw the following query is being generated by Hibernate(parts of the query not related to the issue have been removed):
Code:
select ..... from users this_ left outer join users usersdata2_ on this_.user_created=usersdata2_.user_id left outer join users usersdata3_ on usersdata2_.user_modified=usersdata3_.user_id where this_.user_id=?
when the actual query should be:
Code:
select ..... from users this_ left outer join users usersdata2_ on this_.user_created=usersdata2_.user_id left outer join users usersdata3_ on this_.user_modified = usersdata3_.user_id where this_.user_id=?
So instead of using this_ for joins Hibernated is using usersdata2_ alias.
Either hibernate is confusing its join or I mapped something incorrectly. Any help explaining or fixing this issue would be greatly appreciated.
Thanks