Hibernate单向1-1含连接表映射实例详解

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

Hibernate单向1-1含连接表映射实例详解的相关文章

Java中Hibernate单向(1-N)映射实例详解

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> <s

mysql alter table命令修改表结构实例详解_php实例

mysql alter table语句可以修改表的基本结构,例如添加字段.删除字段.添加主键.添加索引.修改字段数据类型.对表重命名等等操作,本文章通过两个简单的实例向大家介绍mysql alter table的使用方法.  实例一:使用ALTER TABLE命令向表中添加字段.修改字段类型以及设置主键. 首先创建一个表,SQL语句如下: mysql> CREATE TABLE myTable( -> ID SMALLINT -> ); 使用desc命令查看表结构: mysql>

C++Builder注册表编程实例详解

一.注册表编程详解 Windows 注册表中包含了系统配置.机器硬件配置. Win32 应用程序和用户的其他配置信息.许多高级一些的功能都要通过对注册表的操作来实现.在 WinAPI 中提供了 RegCgreateKey() . RegOpenKey() . RegQueryValue() 等函数操作注册表,但是用这些函数来操作注册表使用起来非常麻烦.而利用 C ++ Builder 的 TREGISTRY 类,我们则可以轻松实现对注册表的操作.下面我先介绍一下 TRegistry 类使用方法.

PHP中实现mysql连接与查询实例详解

下面讲一下PHP链接MYSQL数据库 PHP与mysql链接和查询全过程 1.配制: php.ini 加载mysql组件:                extension=php_mysql.dll  前的; 去掉                extension_dir = " "  路径是否正确 2.PHP语法   PHP链接mysql函数                   mysql_connect:  开启MySQL 链接                   mysql_s

Zend Framework教程之Zend_Db_Table表关联实例详解_php实例

本文实例讲述了Zend Framework中Zend_Db_Table表关联用法.分享给大家供大家参考,具体如下: 介绍: 在RDBMS中,表之间有着各种关系,有一多对应,多多对应等等. Zend框架提供了一些方法来方便我们实现这些关系. 定义关系: 下面是本文用的例子的关系定义: <?php class Accounts extends Zend_Db_Table_Abstract { protected $_name = 'accounts'; protected $_dependentTa

mysql alter table命令修改表结构实例详解

mysql alter table语句可以修改表的基本结构,例如添加字段.删除字段.添加主键.添加索引.修改字段数据类型.对表重命名等等操作,本文章通过两个简单的实例向大家介绍mysql alter table的使用方法. 实例一:使用ALTER TABLE命令向表中添加字段.修改字段类型以及设置主键. 首先创建一个表,SQL语句如下: mysql> CREATE TABLE myTable( -> ID SMALLINT -> ); 使用desc命令查看表结构: mysql> d

AngularJs表单验证实例详解_AngularJS

常用的表单验证指令 1. 必填项验证 某个表单输入是否已填写,只要在输入字段元素上添加HTML5标记required即可: 复制代码 代码如下: <input type="text" required /> 2. 最小长度 验证表单输入的文本长度是否大于某个最小值,在输入字段上使用指令ng-minleng= "{number}": 复制代码 代码如下: <input type="text" ng-minlength="

Hibernate配置文件中映射元素详解

详解 本文中将讲述Hibernate的基本配置及配置文件的应用,这对于正确熟练使用Hibernate是相当关键的. 配置文件中映射元素详解 对象关系的映射是用一个XML文档来说明的.映射文档可以使用工具来生成,如XDoclet,Middlegen和AndroMDA等.下面从一个映射的例子开始讲解映射元素,映射文件的代码如下. <?xml version="1.0"?><!--所有的XML映射文件都需要定义如下所示的DOCTYPE.Hibernate会先在它的类路径(c

hibernate批量操作实例详解_java

本文实例讲述了hibernate批量操作的方法.分享给大家供大家参考,具体如下: Hibernate的批量处理 Hibernate完全以面向对象的方式来操作数据库,当程序里以面向对象的方式操作持久化对象时,将被自动转换为对数据库的操作.例如调用Session的delete()方法来删除持久化对象,Hibernate将负责删除对应的数据记录:当执行持久化对象的set方法时,Hibernate将自动转换为对应的update方法,修改数据库的对应记录. 问题是如果需要同时更新100 000条记录,是不