日期:2014-05-19  浏览次数:20863 次

hibernate-mapping 如何映射关联查询中被关联表的字段?
以下代码,我实例化后的list,t2的两个字段( t2.id2, t2.name2)全是null,而该语句放在pl/sql里搜出来字段都是有值的。请问原因是不是t1.hbm.xml没有对t2的映射?该怎么改?

public List<t1> findT1() {
  String strSql = "SELECT t1.*, t2.id2, t2.name2 FROM t1 LEFT JOIN t2 ON t1.id1=t2.id2
";
  Session oSess = this.getHibernateTemplate().getSessionFactory().openSession();
  SQLQuery oQuery = oSess.createSQLQuery(strSql);
  oQuery = oQuery.addEntity(t1.class);
  List list = oQuery.list();
  oSess.close();
  return list;
}

public class t1 implements java.io.Serializable {
  private static final long serialVersionUID = 1L;
  private Integer id1;
  private String name1;
  private Integer id2;
  private String name2;
  ( 各种get & set ……)
}

t1.hbm.xml中只映射了t1的字段,不知道该怎么映射t2的表和字段
 <hibernate-mapping>
  <class name="com.bean.t1" table="T1">
  <id name="id1" type="integer">
  <column name="ID1" precision="22" scale="0" />
  <generator class="native" />
  </id>
  <property name="name1" type="string">
  <column name="NAME2" />
  </property>
  </class>
</hibernate-mapping>

------解决方案--------------------
另外建一个中间类,比如是 QueryT1T2.java
public class QueryT1T2 implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id1;
private String name1;
private Integer id2;
private String name2;

getters & setters…… 
 }
查询时:
createSqlQuery(Sql).addScalar("id1").addScalar("name1").addScalar("id2").addScalar("name2")
把字段一个一个加进去