唯一外键关联
一.单向一对一关联
1.数据模型如下图所示:
2.数据表sql
DROP TABLE T_User;
DROP TABLE T_Group;
CREATE TABLE T_Group (
id INT NOT NULL AUTO_INCREMENT
, name VARCHAR(50)
, PRIMARY KEY (id)
);
CREATE TABLE T_User (
id INT NOT NULL AUTO_INCREMENT
, name VARCHAR(50)
, age INT
, group_id INT NOT NULL
, PRIMARY KEY (id)
, INDEX (group_id)
, CONSTRAINT FK_T_User_1 FOREIGN KEY (group_id)
REFERENCES T_Group (id)
);
3.POJO类
TUser.java
package cn.blogjava.start;
public class TUser implements java.io.Serializable {
// Fields
private Integer id;
private Integer age;
private String name;
private TGroup group;
// Constructors
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public TGroup getGroup() {
return group;
}
public void setGroup(TGroup group) {
this.group = group;
}
/** default constructor */
public TUser() {
}
/** constructor with id */
public TUser(Integer id) {
this.id = id;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
TGroup.java
package cn.blogjava.start;
import java.io.Serializable;
public class TGroup implements Serializable {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.配置文件
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="cn/blogjava/start/TUser.hbm.xml" />
<mapping resource="cn/blogjava/start/TGroup.hbm.xml" />
</session-factory>
</hibernate-configuration>
TGroup.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.blogjava.start.TGroup" table="T_Group" catalog="sample">
<id name="id" type="integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="string" column="name" />
</class>
</hibernate-mapping>
TUser.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.blogjava.start.TUser" table="T_User" catalog="sample">
<id name="id" type="integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="string">
<column name="name" length="100" not-null="true" />
</property>
<property name="age" type="java.lang.Integer" column="age" />
<many-to-one name="group"
class="cn.blogjava.start.TGroup"
column="GROUP_ID"
cascade="all"
unique="true"
/>
</class>
</hibernate-mapping>
4.测试代码
package cn.blogjava.start;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateTest extends TestCase {
Session session = null;
protected void setUp() {
try {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();
} catch (HibernateException e) {
e.printStackTrace();
}
}
protected void tearDown() {
try {
session.close();
} catch (HibernateException e) {
e.printStackTrace();
}
}
/**
* 对象持久化测试(Insert方法)
*/
public void testInsert() {
Transaction tran = null;
try {
TUser user = new TUser();
user.setName("byf");
user.setAge(new Integer(26));
TGroup group = new TGroup();
group.setName("Admin");
// 如果在配置文件中没有cascade="all",就要先插入group信息
// tran = session.beginTransaction();
// session.save(group);
// session.flush();
// tran.commit();
tran = session.beginTransaction();
//设置关联
user.setGroup(group);
//插入user信息
session.save(user);
session.flush();
tran.commit();
Assert.assertEquals(user.getId().intValue()>0 ,true);
} catch (HibernateException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
if(tran != null) {
try {
tran.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
/**
* 对象读取测试(Select方法)
*/
public void testSelect(){
String hql = " from TUser where name='byf'";
try {
List userList = session.createQuery(hql).list();
TUser user = (TUser)userList.get(0);
System.out.println("user name is " + user.getName());
System.out.println("user group is " + user.getGroup().getName());
Assert.assertEquals(user.getName(), "byf");
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
}
二.双向一对一关联
需要对TGroup.java和TGroup.hbm.xml文件作修改
1.在TGroup.java中增加一个TUser类和相应的getter、setter方法
TGroup.java
package cn.blogjava.start;
import java.io.Serializable;
public class TGroup implements Serializable {
private Integer id;
private String name;
private TUser user;
public TUser getUser() {
return user;
}
public void setUser(TUser user) {
this.user = user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.在TGroup.hbm.xml中增加one-to-one配置
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.blogjava.start.TGroup" table="T_Group" catalog="sample">
<id name="id" type="integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="string" column="name" />
<one-to-one
name="user"
class="cn.blogjava.start.TUser"
property-ref="group"
/>
</class>
</hibernate-mapping>
这样就实现了双向关联。可以实现双向查询
package cn.blogjava.start;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateTest extends TestCase {
Session session = null;
protected void setUp() {
try {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();
} catch (HibernateException e) {
e.printStackTrace();
}
}
protected void tearDown() {
try {
session.close();
} catch (HibernateException e) {
e.printStackTrace();
}
}
/**
* 对象持久化测试(Insert方法)
*/
public void testInsert() {
Transaction tran = null;
try {
TUser user = new TUser();
user.setName("byf");
user.setAge(new Integer(26));
TGroup group = new TGroup();
group.setName("Admin");
tran = session.beginTransaction();
//设置关联
user.setGroup(group);
session.save(user);
session.flush();
tran.commit();
Assert.assertEquals(user.getId().intValue()>0 ,true);
} catch (HibernateException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
if(tran != null) {
try {
tran.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
/**
* 对象读取测试(Select方法)
*/
public void testSelect(){
String hql = " from TUser where name='byf'";
String hql2 = " from TGroup where name='admin'";
try {
List userList = session.createQuery(hql).list();
TUser user = (TUser)userList.get(0);
System.out.println("user name is " + user.getName());
System.out.println("user group is " + user.getGroup().getName());
Assert.assertEquals(user.getName(), "byf");
List groupList = session.createQuery(hql2).list();
TGroup group = (TGroup)groupList.get(0);
System.out.println("group name is " + group.getName());
System.out.println("group user is " + group.getUser().getName());
Assert.assertEquals(group.getUser().getName(), "byf");
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
}
posted on 2006-07-05 15:11
knowhow 阅读(434)
评论(0) 编辑 收藏 所属分类:
ORM:Hibernate及其他