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)

你可能感兴趣的:(java,Hibernate,composite_id)