`
chinrui
  • 浏览: 96777 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Annotation使用两个foreign key做联合主键

阅读更多
Annotation使用两个foreign key做联合主键

1、 数据库里面的表结构
学生:(Id , Name)
课程:(Id , Name)
选课表:(Student_ID , Course_ID , Score)
2、 Student类
package com.edu.hpu;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="_student")
public class Student {

	private int id;
	private String name;
	private Set<Course> courses  = new HashSet<Course>();
	
	@Id
	@GeneratedValue
	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;
	}
	
	@ManyToMany
	@JoinTable(name="_score" ,
		joinColumns=@JoinColumn(name="student_ID"),
		inverseJoinColumns=@JoinColumn(name="course_ID")
	)
	public Set<Course> getCourses() {
		return courses;
	}
	public void setCourses(Set<Course> courses) {
		this.courses = courses;
	}
}

3、 Course类
package com.edu.hpu;

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

@Entity
@Table(name="_course")
public class Course {

	private int id;
	private String name;
	
	@Id
	@GeneratedValue
	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;
	}
	
}

4、 Score类以及PK类
package com.edu.hpu;

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

@Entity
@Table(name="_score")
public class Score {

	private int score;
	private PK pk;
	
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	
	@Id
	public PK getPk() {
		return pk;
	}
	public void setPk(PK pk) {
		this.pk = pk;
	}
}

package com.edu.hpu;

import java.io.Serializable;

import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Embeddable
public class PK implements Serializable {

	private Student student;
	private Course course;
	
	@ManyToOne
	@JoinColumn(name="student_ID")
	public Student getStudent() {
		return student;
	}
	public void setStudent(Student student) {
		this.student = student;
	}
	
	@ManyToOne
	@JoinColumn(name="course_ID")
	public Course getCourse() {
		return course;
	}
	public void setCourse(Course course) {
		this.course = course;
	}
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof PK) {
			PK pk = (PK)obj;
			if(pk.getCourse().getId() == this.getCourse().getId() && pk.getStudent().getId() == this.getStudent().getId()) {
				return true;
			}
		}
		return false;
	}
	@Override
	public int hashCode() {
		return student.getName().hashCode() + course.getName().hashCode();
	}
}

5、 测试生成表类(Junit)
package com.edu.hpu;

import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestWork {

	private static SessionFactory sf = null;
	
	@BeforeClass
	public static void beforeClass() {
		Configuration conf = new Configuration().configure();
		ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
		sf = conf.buildSessionFactory(sr);
	}
	
	@Test
	public void testExport() {
		new SchemaExport(new Configuration().configure()).create(true , true);
	}
	
	@Test
	public void testSave() {
		Course co = new Course();
		co.setName("C++");
		Student st = new Student();
		st.setName("qinrui");
		st.setId(1);
		
		Score sc = new Score();
		PK pk = new PK();
		pk.setCourse(co);
		pk.setStudent(st);
		sc.setPk(pk);
		sc.setScore(98);
		
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		session.save(co);
		session.save(st);
		session.save(sc);
		session.getTransaction().commit();
	}
	
	@Test
	public void testGet() {
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		Student st = (Student)session.get(Student.class, 6);
		Set<Course> courses = st.getCourses();
		for(Course cou : courses) {
			System.out.println(cou.getName());
		}
		session.getTransaction().commit();
	}
	
	@AfterClass
	public static void afterClass() {
		sf.close();
	}
}

6、 Hiberante.cfg.xml配置
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mima</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        
        <property name="format_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <!--<property name="hbm2ddl.auto">update</property>-->

        <!--<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>-->
        
        <!--<mapping resource="com/edu/hpu/Husband.hbm.xml" />-->
        <!--
        <mapping resource="com/edu/hpu/Teacher.hbm.xml" />
        <mapping resource="com/edu/hpu/Student.hbm.xml" />
        -->
        <mapping class="com.edu.hpu.Student" />
        <mapping class="com.edu.hpu.Course" />
        <mapping class="com.edu.hpu.Score" />
        
        
    </session-factory>

</hibernate-configuration>

7、 生成的建表语句
create table _course (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )

    create table _score (
        score integer not null,
        course_ID integer,
        student_ID integer,
        primary key (student_ID, course_ID)
    )

    create table _student (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )

    alter table _score 
        add index FKA89FA193A2A75DE0 (course_ID), 
        add constraint FKA89FA193A2A75DE0 
        foreign key (course_ID) 
        references _course (id)

    alter table _score 
        add index FKA89FA19337241E94 (student_ID), 
        add constraint FKA89FA19337241E94 
        foreign key (student_ID) 
        references _student (id)

分享到:
评论

相关推荐

    最全Hibernate 参考文档

    10.9. 在两个不同数据库间复制对象 10.10. Session刷出(flush) 10.11. 传播性持久化(transitive persistence) 10.12. 使用元数据 11. 事务和并发 11.1. Session和事务范围(transaction scopes) 11.1.1. 操作单元...

    Hibernate3的帮助文档

    详细的Hibernate3的帮助文档 前言 1. 翻译说明 2. 版权声明 1. 在Tomcat中快速上手 1.1. 开始Hibernate之旅 1.2. 第一个持久化类 1.3. 映射cat 1.4. 与Cat同乐 ...11.9. 在两个不同数据库间复制对象

    hibernate 框架详解

    在两个不同数据库间复制对象 11.10. Session刷出(flush) 11.11. 传播性持久化(transitive persistence) 11.12. 使用元数据 12. 事务和并发 12.1. Session和事务范围(transaction scopes) 12.1.1. 操作单元...

    hibernate 体系结构与配置 参考文档(html)

    在两个不同数据库间复制对象 10.10. Session刷出(flush) 10.11. 传播性持久化(transitive persistence) 10.12. 使用元数据 11. 事务和并发 11.1. Session和事务范围(transaction scope) 11.1.1. 操作单元(Unit...

    Hibernate 中文 html 帮助文档

    10.9. 在两个不同数据库间复制对象 10.10. Session刷出(flush) 10.11. 传播性持久化(transitive persistence) 10.12. 使用元数据 11. 事务和并发 11.1. Session和事务范围(transaction scope) 11.1.1. 操作单元(Unit...

    hibernate3.04中文文档.chm

    11.9. 在两个不同数据库间复制对象 11.10. Session刷出(flush) 11.11. 传播性持久化(transitive persistence) 11.12. 使用元数据 12. 事务和并发 12.1. Session和事务范围(transaction scopes) 12.1.1. 操作...

    Hibernate教程

    11.9. 在两个不同数据库间复制对象 11.10. Session刷出(flush) 11.11. 传播性持久化(transitive persistence) 11.12. 使用元数据 12. 事务和并发 12.1. Session和事务范围(transaction scopes) 12.1.1. 操作...

    Hibernate3+中文参考文档

    10.9. 在两个不同数据库间复制对象 10.10. Session刷出(flush) 10.11. 传播性持久化(transitive persistence) 10.12. 使用元数据 11. 事务和并发 11.1. Session和事务范围(transaction scopes) 11.1.1. 操作单元...

    Hibernate参考文档

    10.9. 在两个不同数据库间复制对象 10.10. Session刷出(flush) 10.11. 传播性持久化(transitive persistence) 10.12. 使用元数据 11. 事务和并发 11.1. Session和事务范围(transaction scope) 11.1.1. 操作单元(Unit...

Global site tag (gtag.js) - Google Analytics