views:

31

answers:

2

hi,

MyTable is a table in my Oracle DB, it has a CMP_ID to join the COMPANIES table.

Here is the Java implementation :

public class MyTable implements Serializable {
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns( { @JoinColumn(name = "CMP_ID", referencedColumnName = "CMP_ID", nullable = false) })
@XmlTransient
Company company;
...
}

In my JSP Page, i managed to display the MyTable:

${MyTable.company.cmpName}

But Hibernate generated 2 SELECTs : one for the MyObject , and another one to fecth the Company name.

How do i fetch all the informations i want in only one query using Hibernate ? (all fields in MyTable, plus the Company name in the Companies table)

thank you

A: 

That's the way hibernate works. See http://www.javalobby.org/articles/hibernate-query-101/ for more information.

BillThor
so, if i read well, the only way to change this behaviour is to use a custom query ? no other option / annotation?
guigui42
You can also use a left join in the query, but I don't think lazy fetch will work.
BillThor
+1  A: 

If you do not want to use a custom query, set up the fetching strategy as EAGER

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="CMP_ID", referencedColumnName="CMP_ID", nullable=false)
private Company company;

Just an advice: prefer to use @JoinColumns if you have more than one @JoinColumn. Otherwise, use just @JoinColumn. keep in mind HQL queries overrides default fetching strategy.

Arthur Ronald F D Garcia