Hibernate中联合主键生成策略

一、xml配置联合主键

单独设计一个类,作为主键类,如StudentPK

A、实现序列化(Serializable接口)

B、重写equals()hashCode()

为什么要从写equals()hashCode()方法?

hashCode相同的会被存储在hash表的同一位置,当找到特定的hashcode之后,会根据equals()方法判断是否是相同的对象,来查找到对应的数据。

小实验1

(1)创建联合主键类StudentPK

package com.zgy.hibernate.model;

 

import java.io.Serializable;

 

public class StudentPK implements 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;

}

public boolean equals(Object o){

if(o instanceof StudentPK){

StudentPK pk = (StudentPK)o;

if(this.id == pk.getId() && this.name == pk.getName()){

return true;

}

}

return false;

}

public int hashCode(){

return this.name.hashCode();

}

}

 

(2) 使用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.zgy.hibernate.model">

<class name="Student" table="student">

<!-- <id name="id" column="id">

<generator class="native"></generator>

</id>

<property name="name" column="name"></property>

 -->

 

 <!-- 联合主键的配置方式 -->

 <composite-id name="pk" class="com.zgy.hibernate.model.StudentPK">

  <key-property name="id"></key-property>

  <key-property name="name"></key-property>

 </composite-id>

<property name="age" column="age"></property>

<property name="score" column="score"></property>

</class>

</hibernate-mapping>

(3)编写测试程序

package com.zgy.hibernate.model;

 

import static org.junit.Assert.*;

 

import java.util.Date;

 

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;

import org.junit.AfterClass;

import org.junit.BeforeClass;

import org.junit.Test;

 

public class HibernateIDTest {

 

public static SessionFactory sf = null;

@BeforeClass

public static void beforeClass(){

sf = new AnnotationConfiguration().configure().buildSessionFactory();

}

@Test

public void testStudent() {

 

StudentPK pk = new StudentPK();

pk.setId(1);

pk.setName("zhangsan");

Student s = new Student();

s.setPk(pk);

// s.setName("张三");

s.setAge(20);

s.setScore(90);

Session session = sf.openSession();

session.beginTransaction();

session.save(s);

session.getTransaction().commit();

session.close();

}

 

@AfterClass

public static void afterClass(){

sf.close();

}

 

}

 

二、Annotation配置联合主键

方法一:使用@Embeddable

在联合主键类上,配置@Embeddable

Teacher.java中,getPk()上写@Id

小实验2

(1)创建TeacherPK.java

package com.zgy.hibernate.model;

 

import java.io.Serializable;

 

import javax.persistence.Embeddable;

@Embeddable

public class TeacherPK implements 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;

}

public boolean equals(Object o){

if(o instanceof TeacherPK){

TeacherPK pk = (TeacherPK)o;

if(this.id == pk.getId() && this.name == pk.getName()){

return true;

}

}

return false;

}

public int hashCode(){

return this.name.hashCode();

}

}

 

(2)测试

package com.zgy.hibernate.model;

 

import static org.junit.Assert.*;

 

import java.util.Date;

 

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;

import org.hibernate.cfg.Configuration;

import org.junit.AfterClass;

import org.junit.BeforeClass;

import org.junit.Test;

 

public class TeacherTesting {

public static SessionFactory sf = null;

@BeforeClass

public static void beforeClass(){

sf = new AnnotationConfiguration().configure().buildSessionFactory();

}

@Test

public void test() {

TeacherPK pk = new TeacherPK();

pk.setId(1);

pk.setName("t1");

Teacher t = new Teacher();

t.setPk(pk);

// t.setName("t1");

t.setTitle("高级");

t.setAddress("北京");

t.setBirth(new Date());

t.setZhiCheng(ZhiCheng.A);

Session session = sf.openSession();

session.beginTransaction();

session.save(t);

session.getTransaction().commit();

session.close();

}

 

@AfterClass

public static void afterClass(){

sf.close();

}

}

 

(3)查看结果

 

select * from teacher;

desc teacher;

 

 

 

方法二:在方法上添加@EmbeddedId

直接在Teacher.java中的getPK()方法上添加@EmbeddedId

小实验3:

(1)修改Teacher.java

package com.zgy.hibernate.model;

 

import java.util.Date;

 

import javax.annotation.Generated;

import javax.persistence.Column;

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.Id;

import javax.persistence.Table;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;

import javax.persistence.Transient;

 

@Entity

@javax.persistence.TableGenerator(

name="Teacher_GEN",

table="GENERATOR_TABLE",

pkColumnName="pkkey",

valueColumnName="pkvalue",

pkColumnValue="Teacher",

allocationSize=1

)

public class Teacher {

// private int id;

// private String name;

private String title;

private String address;

private String wifeName;

private Date birth;

private ZhiCheng zhiCheng;

@Id

@GeneratedValue(strategy=GenerationType.TABLE,generator="Teacher_GEN")

// public int getId() {

// return id;

// }

// public void setId(int id) {

// this.id = id;

// }

// @Column(name="_name")

// public String getName() {

// return name;

// }

// public void setName(String name) {

// this.name = name;

// }

private TeacherPK pk;

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

 

public String getWifeName() {

return wifeName;

}

public void setWifeName(String wifeName) {

this.wifeName = wifeName;

}

@Temporal(TemporalType.DATE)

public Date getBirth() {

return birth;

}

public void setBirth(Date birth) {

this.birth = birth;

}

@Enumerated(EnumType.STRING)

public ZhiCheng getZhiCheng() {

return zhiCheng;

}

public void setZhiCheng(ZhiCheng zhiCheng) {

this.zhiCheng = zhiCheng;

}

@EmbeddedId

public TeacherPK getPk() {

return pk;

}

public void setPk(TeacherPK pk) {

this.pk = pk;

}

 

}

 

(2)测试

(3)查看结果

 

select * from teacher;

desc teacher;

 

 

 

方法三:

(1)在Teacher.java中修改,在getId(),getName()上添加@Id,在Teacher类名称上添加@IdClass(value=TeacherPK.class)

package com.zgy.hibernate.model;

 

import java.util.Date;

 

import javax.annotation.Generated;

import javax.persistence.Column;

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.Id;

import javax.persistence.IdClass;

import javax.persistence.Table;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;

import javax.persistence.Transient;

 

@Entity

@javax.persistence.TableGenerator(

name="Teacher_GEN",

table="GENERATOR_TABLE",

pkColumnName="pkkey",

valueColumnName="pkvalue",

pkColumnValue="Teacher",

allocationSize=1

)

@IdClass(value=TeacherPK.class)

public class Teacher {

private int id;

private String name;

private String title;

private String address;

private String wifeName;

private Date birth;

private ZhiCheng zhiCheng;

@Id

// @GeneratedValue(strategy=GenerationType.TABLE,generator="Teacher_GEN")

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

@Column(name="_name")

@Id

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

private TeacherPK pk;

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

 

public String getWifeName() {

return wifeName;

}

public void setWifeName(String wifeName) {

this.wifeName = wifeName;

}

@Temporal(TemporalType.DATE)

public Date getBirth() {

return birth;

}

public void setBirth(Date birth) {

this.birth = birth;

}

@Enumerated(EnumType.STRING)

public ZhiCheng getZhiCheng() {

return zhiCheng;

}

public void setZhiCheng(ZhiCheng zhiCheng) {

this.zhiCheng = zhiCheng;

}

/*

 @EmbeddedId

public TeacherPK getPk() {

return pk;

}

public void setPk(TeacherPK pk) {

this.pk = pk;

}

 */

}

 

(2)测试

(3)查看结果

 

 select * from teacher;

 desc teacher;

 

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。