继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

myeclipse试用小记----Hibernate多对一双向关联(2)

largeQ
关注TA
已关注
手记 953
粉丝 92
获赞 585


myeclipse试用小记----Hibernate多对一双向关联(2)

 

在上篇文章“myeclipse试用小记----Hibernate多对一单向关联(1)”中,讲到了“Hibernate多对一单向关联”,现在我打算把这个做成双向的,也就是多对一双向关联,看看myeclipse是如何实现的。

 

环境、数据库还和上篇文章的一样。只是表中的数据清空了。

 

注意:对于有外键的表,清空数据有两种方法:第一是先drop掉外键约束后,进行清除。第二种是先清除从表数据(orders),然后清除主表的数据(customers),具体我及不说了,有空我在写写数据库外键约束的方面的文章,这点也很重要的。

 

步骤

1、清除orders、customers两表数据。

2、用myeclipse新建web工程sx_d2y,加入hibernate支持。

3、同时选中orders、customers生成实体Bean和mapping文件,并对mapping做小的改动。

4、写两个测试类,分别保存Orders对象和Customers的实体对象,看看能否保存到数据库中。

 

 

废话不说了,看过程吧!

 

一、通过myeclipse生成实体和配置文件:

 

Customers.java

---------------------

public class Customers implements java.io.Serializable {

 

    // Fields

 

    private Long id;

 

    private String name;

 

    private Set orderses = new HashSet(0);

 

    // Constructors

 

    /** default constructor */

    public Customers() {

    }

 

    /** full constructor */

    public Customers(String name, Set orderses) {

        this.name = name;

        this.orderses = orderses;

    }

 

    // Property accessors

 

    public Long getId() {

        return this.id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getName() {

        return this.name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public Set getOrderses() {

        return this.orderses;

    }

 

    public void setOrderses(Set orderses) {

        this.orderses = orderses;

    }

 

}

 

Orders.java

---------------------

public class Orders implements java.io.Serializable {

 

    // Fields

 

    private Long id;

 

    private Customers customers;

 

    private String orderNumber;

 

    // Constructors

 

    /** default constructor */

    public Orders() {

    }

 

    /** minimal constructor */

    public Orders(Customers customers) {

        this.customers = customers;

    }

 

    /** full constructor */

    public Orders(Customers customers, String orderNumber) {

        this.customers = customers;

        this.orderNumber = orderNumber;

    }

 

    // Property accessors

 

    public Long getId() {

        return this.id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public Customers getCustomers() {

        return this.customers;

    }

 

    public void setCustomers(Customers customers) {

        this.customers = customers;

    }

 

    public String getOrderNumber() {

        return this.orderNumber;

    }

 

    public void setOrderNumber(String orderNumber) {

        this.orderNumber = orderNumber;

    }

 

}

 

Customers.hbm.xml

-------------------

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"[url]http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd[/url]">

<!--

    Mapping file autogenerated by MyEclipse Persistence Tools

-->

<hibernate-mapping>

    <class name="org.lavasoft.Customers" table="customers">

        <id name="id" type="java.lang.Long">

            <column name="ID" />

            <generator class="increment" />

        </id>

        <property name="name" type="java.lang.String">

            <column name="NAME" length="15" />

        </property>

        <set name="orderses" inverse="true" cascade="all-delete-orphan">

            <key>

                <column name="CUSTOMER_ID" not-null="true" />

            </key>

            <one-to-many class="org.lavasoft.Orders" />

        </set>

    </class>

</hibernate-mapping>

 

Orders.hbm.xml

-------------------

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"[url]http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd[/url]">

<!--

    Mapping file autogenerated by MyEclipse Persistence Tools

-->

<hibernate-mapping>

    <class name="org.lavasoft.Orders" table="orders" catalog="testdb">

        <id name="id" type="java.lang.Long">

            <column name="ID" />

            <generator class="increment" />

        </id>

        <many-to-one name="customers" class="org.lavasoft.Customers" fetch="select" cascade="save-update">

            <column name="CUSTOMER_ID" not-null="true" />

        </many-to-one>

        <property name="orderNumber" type="java.lang.String">

            <column name="ORDER_NUMBER" length="15" />

        </property>

    </class>

</hibernate-mapping>

 

二、写测试类进行测试

 

在测试之前,先清空这两个关联表的数据。

 

D:\mysql-5.0.37-win32\bin>mysql -uroot -pleizhimin

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 32

Server version: 5.0.37-community MySQL Community Edition (GPL)

 

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

 

mysql> use testdb;

Database changed

mysql> show tables;

+------------------+

| Tables_in_testdb |

+------------------+

| card             |

| customers        |

| orders           |

| person           |

| t_user           |

| user             |

+------------------+

6 rows in set (0.00 sec)

 

mysql> delete from orders;

Query OK, 2 rows affected (0.03 sec)

 

mysql> delete from customers;

Query OK, 1 row affected (0.03 sec)

 

看清了,我已经干掉这个两个表的所有数据了。

 

然后,我写一个测试类TestbyOrder,从保存Orders实体对象,看能否级联保存相关的Customers对象:

 

package org.lavasoft;

 

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.Transaction;

 

public class TestbyOrder {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        if(HibernateSessionFactory.getSession()==null)System.out.println("null");

        Session session=HibernateSessionFactory.getSession();

        Transaction tx=session.beginTransaction();

        Customers c=new Customers();

        c.setName("c1");

       

        Orders o1 =new Orders();

        o1.setOrderNumber("11");

        Orders o2 =new Orders();

        o2.setOrderNumber("22");

       

        c.getOrderses().add(o1);

        c.getOrderses().add(o2);

       

        o1.setCustomers(c);

        o2.setCustomers(c);

       

        try {

            session.save(o1);

            session.save(o2);

            //session.save(c);

            tx.commit();

        } catch (HibernateException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            tx.rollback();

        }finally{

            session.close();

        }      

    }

 

}

 

运行这个类,控制台信息如下:

Hibernate: select max(ID) from orders

Hibernate: select max(ID) from customers

Hibernate: insert into customers (NAME, ID) values (?, ?)

Hibernate: insert into testdb.orders (CUSTOMER_ID, ORDER_NUMBER, ID) values (?, ?, ?)

Hibernate: insert into testdb.orders (CUSTOMER_ID, ORDER_NUMBER, ID) values (?, ?, ?)

 

从控制台信息发现已经级联保存进去了。

 

在从开库看看,到底写的进去的数据是什么:

mysql> select * from orders;

+----+--------------+-------------+

| ID | ORDER_NUMBER | CUSTOMER_ID |

+----+--------------+-------------+

|  1 | 11           |           1 |

|  2 | 22           |           1 |

+----+--------------+-------------+

2 rows in set (0.00 sec)

 

mysql> select * from customers;

+----+------+

| ID | NAME |

+----+------+

|  1 | c1   |

+----+------+

1 row in set (0.00 sec)

 

mysql>

 

开库查结果表明,写入Orders对象的同时,写入了相关的Customers对象。

 

下面再进行一下反向测试:

 

先清空两个表

 

mysql> delete from orders;

Query OK, 2 rows affected (0.03 sec)

 

mysql>  delete from customers;

Query OK, 1 row affected (0.00 sec)

 

mysql>

 

然后写测试类:

 

package org.lavasoft;

 

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.Transaction;

 

public class TestbyCustomer {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        if(HibernateSessionFactory.getSession()==null)System.out.println("null");

        Session session=HibernateSessionFactory.getSession();

        Transaction tx=session.beginTransaction();

        Customers c=new Customers();

        c.setName("c1");

       

        Orders o1 =new Orders();

        o1.setOrderNumber("11");

        Orders o2 =new Orders();

        o2.setOrderNumber("22");

       

        c.getOrderses().add(o1);

        c.getOrderses().add(o2);

       

        o1.setCustomers(c);

        o2.setCustomers(c);

       

        try {

            session.save(c);

            tx.commit();

        } catch (HibernateException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            tx.rollback();

        }finally{

            session.close();

        }      

    }

}

 

运行这个测试类,控制台信息如下:

Hibernate: select max(ID) from customers

Hibernate: select max(ID) from orders

Hibernate: insert into customers (NAME, ID) values (?, ?)

Hibernate: insert into testdb.orders (CUSTOMER_ID, ORDER_NUMBER, ID) values (?, ?, ?)

Hibernate: insert into testdb.orders (CUSTOMER_ID, ORDER_NUMBER, ID) values (?, ?, ?)

 

开库查,看看写入数据是什么:

 

mysql> select * from orders;

+----+--------------+-------------+

| ID | ORDER_NUMBER | CUSTOMER_ID |

+----+--------------+-------------+

|  1 | 11           |           1 |

|  2 | 22           |           1 |

+----+--------------+-------------+

2 rows in set (0.00 sec)

 

mysql> select * from customers;

+----+------+

| ID | NAME |

+----+------+

|  1 | c1   |

+----+------+

1 row in set (0.00 sec)

 

mysql>

 

开库查结果表明,写入Customers对象的同时,写入了相关的Orders对象。

 

从而可以证明:这个双向关联是成功的。

 

呵呵,myeclipse不错,是个好东西。

 

myeclipse试用小记----Hibernate多对一单向关联(1)

附件:http://down.51cto.com/data/2348079

©著作权归作者所有:来自51CTO博客作者leizhimin的原创作品,如需转载,请与作者联系,否则将追究法律责任

职场Hibernate休闲ORM/持久化


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP