package com.hibernate_onetoonepk;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="t_stu")
public class Students { //在数据库表中是主表 id为主键被 sid表中的stuId应用
private String id;
private String name;
private StuID stuid;
@Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToOne(mappedBy="stu")
public StuID getStuid() {
return stuid;
}
public void setStuid(StuID stuid) {
this.stuid = stuid;
}
}
package com.hibernate_onetoonepk;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="t_sid")
public class StuID {
private int id;
private Students stu;
@OneToOne
@JoinColumn(name="stuId")
public Students getStu() {
return stu;
}
public void setStu(Students stu) {
this.stu = stu;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.hibernate_onetoonepk;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class Test { //测试
public static void main(String[] args) {
AnnotationConfiguration af = new AnnotationConfiguration();
SessionFactory sf = af.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
// StuID id = new StuID();
// Students stu = new Students();
// stu.setId("2223");
// stu.setName("yyy");
// //id.setId(1);
// id.setStu(stu);
//
// session.save(stu);
// session.save(id);
Students stu = (Students)session.get(Students.class, "2222");
System.out.println(stu.getName());
System.out.println(stu.getStuid().getId());
session.beginTransaction().commit();
}
}
//一下为hibernate.cfg.xml的配置
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- <mapping resource="com/hibernate/po/User.hbm.xml"/> -->
<mapping class="com.hibernate_onetoonepk.Students"></mapping>
<mapping class="com.hibernate_onetoonepk.StuID"></mapping>
</session-factory>
</hibernate-configuration>