Hibernate学习笔记_联合主键

复合主键(联合主键):多个字段构成唯一性。

一,xml方式

1. 将联合主键的属性提取出来,重新编写一个StudentPK类(原Student类中的id,name要删除 并新加入属性“StudentPK”)

//StudentPK .javapackage com.bjsxt.hibernate;

public class StudentPK implements java.io.Serializable{
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if(o instanceof StudentPK) {
            StudentPK pk = (StudentPK)o;
            if(this.id == pk.getId() && this.name.equals(pk.getName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        return this.name.hashCode();
    }
}
//Student .java
package com.bjsxt.hibernate;

public class Student {

    private StudentPK pk;

    private int age;
    private String sex;
    private boolean good;
    public boolean isGood() {
        return good;
    }
    public void setGood(boolean good) {
        this.good = good;
    }
    /*public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }*/
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public StudentPK getPk() {
        return pk;
    }
    public void setPk(StudentPK pk) {
        this.pk = pk;
    }

}

注意:

i.   新建StudentPK 类必须实现 java.io.Serializable 序列化接口(把类对象序列化)

ii.   新StudentPK 类要重写equals和hashCode方法(保证唯一性)

2.  联合主键生成策略XML配置方法

<hibernate-mapping>
    <class name="com.bjsxt.hibernate.Student">

        <composite-id name="pk" class="com.bjsxt.hibernate.StudentPK">
            <key-property name="id"></key-property>
            <key-property name="name"></key-property>
        </composite-id>

        <property name="age" />
        <property name="sex" />
        <property name="good" type="yes_no"></property>
    </class>

</hibernate-mapping>

 二,Annotation

1.前三步与Xml方式前三步一样 都要建立新的类 都要实现Serializable接口 重写equals和hashCode方法.

package com.bjsxt.hibernate;

import javax.persistence.Embeddable;

@Embeddable
public class TeacherPK implements java.io.Serializable{
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if(o instanceof TeacherPK) {
            TeacherPK pk = (TeacherPK)o;
            if(this.id == pk.getId() && this.name.equals(pk.getName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        return this.name.hashCode();
    }
}
package com.bjsxt.hibernate;

import java.util.Date;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.IdClass;
import javax.persistence.SequenceGenerator;

import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity
@javax.persistence.TableGenerator(
        name="Teacher_GEN",
        table="GENERATOR_TABLE",
        pkColumnName = "pk_key",
        valueColumnName = "pk_value",
        pkColumnValue="Teacher",
        allocationSize=1
    )

@SequenceGenerator(name="teacherSEQ", sequenceName="teacherSEQ_DB")

public class Teacher {

    private TeacherPK pk;

    private String title;
    private String yourWifeName;
    private Date birthDate;
    private boolean good;
    private Gender gender;

    public Gender getGender() {
        return gender;
    }
    public void setGender(Gender gender) {
        this.gender = gender;
    }
    public boolean isGood() {
        return good;
    }
    public void setGood(boolean good) {
        this.good = good;
    }
    @Transient
    public String getYourWifeName() {
        return yourWifeName;
    }
    public void setYourWifeName(String yourWifeName) {
        this.yourWifeName = yourWifeName;
    }

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Temporal(TemporalType.TIME)
    public Date getBirthDate() {
        return birthDate;
    }
    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    @Id
    public TeacherPK getPk() {
        return pk;
    }
    public void setPk(TeacherPK pk) {
        this.pk = pk;
    }
}

 方法一:

在新类前写@Embeddable,在原类的新属性“TercherPK”的get方法前写@ld,

//TeacherPK .java@Embeddable
public class TeacherPK implements java.io.Serializable{
    private int id;
    private String name;
。。。。。。。
}
//Teacher .java
@Entity
public class Teacher {

    private TeacherPK pk;
.......................

    @Id
    public TeacherPK getPk() {
        return pk;
    }
    public void setPk(TeacherPK pk) {
        this.pk = pk;
    }
}

方法2:

新的TeacherPK 类无需加注解,只需在原Teacher类新属性“TercherPK”的get方法前写@EmbeddedlD即可

@EmbeddedId
    public TeacherPK getPk() {
        return pk;
    }
    public void setPk(TeacherPK pk) {
        this.pk = pk;
    }

方法3:

新TeacherPK 类无需加注解,原Teacher类的id,name属性保留不变,也无需新增“TercherPK”属性。 只在id,name的get方法前都加@Id,并在原Teacher类前加“@IdClass(TeacherPK.class)”

@IdClass(TeacherPK.class)
public class Teacher {

    private int id;

    private String name;
    。。。。。

    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @Id
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
。。。。。。
}
时间: 2024-10-25 21:28:04

Hibernate学习笔记_联合主键的相关文章

Hibernate 查询排序与联合主键映射

1.查询排序 (1)数据库排序(推荐) <map order-by="name ase" > <!--name的升序,降序desc--> session.createQuery(" ").uniqueResult() //返回唯一的对象,前台对象只有一个 <set order-by="name asc"> (2)内存排序 <set sort="natural" > sort属性值

Hibernate(5)—— 联合主键 、一对一关联关系映射(xml和注解) 和 领域驱动设计

俗话说,自己写的代码,6个月后也是别人的代码……复习!复习!复习!涉及的知识点总结如下: One to One 映射关系 一对一单向外键(XML/Annotation) 一对一双向外键关联(XML/Annotation) 联合主键 一对一单向外键联合主键(Xml/Annotation) 一对一组件关联(XML/Annotation) 理解组件 领域驱动设计——自动生成数据库脚本 一对一关系的小结 一些出错问题的总结 自动生成数据库脚本 一般在项目开发过程中,我们的习惯是先建好数据库和表,然后在进

Hibernate学习笔记_关系映射

    一对一关联     一,     一对一单向外键关联 a)    Annotation: 在被约束表字段的get方法上加@0ne20ne @JoinColumn //Husband .java @Entity public class Husband { private int id; private String name; private Wife wife; @Id @GeneratedValue public int getId() { return id; } public S

hibernate框架学习笔记4:主键生成策略、对象状态

创建一个实体类: package domain; public class Customer { private Long cust_id; private String cust_name; private String cust_source; private String cust_industry; private String cust_level; private String cust_linkman; private String cust_phone; private Stri

CUBRID学习笔记 14 删除主键错误

发生这样的问题.其实和别的数据库基本原因差不多.  就是外键冲突. 看看有没有外键引用这个表的主键. 然后删除外键. 就可以了 SELECT class_name FROM db_index WHERE index_name = 'fk_game_athlete_code'; ALTER TABLE game DROP FOREIGN KEY fk_game_athlete_code; ALTER TABLE game ADD CONSTRAINT FOREIGN KEY ("athlete_c

Hibernate学习笔记_查询

HQL vs EJBQL 1         NativeSQL >HQL.> EJBQL(JPQL 1.0) > QBC(Query By Criteria) > QBE(Query By Example)" 2         总结:QL应该和导航关系结合,共同为査询提供服务. @Test public void testHQL_01() { Session session = sf.openSession(); session.beginTransaction();

Hibernate学习笔记_事务

 事务并发处理(面试的意义更大)                        a)   事务:ACID i.   Atomic(原子性) Consistency(一致性) Isolation(隔离性) Durability(独立性) b)   事务并发时可能出现的问题: 第一类丢失更新(Lost Update) 时间 取款事务A 存款事务B T1 开始事务   T2   开始事务 T3 查询账户余额为1000元   T4   查询账户余额为1000元 T5   汇入100元把余额改为1100元

Hibernate学习笔记_缓存

一级缓存和二级缓存和査询缓存(面试题)                 a)    什么是缓存 b)    什么是一级缓存,session级别的缓存 c)    什么是二级缓存,SessionFactory级别的缓存,可以跨越session存在 i.   经常被访间 ii.   改动不大不会经常改动 iii.   数重有限 d)    打开二级缓存 i.   hibernate.cfg.xml 设定: <property name= "cache.use_second_level_cach

hibernate学习笔记_基础配置

一.hibernate.cfg.xml: hbni2ddl.auto 二.搭建日志环境并配置显示DDL语句 我们使用slf接口,然后使用log4j的实现. 1.  首先引入log4j的jar包(log4j-1.2.14.jar), 2.  然后再引入slf4j实现LOG4J和适配器jar包(slf4j-log4j12-1.5.8.jar) 3.  最后创建log4j的配置文件(log4j.properties),并加以修改,只要保留 log4j.logger.org.hibernate.tool