下面是我完整的代碼Hibernate中一對一關聯的行爲?
下面是CFG文件
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">MyProject1</property>
<property name="hibernate.connection.password">tingtong</property>
<property name="hibernate.default_schema">MyProject1</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.hbm2ddl.auto" >update</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Mapping files -->
<mapping resource="Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
下面是映射文件
<hibernate-mapping>
<class name="com.daasl.Person" table="person">
<id name="id" type="int">
<generator class="increment"/>
</id>
<property name="name" column="cname" type="string"/>
<one-to-one name="address" class="com.daasl.Address" property-ref="personId" cascade="all"/>
</class>
<class name="com.daasl.Address" table="Address">
<id name="id" type="int">
<generator class="increment"/>
</id>
<!--for one to one -->
<property name="personId" type="int"/>
<property name="addressLine1" type="string"/>
</hibernate-mapping>
以下
是人的價值對象
public class Person implements Serializable {
private int id;
private String name;
//private int addressId;
private Address address;
// getter seeter for each field
}
下面
是地址值對象
public class Address {
private int id;
private int personId;
private String addressLine1;
// getter seeter for each field
}
下面是從主方法
tx = session.beginTransaction();
person = (Person)session.get(Person.class, 4);
// Create a Person object and save it
Person p1 = new Person();
p1.setName("Scott");
Address add1= new Address();
add1.setAddressLine1("NY1");
p1.setAddress(add1);
session.save(p1);
// p1.setName("mohit1");
// Retrieve the person objects
person = (Person)session. get(Person.class,1);
tx.commit();
tx = null;
代碼段如上述代碼時,我保存Person
對象我期望也保存地連同correponding地址對象personid
。 當我運行以上程序personid
正在以0
in personid列在地址表內。根據我的理解,personid
應該與人員表id值一起插入。對?
我想知道的第二件事是:one to one
映射創建外鍵子鍵關係。如上例中我期待personid列內的地址表應該指向人表的主鍵即id列。 但是它沒有在地址表的personid列上創建任何外鍵約束。
我在這裏丟失了什麼