Hibernate中联合主键生成策略(一)

2015-01-27 22:37:38 · 作者: · 浏览: 31

一、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配置联合主键

































(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.j