hibernate学习3之one-to-one单向外键关联

one-to-one关联其实是many-to-one的一种特殊形式。

老规矩。hibernate.cfg.xml先看(没什么特别的吧)
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_one2one_ufk_1</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">bjsxt</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.show_sql">true</property>
		
		<mapping resource="com/bjsxt/hibernate/IdCard.hbm.xml"/>
		<mapping resource="com/bjsxt/hibernate/Person.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

下面是2个实体类,一个用户一个卡号
public class IdCard {
	
	private int id;
	
	private String cardNo;

	//setter,getter
}

public class Person {

	private int id;
	
	private String name;
	
	private IdCard idCard; //一个用户一个卡号

	//setter,getter
	
}

2个映射文件:
IdCard.hbm.xml:
<?xml version="1.0"?>
<!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.bjsxt.hibernate.IdCard" table="t_idcard">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="cardNo"/>
	</class>
</hibernate-mapping>

Person.hbm.xml:
<?xml version="1.0"?>
<!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.bjsxt.hibernate.Person" table="t_person">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name"/>
		<many-to-one name="idCard" unique="true"/>
                <!--
                <many-to-one name="idCard" unique="true" cascade="all"/>
                -->
	</class>
</hibernate-mapping>

看上面的配置,其实配置的是many-to-one,只不过one-to-one是many-to-one的特殊情况而已,只要在many-to-one中配置unique="true",就变成one-to-one关系了。
测试一下:
public void testSave() {
		Session session = null;
		try {
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			IdCard idCard = new IdCard();
			idCard.setCardNo("88888888888888");
			session.save(idCard);//如果设置了级联,这句可以舍去。
			
			Person person = new Person();
			person.setName("菜10");
			person.setIdCard(idCard);
			
			session.save(person);
			
			session.getTransaction().commit();
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally {
			HibernateUtils.closeSession(session);
		}
	}			

你可能感兴趣的:(mysql,Hibernate,.net,xml,jdbc)