复合主键

hibernate复合主键的可选值:

<composite-id
 name="propertyName"
 class="ClassName"
 mapped="true|false"
 access="field|property|ClassName">
 node="element-name|."
 <key-property name="propertyName" type="typename" column="column_name"/>
 <key-many-to-one name="propertyName class="ClassName" column="column_name"/>
 ......
</composite-id>

create table composited_id_entity(
   foo_id varchar(46) not null,
   key_id varchar(46) not null,
   name varchar(200) not null,
   create_date timestamp,
   primary key(foo_id, key_id)
);

当表使用复合字段作为主键时,hibernate声明复合主键,需要使用compositd-id和key-property元素,如:

<class name="CompositedIdEntity" table="composited_id_entity">
		<composite-id>
			<key-property name="fooId" column="foo_id"/>
			<key-property name="keyId" column="key_id"/>
		</composite-id>
		<property name="name"/>
		<property name="date" type="timestamp" column="create_date"/>
		
	</class>
有复合主键的表对应的persistent class要重写hashCode()和equals(),这样才能实现复合键是否相等,

persistent class还要实现Serializable接口。

public class CompositedIdEntity implements Serializable{
	
	private static final long serialVersionUID = 5238531209505340462L;

	private String fooId;
	
	private String keyId;
	
	private String name;
	
	private Date date;
	
	public CompositedIdEntity(){}
	
	public CompositedIdEntity(String fooId, String keyId, String name, Date date){
		this.fooId = fooId;
		this.keyId = keyId;
		this.name = name;
		this.date = date;
	}

	//get set method.
	
	@Override
	public int hashCode() {
		
		return this.getFooId().hashCode() + this.getKeyId().hashCode();
	}
	
	@Override
	public boolean equals(Object object) {
		if(object == null || !(object instanceof CompositedIdEntity)) return false;
		CompositedIdEntity entity = (CompositedIdEntity) object;
		
		return this.getFooId().equals(entity.getFooId()) &&
			   this.getKeyId().equals(entity.getKeyId()) &&
			   this.getName().equals(entity.getName()) &&
			   this.getDate().equals(entity.getDate());
	}

}
测试:

java.io.Serializable ser =  session.save(
				new CompositedIdEntity("d820152b", "0e9dcc", "content", new Date()));
		System.out.println(ser);
输出:

org.lam.detector.hibernate.charpter1.model.CompositedIdEntity@d5f398c6
可以看出save()返回了表mapping对应类的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值