码迷,mamicode.com
首页 > Web开发 > 详细

hibernate ——联合主键

时间:2016-06-02 00:51:26      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

接上一篇博客:http://www.cnblogs.com/tengpan-cn/p/5551323.html

 

主键类不需要写任何注解,表对象类使用@IdClass注解
在表对象类前面加@IdClass(value=主键类名.class)然后,表对象类中也不必包含主键类,直接分成各个属性即可。在多个属性前加@ID
 

添加主键类,注意必须实现Serializable接口

技术分享
package com.pt.hibernate;

import java.io.Serializable;

public class UnionId implements Serializable{
    public String getSchoolName() {
        return schoolName;
    }
    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    String schoolName;
    int id;
}
UnionId.java
技术分享
package com.pt.hibernate;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;

@Entity
@IdClass(value=UnionId.class)
public class Student {
    String schoolName;
    int id;
    String stuName;
    
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    @Id
    public String getSchoolName() {
        return schoolName;
    }
    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }
    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

}
Student.java

生成表的语句:

create table Student (
        id integer not null,
        schoolName varchar(255) not null,
        stuName varchar(255),
        primary key (id, schoolName)
    ) ENGINE=InnoDB

 

hibernate ——联合主键

标签:

原文地址:http://www.cnblogs.com/tengpan-cn/p/5551480.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!