> 데이터 베이스 > MySQL 튜토리얼 > Hibernate中联合主键生成策略

Hibernate中联合主键生成策略

WBOY
풀어 주다: 2016-06-07 16:13:13
원래의
1114명이 탐색했습니다.

一、xml配置联合主键 单独设计一个类,作为主键类,如StudentPK A、实现序列化(Serializable接口) B、重写equals()和hashCode() 为什么要从写equals()和hashCode()方法? hashCode相同的会被存储在hash表的同一位置,当找到特定的hashcode之后,会根据equa

一、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【本文来自鸿网互联 (http://www.68idc.cn)】 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;

 

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿