Hibernate单向1-1映射范例
其实 Many-to-one 和 one-to-one 非常相似,只需要在 <many-to-one> 的尖括号中添加 unique="true"即可
1.hibernate.cfg.xml
代码如下 |
复制代码 |
<!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>
<!-- 配置数据库方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 配置数据库的驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 配置数据库用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 配置数据库的密码 -->
<property name="hibernate.connection.password">root</property>
<!-- 配置数据库的url -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<!-- 配置数据池的最大容量 -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- 配置数据池的最小容量 -->
<property name="hibernate.c3p0.min_size">1</property>
<!-- 配置数据链接的超时界限 -->
<property name="hibernate.c3p0.timeout">5000</property>
<!-- 在控制台显示后台是否打印执行的sql -->
<property name="hibernate.show_sql">true</property>
<!-- 是否以友好的格式显示打印的sql -->
<property name="hibernate.format_sql">true</property>
<!-- 打印一些辅助性的注释 -->
<property name="hibernate.use_sql_comments">true</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
<!-- 配置数据操作的方式,当为create的时候,每当我们运行这个MemberHandler的时候总是会删除以前的表,然后重新建表,这意味着以前的数据会被丢弃,所以实际应用中要用update -->
<property name="hbm2ddl.auto">update</property>
<!-- 将我们上面 Member 的映射文件添加进来 -->
<mapping resource="org/Rudiment/hibernate/Member.hbm.xml" />
<mapping resource="org/Rudiment/hibernate/Address.hbm.xml" />
</session-factory>
</hibernate-configuration>
|
2.(一)持久化类 Member.java
代码如下 |
复制代码 |
package org.Rudiment.hibernate;
import java.io.Serializable;
public class Member{
private Integer id;
private Integer age;
private String name;
private Address address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
|
3.Member类的映射规则文件 Member.cfg.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">
<!-- Generated 2013-9-9 19:50:34 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="org.Rudiment.hibernate">
<class name="Member" table="TEST_MEMBER">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<property name="age" column="AGE"></property>
<property name="name" column="NAME"></property>
<!-- 注意这里的cascade需要配置为all,如果放空为默认的化会导致 hibernate报如下的错误信息:object references an unsaved transient instance - save the transient instance before flushing: org.Rudiment.hibernate.Address -->
<many-to-one name="address" unique="true" class="Address" cascade="all" lazy="proxy"></many-to-one>
<!-- 注意上面的lazy要为false如果为默认值为非false,则当我们调用MemberHandler中query方法的时候,查出来的Member是没有Address的信息的 -->
</class>
</hibernate-mapping>
|
4.(一)持久化类 Address.java
代码如下 |
复制代码 |
package org.Rudiment.hibernate;
public class Address
{
private Integer address_id;
private String address_detail;
public Address()
{}
public Address(String detail)
{
this.address_detail = detail;
}
public Integer getAddress_id() {
return address_id;
}
public void setAddress_id(Integer address_id) {
this.address_id = address_id;
}
public String getAddress_detail() {
return address_detail;
}
public void setAddress_detail(String address_detail) {
this.address_detail = address_detail;
}
}
|
5.Address.java 的地址映射文件
代码如下 |
复制代码 |
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2013-9-10 14:49:04 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="org.Rudiment.hibernate.Address" table="ADDRESS">
<id name="address_id" type="java.lang.Integer">
<column name="ADDRESS_ID" />
<generator class="native" />
</id>
<property name="address_detail" type="java.lang.String">
<column name="ADDRESS_DETAIL" />
</property>
</class>
</hibernate-mapping>
|
6.对持久化类操纵的类: MemberHandler.java
代码如下 |
复制代码 |
package org.Rudiment.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class MemberHandler
{
public static void insert(int i) {
Configuration conf = new Configuration();
conf.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
session.beginTransaction();
Member m = new Member();
m.setAge(24 + i);
m.setName("IT客栈");
Address ad = new Address("广州" + i + "路");
m.setAddress(ad);
session.save(m);
session.getTransaction().commit();
session.close();
}
public static Member query(int id)
{
Configuration conf = new Configuration();
conf.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
Member m = (Member)session.get(Member.class, 1);
session.close();
return m;
}
public static Member addMemberInSameAddress(Member m, int id)
{
Configuration conf = new Configuration();
conf.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
m.setAddress(query(id).getAddress());
session.save(m);
tx.commit();
session.close();
return m;
}
public static void main(String[] args) {
for(int i=0; i<2; i++)
{
insert(i);
}
}
}
|
注:
当运行MemberHandler的时候将发现,后台数据库多了一个 test_member 和 address 的数据表,表的内容如下:
代码如下 |
复制代码 |
mysql> show tables;
+---------------------+
| Tables_in_hibernate |
+---------------------+
| address |
| test_member |
+---------------------+
2 rows in set (0.00 sec)
mysql> select * from test_member;
+----+------+--------+---------+
| ID | AGE | NAME | address |
+----+------+--------+---------+
| 1 | 24 | IT客栈 | 1 |
| 2 | 25 | IT客栈 | 2 |
+----+------+--------+---------+
2 rows in set (0.00 sec)
mysql> select * from address;
+------------+----------------+
| ADDRESS_ID | ADDRESS_DETAIL |
+------------+----------------+
| 1 | 广州0路 |
| 2 | 广州1路 |
+------------+----------------+
2 rows in set (0.00 sec)
mysql> desc test_member;
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| AGE | int(11) | YES | | NULL | |
| NAME | varchar(255) | YES | | NULL | |
| address | int(11) | YES | UNI | NULL | |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.02 sec)
mysql> desc address;
+----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+----------------+
| ADDRESS_ID | int(11) | NO | PRI | NULL | auto_increment |
| ADDRESS_DETAIL | varchar(255) | YES | | NULL | |
+----------------+--------------+------+-----+---------+----------------+
2 rows in set (0.03 sec)
|
当我们在hibernate中的1对1的模式下如果出现插入重复数据的时候,hibernate将出现下面的报错信息:
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
单向1-1含中间连接表映射范例
其实 Many-to-one 和 one-to-one 非常相似,只需要在 <many-to-one> 的尖括号中添加 unique="true"即可
1.hibernate.cfg.xml
代码如下 |
复制代码 |
<!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>
<!-- 配置数据库方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 配置数据库的驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 配置数据库用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 配置数据库的密码 -->
<property name="hibernate.connection.password">root</property>
<!-- 配置数据库的url -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<!-- 配置数据池的最大容量 -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- 配置数据池的最小容量 -->
<property name="hibernate.c3p0.min_size">1</property>
<!-- 配置数据链接的超时界限 -->
<property name="hibernate.c3p0.timeout">5000</property>
<!-- 在控制台显示后台是否打印执行的sql -->
<property name="hibernate.show_sql">true</property>
<!-- 是否以友好的格式显示打印的sql -->
<property name="hibernate.format_sql">true</property>
<!-- 打印一些辅助性的注释 -->
<property name="hibernate.use_sql_comments">true</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
<!-- 配置数据操作的方式,当为create的时候,每当我们运行这个MemberHandler的时候总是会删除以前的表,然后重新建表,这意味着以前的数据会被丢弃,所以实际应用中要用update -->
<property name="hbm2ddl.auto">update</property>
<!-- 将我们上面 Member 的映射文件添加进来 -->
<mapping resource="org/Rudiment/hibernate/Member.hbm.xml" />
<mapping resource="org/Rudiment/hibernate/Address.hbm.xml" />
</session-factory>
</hibernate-configuration>
|
2.(一)持久化类 Member.java
代码如下 |
复制代码 |
package org.Rudiment.hibernate;
import java.io.Serializable;
public class Member{
private Integer id;
private Integer age;
private String name;
private Address address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
|
3.Member类的映射规则文件 Member.cfg.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">
<!-- Generated 2013-9-9 19:50:34 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="org.Rudiment.hibernate">
<class name="Member" table="TEST_MEMBER">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<property name="age" column="AGE"></property>
<property name="name" column="NAME"></property>
<join table="member_address">
<key column="person_id" />
<!-- 注意这里的cascade需要配置为all,如果放空为默认的化会导致 hibernate报如下的错误信息:object references an unsaved transient instance - save the transient instance before flushing:org.Rudiment.hibernate.Address -->
<many-to-one name="address" unique="true" class="Address" cascade="all" lazy="proxy"></many-to-one>
<!-- 注意上面的lazy要为false如果为默认值为非false,则当我们调用MemberHandler中query方法的时候,查出来的Member是没有Address的信息的 -->
</join>
</class>
</hibernate-mapping>
|
4.(一)持久化类 Address.java
代码如下 |
复制代码 |
package org.Rudiment.hibernate;
public class Address
{
private Integer address_id;
private String address_detail;
public Address()
{}
public Address(String detail)
{
this.address_detail = detail;
}
public Integer getAddress_id() {
return address_id;
}
public void setAddress_id(Integer address_id) {
this.address_id = address_id;
}
public String getAddress_detail() {
return address_detail;
}
public void setAddress_detail(String address_detail) {
this.address_detail = address_detail;
}
}
|
5.Address.java 的地址映射文件 Address.cfg.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">
<!-- Generated 2013-9-10 14:49:04 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="org.Rudiment.hibernate.Address" table="ADDRESS">
<id name="address_id" type="java.lang.Integer">
<column name="ADDRESS_ID" />
<generator class="native" />
</id>
<property name="address_detail" type="java.lang.String">
<column name="ADDRESS_DETAIL" />
</property>
</class>
</hibernate-mapping>
|
6.对持久化类操纵的类: MemberHandler.java
代码如下 |
复制代码 |
package org.Rudiment.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class MemberHandler
{
public static void insert(int i) {
Configuration conf = new Configuration();
conf.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
session.beginTransaction();
Member m = new Member();
m.setAge(24 + i);
m.setName("IT客栈");
Address ad = new Address("广州" + i + "路");
m.setAddress(ad);
session.save(m);
session.getTransaction().commit();
session.close();
}
public static Member query(int id)
{
Configuration conf = new Configuration();
conf.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
Member m = (Member)session.get(Member.class, 1);
session.close();
return m;
}
public static Member addMemberInSameAddress(Member m, int id)
{
Configuration conf = new Configuration();
conf.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
m.setAddress(query(id).getAddress());
session.save(m);
tx.commit();
session.close();
return m;
}
public static void main(String[] args) {
for(int i=0; i<2; i++)
{
insert(i);
}
}
}
|
注:
当运行MemberHandler的时候将发现,后台数据库多了一个 test_member、member_address 和 address 的数据表,表的内容如下:
代码如下 |
复制代码 |
mysql> show tables;
+---------------------+
| Tables_in_hibernate |
+---------------------+
| address |
| member_address |
| test_member |
+---------------------+
3 rows in set (0.00 sec)
mysql> select * from test_member;
+----+------+--------+
| ID | AGE | NAME |
+----+------+--------+
| 1 | 24 | IT客栈 |
| 2 | 25 | IT客栈 |
+----+------+--------+
2 rows in set (0.00 sec)
mysql> select * from member_address;
+-----------+---------+
| person_id | address |
+-----------+---------+
| 1 | 1 |
| 2 | 2 |
+-----------+---------+
2 rows in set (0.00 sec)
mysql> select * from address;
+------------+----------------+
| ADDRESS_ID | ADDRESS_DETAIL |
+------------+----------------+
| 1 | 广州0路 |
| 2 | 广州1路 |
+------------+----------------+
2 rows in set (0.00 sec)
mysql> desc test_member;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| AGE | int(11) | YES | | NULL | |
| NAME | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.02 sec)
mysql> desc member_address;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| person_id | int(11) | NO | PRI | NULL | |
| address | int(11) | YES | UNI | NULL | |
+-----------+---------+------+-----+---------+-------+
2 rows in set (0.02 sec)
mysql> desc address;
+----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+----------------+
| ADDRESS_ID | int(11) | NO | PRI | NULL | auto_increment |
| ADDRESS_DETAIL | varchar(255) | YES | | NULL | |
+----------------+--------------+------+-----+---------+----------------+
2 rows in set (0.05 sec)
|
当我们在hibernate中的1对1的模式下如果出现插入重复数据的时候,hibernate将出现下面的报错信息:
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
时间: 2024-10-23 13:32:53