自底向上带你逆向解析hibernate联合主键-阿里云开发者社区

开发者社区> 开发与运维> 正文

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

简介: 从mysql的建表语句出发了解析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() {
        ...
    }

}

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章