Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 320|回复: 0

[Java框架学习]hibernate入门系列 2-- xml关系映射篇(上)

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-11-4 00:00:17 | 显示全部楼层 |阅读模式
    现在起主要讲 hibernate中的关系映射。对应的关系主要有 1:1, n:1, n:n。今天主要写1:1。 关系映射篇(上)―― 之1:1    1对1的关系在现实中很常见。比方说:人和身份证。1个身份证对应着一个身份证,一个身份证对应着一个人。那么,我们就以此为原型。进行代码编写。 建立实体模型如图:

      
      
       
       
         
       

         
       
      


    根据模型,创建数据库
    use HibernateQuickUse;
    drop table if exists Person;
    drop table if exists Card;
    create table Card (
            id varchar(32) primary key,
            cardDesc varchar(128) not null
    );
    create table Person (
            id varchar(32) primary key,
            name varchar(32) not null,
            card_id varchar(32) not null,
            foreign key(card_id) references Card(id)
    );
              [/code]
    java代码如下:
    Person类
    package org.py.hib.relation.one2one;
    /**
    * Person entity.
    */
    @SuppressWarnings("serial")
    public class Person implements java.io.Serializable
    {
            private String id;
            private String name;
            private Card card;
            public Person()
            {
            }
            public String getId()
            {
                    return this.id;
            }
            public void setId(String id)
            {
                    this.id = id;
            }
            public Card getCard()
            {
                    return this.card;
            }
            public void setCard(Card card)
            {
                    this.card = card;
            }
            public String getName()
            {
                    return this.name;
            }
            public void setName(String name)
            {
                    this.name = name;
            }
    }[/code]
    Card类:
    package org.py.hib.relation.one2one;
    /**
    * Card entity.
    */
    @SuppressWarnings("serial")
    public class Card implements java.io.Serializable
    {
            private String id;
            private String cardDesc;
            public Card()
            {
            }
            public String getId()
            {
                    return this.id;
            }
            public void setId(String id)
            {
                    this.id = id;
            }
            public String getCardDesc()
            {
                    return cardDesc;
            }
            public void setCardDesc(String cardDesc)
            {
                    this.cardDesc = cardDesc;
            }
    }[/code]
    xml映射文件如下:
    Person.hbm.xml
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
            <class name="org.py.hib.relation.one2one.Person" table="person">
                    <id name="id" type="java.lang.String" column="id" length="32">
                            <generator class="uuid" />
                    </id>
                    <property name="name" type="java.lang.String">
                            <column name="name" length="32" />
                    </property>
                    <many-to-one name="card" class="org.py.hib.relation.one2one.Card" unique="true"
                            cascade="all" column="card_id" />
                           
            </class>
    </hibernate-mapping>
                      [/code]
    今天讲的是one-to-one配置。但是,此处用的是many-to-one,这个是什么原因呢?其实,one-to-one就是特殊的many-to-one。  
    Card.hbm.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!--
        Mapping file autogenerated by MyEclipse Persistence Tools
    -->
    <hibernate-mapping>
        <class name="org.py.hib.relation.one2one.Card" table="card">
            <id name="id" type="java.lang.String" column="id" length="32">
                <generator class="uuid" />
            </id>
            
            <property name="cardDesc" type="java.lang.String" column="cardDesc" length="128" not-null="true"/>
        </class>
    </hibernate-mapping>[/code]
    测试代码如下:
    One2OneTest.java
    package org.py.hib.relation.one2one;
    import junit.framework.Assert;
    import junit.framework.TestCase;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.junit.After;
    import org.junit.Before;
    public class One2OneTest extends TestCase
    {
            private SessionFactory factory;
            private String m_name = "ryanpoy";
            private String m_name2 = "ryanpoy2";
            private String m_cardDesc1 = "desc_1";
            private String m_cardDesc2 = "desc_2";
            @Before
            public void setUp() throws Exception
            {
                    Configuration conf = new Configuration().configure();
                    factory = conf.buildSessionFactory();
            }
            /**
             * 测试添加
             * @throws Exception
             */
            public void testSave() throws Exception
            {
                    System.out.println("
    === test save ===");
                    Card card = new Card();
                    card.setCardDesc(m_cardDesc1);
                    Person person = new Person();
                    person.setName(m_name); // 设置用户名 = m_name
                    person.setCard(card);
                    Session session = null;
                    Transaction tran = null;
                    try
                    {
                            session = factory.openSession();
                            tran = session.beginTransaction();
                            session.save(person);
                           
                            tran.commit();
                            Assert.assertEquals(person.getId() != null, true);
                            Assert.assertEquals(card.getId() != null, true);
                    } catch (Exception ex)
                    {
                            tran.rollback();
                            throw ex;
                    } finally
                    {
                            if (session != null)
                            {
                                    try
                                    {
                                            session.close();
                                    } catch (Exception ex)
                                    {
                                            // nothing to do
                                    } finally
                                    {
                                            if (session != null)
                                                    session = null;
                                    }
                            }
                    }
            }
            /**
             * 测试查询
             * @throws Exception
             */
            public void testFind() throws Exception
            {
                    System.out.println("
    === test find ===");
                    Session session = null;
                    try
                    {
                            session = factory.openSession();
                            Person person = (Person) session.createQuery("from Person").list().get(0);
                            Assert.assertEquals(true, person.getId() != null);
                            Assert.assertEquals(m_name, person.getName());
                            Assert.assertEquals(true, person.getCard().getId() != null);
                            Assert.assertEquals(m_cardDesc1, person.getCard().getCardDesc());
                    } catch (Exception ex)
                    {
                            throw ex;
                    } finally
                    {
                            if (session != null)
                            {
                                    try
                                    {
                                            session.close();
                                    } catch (Exception ex)
                                    {
                                            // nothing to do
                                    } finally
                                    {
                                            if (session != null)
                                                    session = null;
                                    }
                            }
                    }
            }
            /**
             * 测试修改
             * @throws Exception
             */
            public void testModify() throws Exception
            {
                    System.out.println("
    === test modify ===");
                    Session session = null;
                    Transaction tran = null;
                    try
                    {
                            session = factory.openSession();
                            tran = session.beginTransaction();
                    Person person = (Person) session.createQuery("from Person").list().get(0);
                    person.setName(m_name2); // 修改用户名 = m_name2.(原来用户名= m_name)
                    person.getCard().setCardDesc(m_cardDesc2); //修改cardDesc为m_cardDesc2(原来是:m_cardDesc1)
                            tran.commit();
                    } catch (Exception ex)
                    {
                            throw ex;
                    } finally
                    {
                            if (session != null)
                            {
                                    try
                                    {
                                            session.close();
                                    } catch (Exception ex)
                                    {
                                            // nothing to do
                                    } finally
                                    {
                                            if (session != null)
                                                    session = null;
                                    }
                            }
                    }
                    /*
                     * 修改后再查询
                     */
                    System.out.println("
    === test find after modify ===");
                    try
                    {
                            session = factory.openSession();
                            Person person = (Person) session.createQuery("from Person").list().get(0);
                            Assert.assertEquals(true, person.getId() != null);
                            Assert.assertEquals(m_name2, person.getName());
                            Assert.assertEquals(true, person.getCard().getId() != null);
                            Assert.assertEquals(m_cardDesc2, person.getCard().getCardDesc());
                    } catch (Exception ex)
                    {
                            throw ex;
                    } finally
                    {
                            if (session != null)
                            {
                                    try
                                    {
                                            session.close();
                                    } catch (Exception ex)
                                    {
                                            // nothing to do
                                    } finally
                                    {
                                            if (session != null)
                                                    session = null;
                                    }
                            }
                    }
            }
            /**
             * 测试删除
             * @throws Exception
             */
            public void testDelete() throws Exception
            {
                    System.out.println("
    === test delete ===");
                    Session session = null;
                    Transaction tran = null;
                    try
                    {
                            session = factory.openSession();
                            tran = session.beginTransaction();
                            Person person = (Person) session.createQuery("from Person").list().get(0);
                            session.delete(person);
                            tran.commit();
                    } catch (Exception ex)
                    {
                            throw ex;
                    } finally
                    {
                            if (session != null)
                            {
                                    try
                                    {
                                            session.close();
                                    } catch (Exception ex)
                                    {
                                            // nothing to do
                                    } finally
                                    {
                                            if (session != null)
                                                    session = null;
                                    }
                            }
                    }
                    /*
                     * 删除后再查询
                     */
                    System.out.println("
    === test find after delete ===");
                    try
                    {
                            session = factory.openSession();
                            Integer num = (Integer) session.createQuery("from Person").list().size();
                            Assert.assertEquals(0, num.intValue());
                            num = (Integer) session.createQuery("from Card").list().size();
                            Assert.assertEquals(0, num.intValue());
                    } catch (Exception ex)
                    {
                            throw ex;
                    } finally
                    {
                            if (session != null)
                            {
                                    try
                                    {
                                            session.close();
                                    } catch (Exception ex)
                                    {
                                            // nothing to do
                                    } finally
                                    {
                                            if (session != null)
                                                    session = null;
                                    }
                            }
                    }
            }
            /**
             *
             */
            @After
            public void tearDown() throws Exception
            {
                    factory.close();
            }
    }
                    [/code]
    运行test,

    C:h>java org.junit.runner.JUnitCore org.py.hib.relation.one2one.One2OneTest

    一路飚绿。呵呵。陶醉一番。不过,这也就是一个拿不出手的测试和一个拿不出手的例子。没有任何实际意义的例子。仅此一个demo而已。
    在1:1中,其实还有一种方式,即:唯一主键关联。但是,我一直倾向于上面的这种形式,所以,唯一主键关联以后介绍了。
       


      
      
       
       

         
       

         
       
      
    复制代码

    源码下载:http://file.javaxxz.com/2014/11/4/000016750.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-25 14:13 , Processed in 0.383961 second(s), 48 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表