总结个
hibernate联合
主键的创建方式,刚看完兵爷的视频,赶紧弄下来。冬爷,赶紧膜拜知道不?我这弄下来是为了明天面试,压力大很知道不?
联合主键,讲一张表中两个属性同时作为主键。
student.java
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.IdClass;
@Entity
@IdClass(value=StudentPK.
class)
public class Student {
//@EmbeddedId
//private StudentPK pk;
@Id
private int id;
@Id
private String name;
// public StudentPK getPk() {
// return pk;
// }
// public void setPk(StudentPK pk) {
// this.pk = pk;
// }
private int age;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
还有另外一个类专门设立有关主键的两个变量。
studentPK.java
package com.hibernate.finalmodel;
import java.io.Serializable;
import javax.persistence.Embeddable;
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.equals(pk.getName()))
return true;
}
return false;
}
public int hashCode() {
return this.name.hashCode();
}
}
这里必须重写equals和hashcode方法。重写hashcode是要定位name属性是否一致,在
内存中,hashcode相同的对象线性储存。找到相同的hashcode后,在比较equals,从而得到联合主键的比较结果。
写一个单元测试
TestBase.java
package com.hibernate.finaltest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.hibernate.finalmodel.Student;
import com.hibernate.finalmodel.StudentPK;
public class TestBase {
private static SessionFactory sessionFactory = null;
Session session;
@BeforeClass
public static void preMethod() {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
// if(session == null)
// session = sessionFactory.openSession();
// else
// session = sessionFactory.getCurrentSession();
}
@AfterClass
public static void postMethod() {
sessionFactory.close();
}
@Test
public void testMethod() {
System.out.println("start create student");
session = sessionFactory.openSession();
// Student s = new Student();
// s.setAge(23);
// s.setName("samuel");
StudentPK pk = new StudentPK();
pk.setId(1);
pk.setName("Andrew");
Student s = new Student();
//s.setPk(pk);
s.setAge(7);
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
}
}
[/code
测试成功。就这么多了。明天面试就就扯这个了。