我是休眠的新手,我创建了表和映射,并使用以下代码列出了表中的所有行。
List places = session.createQuery("FROM Place").list();
for (Iterator iterator = places.iterator(); iterator.hasNext();) {
Place place = (Place) iterator.next();
System.out.println("-" + place.getName());
}
此代码工作正常,但是 PLACE 表与 ADDRESS 表具有一对一的关系,并且此代码为 ADDRESS 表中的所有行返回空值并打印出:
-null
-null
-null
-343
-223
-122
我只想要 PLACES 表中的行。我该如何管理?
重要提示:在 Pierre-Henri Toussaint 的回答之后,我注意到生成的 sql。Hibernate 首先从地址生成一个选择查询,然后从一个地方选择查询。(当我将约束值更改为 false 时,它会为地址表的每一行生成一个查询)
地址.hbm.xml:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.places.general.Address" table="ADDRESS" schema="dbo">
<id name="placeId" type="java.lang.Integer">
<column name="PLACE_ID" />
<generator class="foreign">
<param name="property">place</param>
</generator>
</id>
<one-to-one name="place" class="com.places.general.Place"
constrained="true">
</one-to-one>
<property column="PLACE_ADDRESS" length="250" name="placeAddress" type="java.lang.String"/>
<property column="PHONE" length="50" name="phone" type="java.lang.String"/>
</class>
</hibernate-mapping>
Place.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.places.general.Place" table="PLACES" schema="dbo">
<id column="ID" name="id" type="java.lang.Integer">
<generator class="identity"/>
</id>
<property column="NAME" length="100" name="name" not-null="true" type="java.lang.String"/>
<property column="DETAILS" length="200" name="details" type="java.lang.String"/>
</class>
</hibernate-mapping>
地方.java:
import java.io.Serializable;
public class Place implements Serializable{
private Integer id;
private String name;
private String details;
public Place() {
}
public Place(String name, String details) {
this.name = name;
this. details = details;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this. details = details;
}
}