自底向上带你逆向解析hibernate联合主键

参考1参考2
1 最后生成具有复合主键的表
数据库表的主键由两个及以上的字段组成

create table people(
name varchar(20),
type varchar(20),
age int(11),
primary key (name,type)
); 

2 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="com">
    <class name="People" table="people">
        <composite-id name="peopleKey" class="com.PeoplePK">
            <key-property name="name" />
            <key-property name="type" />
        </composite-id>
        <property name="age" column="age" />
    </class>
</hibernate-mapping>

3 配置映射

<mapping resource="com/People.hbm.xml" />

4 java类

  • People.java
package com;
public class People {
    PeoplePK peopleKey = new PeoplePK();
    private int age;
    public PeoplePK getPeopleKey() {
        return peopleKey;
    }
    public void setPeopleKey(PeoplePK peopleKey) {
        this.peopleKey = peopleKey;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

主键类

package com;
public class PeoplePK implements java.io.Serializable {

    private String name;

    private String type;

    public String name() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String type() {
        return type;
    }
    public void setType(String type) {
        this.secondName = secondName;
    }
    public boolean equals(Object obj) {
        ...
    }
    public int hashCode() {
        ...
    }

}
上一篇:软件设计师22-存储器系统01


下一篇:软件设计师备考错题01