My goal is to create my Contact
object directly from query and hibernate, the peculiarities are mainly three:
- The contact object has another custom object inside that is the
Company
. - The contact object contains many more fields and I just want to retrieve a few
- To retrieve the values I have to use a complex query that I cannot generate via a simple
createCriteria
using hibernate.
Contact
@Entity
@Table(name = "contacts")
public class Contact
{
private String firstName;
private String lastName;
private Company company;
...
}
Company
@Entity
@Table(name = "companies")
public class Contact
{
private Integer id;
private String name;
...
}
SQL Query
As I explained before the query is very complex but for convenience both in writing and in answering the question I have reduced it to its minimum terms:
SELECT a.first_name as firstName,
a.last_name as lastName,
a.company_id as companyId,
b.company_name as companyName
FROM contacts a
INNER JOIN companies b ON a.company_id = b.company_id
UserType (CompanyType)
To create the Company
object I use a UserType
and it is the following
public class CompanyType implements UserType
{
@Override
public int[] sqlTypes()
{
return new int[] { Types.INTEGER, Types.VARCHAR };
}
@SuppressWarnings("rawtypes")
@Override
public Class returnedClass()
{
return Company.class;
}
...
}
Java
I am currently building my object in the following way and is it working.. currently thanks to my UserType
I can create a new Company
object and set the id.
Type companyType = session.getTypeHelper().custom(CompanyType.class);
results = session.createSQLQuery(SQL_QUERY)
.addScalar("firstName", StandardBasicTypes.STRING)
.addScalar("lastName", StandardBasicTypes.STRING)
.addScalar("companyId", companyType)
.setResultTransformer(Transformers.aliasToBean(Contact.class))
.list();
My goal is to set the name of the Company
in the same object created before (by the id).. I tried to add the following line of code but I get an error because it is trying to allocate a new object instead of setting the current one:
.addScalar("companyName", companyType)