`

联合主键--Annotation

阅读更多

联合主键Annotation配置方法有三种:

1.将组件类注解为@EmbeddedId,并将组建的属性注解为@Id

2.将组件的属性注解为@EmbeddeId

3.将类注解为@IdClass,并将该实体中所有的主键的属性都注解为@Id

 

第一种:

1.定义注解类并其直接为@Embeddable

package com.zchen.hibernate.sxt.domain;

import java.io.Serializable;

import javax.persistence.Embeddable;

@Embeddable
public class StudentPK implements Serializable{
	private static final long serialVersionUID = -7880746333829652369L;
	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();
	}*/
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		StudentPK other = (StudentPK) obj;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}

 2.定义实体类,将注解类放入其中并注解为@Id

package com.zchen.hibernate.sxt.domain;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="T_STUDENTS")
public class Students {
	private StudentPK pk;

	@Id
	public StudentPK getPk() {
		return pk;
	}

	public void setPk(StudentPK pk) {
		this.pk = pk;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	private int age;

	private String address;

}

 3.定义Hibernate.cfg.xml配置文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		 <property name="connection.url">jdbc:mysql:///db_czbk_hibernate</property>
		 <property name="connection.username">root</property>
		 <property name="connection.password">1234</property>
		 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		 <property name="hbm2ddl.auto">create</property>
		 <property name="current_session_context_class">thread</property>
		 <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		 <property name="show_sql">true</property>
		 <mapping class="com.zchen.hibernate.sxt.domain.Students"/>
		 
	</session-factory>
</hibernate-configuration>

 

4.测试:

package com.zchen.hibernate.sxt.test;

import org.hibernate.HibernateException;
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;

import com.zchen.hibernate.sxt.domain.StudentPK;
import com.zchen.hibernate.sxt.domain.Students;


public class StudentsTest {
	
	private static SessionFactory sf = null;
	
	@BeforeClass
	public static void beforeClass(){
		try {
			sf = new AnnotationConfiguration().configure().buildSessionFactory();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void addStduentTest(){
		StudentPK pk = new StudentPK();
		pk.setId(2);
		pk.setName("chen");
		
		Students s = new Students();
		s.setAge(20);
		s.setAddress("湖南");
		s.setPk(pk);

		Session session = sf.getCurrentSession();
		session.beginTransaction();
		
		session.save(s);
		
		session.getTransaction().commit();
	}
	
	@AfterClass
	public static void afterClass(){
		if(sf != null){
			try {
				sf.close();
			} catch (HibernateException e) {
				e.printStackTrace();
			}
		}
	}


}

 

第二种:

1.定义主键类

package com.zchen.hibernate.sxt.domain;

import java.io.Serializable;

import javax.persistence.Embeddable;

//1.@Embeddable
public class StudentPK implements Serializable{
	private static final long serialVersionUID = -7880746333829652369L;
	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();
	}*/
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		StudentPK other = (StudentPK) obj;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}

 2.定义实体类

package com.zchen.hibernate.sxt.domain;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="T_STUDENTS")
public class Students {
	private StudentPK pk;

	//@Id
	@EmbeddedId
	public StudentPK getPk() {
		return pk;
	}

	public void setPk(StudentPK pk) {
		this.pk = pk;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	private int age;

	private String address;

}

 

 

第三种:

1.定义主键类:

package com.zchen.hibernate.sxt.domain;

import java.io.Serializable;

import javax.persistence.Embeddable;

public class StudentPK implements Serializable{
	private static final long serialVersionUID = -7880746333829652369L;
	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();
	}*/
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		StudentPK other = (StudentPK) obj;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}

 

2.定义实体类:

package com.zchen.hibernate.sxt.domain;

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

@Entity
@Table(name="T_STUDENTS")
@IdClass(value=StudentPK.class)
public class Students {
	/*private StudentPK pk;

	//@Id
	@EmbeddedId
	public StudentPK getPk() {
		return pk;
	}

	public void setPk(StudentPK pk) {
		this.pk = pk;
	}*/

	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;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	private int age;

	private String address;

}

3.测试用例:

package com.zchen.hibernate.sxt.test;

import org.hibernate.HibernateException;
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;

import com.zchen.hibernate.sxt.domain.StudentPK;
import com.zchen.hibernate.sxt.domain.Students;


public class StudentsTest {
	
	private static SessionFactory sf = null;
	
	@BeforeClass
	public static void beforeClass(){
		try {
			sf = new AnnotationConfiguration().configure().buildSessionFactory();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void addStduentTest(){
		/*StudentPK pk = new StudentPK();
		pk.setId(3);
		pk.setName("aaa");*/
		
		Students s = new Students();
		s.setId(4);
		s.setName("pig");
		s.setAge(20);
		s.setAddress("湖南");
		//s.setPk(pk);

		Session session = sf.getCurrentSession();
		session.beginTransaction();
		
		session.save(s);
		
		session.getTransaction().commit();
	}
	
	@AfterClass
	public static void afterClass(){
		if(sf != null){
			try {
				sf.close();
			} catch (HibernateException e) {
				e.printStackTrace();
			}
		}
	}


}

 

 

 

分享到:
评论

相关推荐

    Hibernate一对一单向外键关联 (联合主键annotation)

    本篇将详细讲解如何使用Hibernate进行一对一单向外键关联,并且该关联涉及到联合主键的注解配置。 首先,一对一关联可以分为两种类型:单向和双向。在单向一对一关联中,只有一个实体知道另一个实体的存在,而另一...

    hibernate-annotation-3.2.1

    4. **继承策略**:Hibernate支持单表继承(`@Inheritance(strategy = InheritanceType.SINGLE_TABLE)`)、联合继承(`@Inheritance(strategy = InheritanceType.JOINED)`)和分表继承(`@Inheritance(strategy = ...

    最全的Hibernate Annotation API文档

    Hibernate支持单表继承、联合继承和多表继承。可以使用`@Inheritance`、`@DiscriminatorValue`等注解进行配置。 九、转换器(Converters) 使用`@Converter`注解可以自定义类型转换,处理自定义类型或枚举类型与...

    Hibernate Annotation 学习笔记

    - Hibernate支持单表继承(Single Table Inheritance, STI)、联合继承(Union Subclassing, USI)和表-per类继承(Table Per Concrete Class, TPC)。 - `@Inheritance(strategy = InheritanceType.SINGLE_TABLE)...

    hibernate_annotation

    5.1 InheritanceType:支持单表继承、联合继承和表-per-class策略,通过@Entity和@Inheritance注解实现: ```java @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public abstract class Person { ...

    Hibernate Annotation应用

    7. **继承映射**:Hibernate支持单表继承(SINGLE_TABLE)、联合继承(JOINED)和表-per-hierarchy(TABLE_PER_CLASS)。使用`@Inheritance`和`@DiscriminatorColumn`、`@DiscriminatorValue`注解可以定义继承策略。...

    Hibernate annotation 详解

    自Hibernate 3开始,引入了注解(Annotation)支持,使得开发者无需XML配置就能实现对象与数据库表之间的映射。本文将深入探讨Hibernate注解的使用方法和常见注解,旨在帮助开发者更好地理解和应用Hibernate注解。 ...

    Hibernate关联关系的CRUD和集合映射(annotation)

    5. **@JoinTable**:在多对多关系中,用于定义中间表的详细信息,包括联合主键等。 ### 集合映射的加载策略 Hibernate提供了多种加载策略,例如: - **EAGER**:集合会在主对象加载时一起加载,适合小规模数据。 ...

    Hibernate笔记 马士兵

    第1课 课程内容 6 第2课 Hibernate UML图 6 第3课 风格 7 第4课 资源 7 第5课 环境准备 7 ...三、 联合主键 24 1、xml方式 24 2、annotation方式 27 第14课 Hibernate核心开发接口(重点) 29 ........

    Hibernate annotations大全

    1. Hibernate Annotation 概述 Hibernate Annotations是Hibernate框架中的一种元数据表示方式,它允许开发者在Java实体类上直接添加注解,替代传统的XML配置文件来描述对象关系映射(ORM)。这种方式使得ORM配置更加...

    django-1.3-cheetsheet

    #### 二、聚合与注释函数(Aggregation/Annotation Functions) 聚合与注释函数可以用来对查询结果进行计算和统计。 1. **`Avg(field)`**:计算指定字段的平均值。 - 示例:`Customer.objects.all().aggregate...

    hibernate学习笔记

    同时,探讨联合主键的概念及其在实际应用中的重要性。 #### 六、Hibernate核心开发接口深度剖析 - **API概览**:深入研究Hibernate API文档,重点关注`Configuration`、`SessionFactory`、`Session`、`SchemaExport...

    hibenate5.0开发者文档

    - **Annotation配置**: 使用Java注解来替代XML配置,更加简洁且易于维护。 **3. 数据库操作** - **CRUD操作**: Create(创建)、Read(读取)、Update(更新)、Delete(删除)是基本的数据库操作。Hibernate通过...

    eib3.0中的注解

    - **定义**:当需要使用多个属性变量(表中的多列)联合起来作为主键时,就需要使用复合主键。复合主键要求开发者自定义一个复合主键类。 - **示例**: ```java @Embeddable public class CompositeKey ...

    EJB 注释精解(pdf版)

    复合主键是指使用多个属性变量(表中的多列)联合起来作为主键。为了实现复合主键,需要编写一个复合主键类(CompositePrimaryKeyClass),并遵循以下规则: - **复合主键类要求**: - 必须实现`Serializable`接口...

    Hibernate ORM 5.2.7.Final User Guide

    - **Annotation配置**: 使用@Entity、@Table等注解,以及@EntityListeners等,实现对实体的元数据注解配置。 **3. 数据库映射** - **实体类映射**: 如何定义实体类,包括属性、构造函数、setter/getter方法等。 - *...

    马士兵hibernate笔记

    第13课专注于ID主键的生成策略,包括Xml方式和AnnotateOn方式,如AUTO、IDENTITY、SEQUENCE、TABLE等策略,并讨论了联合主键的配置。 第14课是核心内容,介绍了Hibernate的主要开发接口,如`Configuration...

    hibernate所有开发包

    1. Entity:通过@Entity注解标记的类表示数据库表,@Id标注主键字段,@GeneratedValue指定自增策略。 2. Table/Column:使用@Table和@Column注解来指定表名和字段名,其他如@Temporal、@Lob等注解用于特殊类型的映射...

Global site tag (gtag.js) - Google Analytics