Hibernate 一对一外键关联

一 表结构:

 

CREATE TABLE `address` (
  `aid` int(11) NOT NULL auto_increment,
  `address` varchar(255) NOT NULL default '',
  PRIMARY KEY  (`aid`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

CREATE TABLE `user` (
  `userid` int(11) NOT NULL auto_increment,
  `username` varchar(255) NOT NULL default '',
  `age` int(2) default NULL,
  `addressID` int(11) default NULL,               --外键
  PRIMARY KEY  (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

 

二 POJO与映射文件

 

public class User {

	private Integer userid;
	private String username;
	private Integer age;
	private Address address;
//getters setters method...
}

public class Address {
	private Integer aid;
	private String address;
	private User user;
//getters setters method...
}

 

User.hbm.xml

	<class name="com.pojo.User" table="user" dynamic-insert="true"
		dynamic-update="true">
		<id name="userid" type="integer">
			<column name="userid" sql-type="int" length="11"></column>
			<generator class="native"></generator>
		</id>
		<property name="username" type="string">
			<column name="username" sql-type="varchar" length="255"
				not-null="true">
			</column>
		</property>
		<property name="age" type="integer">
			<column name="age" sql-type="int" length="2"></column>
		</property>
		<many-to-one name="address" class="com.pojo.Address"
			cascade="all" column="addressID" unique="true">
		</many-to-one>
	</class>
</hibernate-mapping>

 

Address.hbm.xml

<hibernate-mapping>
	<class name="com.pojo.Address" table="address" dynamic-insert="true" dynamic-update="true">
		<id name="aid" type="integer">
			<column name="aid" sql-type="int" length="11"></column>
			<generator class="native">
			</generator>
		</id>
		<property name="address" type="string">
			<column name="address" sql-type="varchar" length="255"></column>
		</property>
		<one-to-one name="user" class="com.pojo.User"
			constrained="true" cascade="all" property-ref="address">
		</one-to-one>
	</class>
</hibernate-mapping>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值