一、关于联合主键的映射测试实例
实体类:
package com.***.comBineKey;
public class Person {
private Person_pk pk;
private long age;
public Person_pk getPk() {
return pk;
}
public void setPk(Person_pk pk) {
this.pk = pk;
}
public long getAge() {
return age;
}
public void setAge(long age) {
this.age = age;
}
}
联合主键类:
package com.***.comBineKey;
import java.io.Serializable;
/**
* 联合主键映射测试实例
* @author Victor
*
*/
public class Person_pk implements Serializable{
/**
* 实现序列化接口
* 判断两个对象是否相等【解决方法:重写equals方法,最好再重写hasCode方法加快解析速度(hasCode只比较ID)】
*/
private static final long serialVersionUID = 1L;
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int hasCode(){
return (int)id;//hasCode只会和id比较
}
public boolean equals(Object obj){
if(obj==null){
return false;
}
if(this==obj){
return true;
}
Person_pk person_pk=(Person_pk) obj;
if(!(obj instanceof Person_pk)){
return false;
}
if(this.id==person_pk.id && this.name.equals(person_pk.name)){
return true;
}
return false;
}
}
测试类:
package com.***.hibernateTest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PersonTest {
private SessionFactory sf;
private Session session;
private Transaction tran;
@Before
public void before(){
Configuration con=new Configuration().configure();
sf=con.buildSessionFactory();
session=sf.openSession();
tran=session.beginTransaction();
}
@After
public void after(){
//把SQL语句刷到数据库,执行的是单纯的SQL语句
//把对象刷到数据库中,调用对象的get方法
//给?占位符赋值
tran.commit();
//关闭session【因为session不安全】
//也会提交事务
session.close();
}
@Test
public void AutoCreateTable() {
try {
Configuration con=new Configuration().configure("hibernate.cfg.xml");
SchemaExport create=new SchemaExport(con);
create.create(false, true);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
配置文件:
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.***.comBineKey.Person" table="pk_person">
<composite-id name="pk" class="com.***.comBineKey.Person_pk">
<key-property name="id"/>
<key-property name="name"/>
</composite-id>
<property name="age"/>
</class>
</hibernate-mapping>
二、类与类之间的关系:
<一>、一对一单向关联
实体类一:
实体类二:
配置文件一:
配置文件二:
测试类: