转发自 https://blog.csdn.net/guominjin/article/details/78963578
1>:首先将要作为主键的属性首先抽取成单独的实体 并提供get And set方法 并且还需要序列化
比如现在有一个实体 People ,具有属性pName,pAddress,pJavaScore,pCscore
复合主键为pName,pAddress
**********将这两个属性抽离形成一个新的实体并提供setter,gettter方法实现序列化(坑区)
compositionkey.java
-
import java.io.Serializable;
-
-
/**
-
*
-
* @author Guomin JIn
-
*
-
*/
-
public
class CompositionKey implements Serializable{
-
private String pName;
-
private String pAddress;
-
public String getpName() {
-
return pName;
-
}
-
public void setpName(String pName) {
-
this.pName = pName;
-
}
-
public String getpAddress() {
-
return pAddress;
-
}
-
public void setpAddress(String pAddress) {
-
this.pAddress = pAddress;
-
}
-
-
}
2>:在实际的实体中申明主键实体的变量
抽离之后的Peopel实体如下:
People.java
-
package cn.pzhu.composition;
-
/**
-
* 实体类
-
* @author Guomin JIn
-
*
-
*/
-
public
class People {
-
private CompositionKey key;
-
private
float pJavaScore;
-
private
float pCScore;
-
public CompositionKey getKey() {
-
return key;
-
}
-
public void setKey(CompositionKey key) {
-
this.key = key;
-
}
-
public float getpJavaScore() {
-
return pJavaScore;
-
}
-
public void setpJavaScore(float pJavaScore) {
-
this.pJavaScore = pJavaScore;
-
}
-
public float getpCScore() {
-
return pCScore;
-
}
-
public void setpCScore(float pCScore) {
-
this.pCScore = pCScore;
-
}
-
@Override
-
public String toString() {
-
return
"People [key=" + key +
", pJavaScore=" + pJavaScore +
", pCScore=" + pCScore +
"]";
-
}
-
-
-
}
扫描二维码关注公众号,回复:
6178553 查看本文章
![](/qrcode.jpg)
3>:在映射文件中编写实体的配置文件
配置文件如下:
hibernate.cfg.xml省略()
people.hbm.xml
-
<?xml version="1.0"?>
-
<!DOCTYPE hibernate-mapping PUBLIC
-
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
-
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
-
-
<hibernate-mapping package="cn.pzhu.composition">
-
<class name="People" table="peopel" >
-
<composite-id name="key">
-
<key-property name="pName" length="10" type="java.lang.String">
</key-property>
-
<key-property name="pAddress" length="10" type="java.lang.String">
</key-property>
-
</composite-id>
-
<property name="pJavaScore" length="5"/>
-
<property name="pCScore">
</property>
-
</class>
-
</hibernate-mapping>
4>:编写测试类
测试类使用junit
-
@Test
-
public void test_0001() {
-
Session session=
new Configuration()
-
.configure(
"hibernate.cfg.xml")
-
.addClass(People.class)
-
.buildSessionFactory()
-
.openSession();
-
-
session.beginTransaction();
-
-
CompositionKey key=
new CompositionKey();
-
key.setpName(
"jgm");
-
key.setpAddress(
"chengdu");
-
-
People people=
new People();
-
people.setKey(key);
-
people.setpJavaScore(
12.34f);
-
people.setpCScore(
36.2f);
-
//HibernateUtil.save(people);
-
session.save(people);
-
}