zoukankan      html  css  js  c++  java
  • Hibernate关联关系映射之一对一(主键关联)

    在业务成的域模型中,类和类之间最普遍的关系就是关联关系,而关联也是有方向的。

    就以例子来说明:一个人对应一张身份证。对其进行增删改。

    对于人在数据创建表的时候,我们就给他两个字段,一个是id号,一个就是名字。

    那么对于身份证也就是两个字段,一个对应于一个人相同的id号,一个就是身份证码。

    1 那么来创建数据库表:

     人为主表,身份证为从表。

    1 create table person(
    2 id bigint primary key auto_increment,
    3 userName varchar(20)
    4 );
    5  
    6 create table card(
    7 id bigint primary key,
    8 cardNo varchar(18)
    9 );

    创建实体类的时候,人要引用身份证卡的信息,同样身份证卡也要引用人这个类。

    2 那么来创建实体类:

    人:

     1 package com.cy.beans;
     2 
     3 import java.io.Serializable;
     4 
     5 public class Person implements Serializable {
     6 
     7     private static final long serialVersionUID = 1L;
     8     private long id;
     9     private String userName;
    10     private Card card;// 卡 一对一关联
    11 
    12     public void person() {
    13 
    14     }
    15 
    16     public long getId() {
    17         return id;
    18     }
    19 
    20     public void setId(long id) {
    21         this.id = id;
    22     }
    23 
    24     public String getUserName() {
    25         return userName;
    26     }
    27 
    28     public void setUserName(String userName) {
    29         this.userName = userName;
    30     }
    31 
    32     public Card getCard() {
    33         return card;
    34     }
    35 
    36     public void setCard(Card card) {
    37         this.card = card;
    38     }
    39 
    40     @Override
    41     public String toString() {
    42         return "Person [id=" + id + ", userName=" + userName + ", card=" + card
    43                 + "]";
    44     }
    45 
    46 }

    身份证:

     1 package com.cy.beans;
     2 
     3 import java.io.Serializable;
     4 
     5 public class Card implements Serializable{
     6 
     7     
     8     private static final long serialVersionUID = 1L;
     9     
    10     private long id;
    11     private String cardNo;
    12     private Person person;//人  一对一关联
    13     
    14     public Card(){
    15         
    16     }
    17     public long getId() {
    18         return id;
    19     }
    20     public void setId(long id) {
    21         this.id = id;
    22     }
    23     public String getCardNo() {
    24         return cardNo;
    25     }
    26     public void setCardNo(String cardNo) {
    27         this.cardNo = cardNo;
    28     }
    29     public Person getPerson() {
    30         return person;
    31     }
    32     public void setPerson(Person person) {
    33         this.person = person;
    34     }
    35     @Override
    36     public String toString() {
    37         return "Card [id=" + id + ", cardNo=" + cardNo + ", person=" + person
    38                 + "]";
    39     }
    40     
    41 
    42 }

     现在创建映射文件

    Person.hbm.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC 
     3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5     
     6     <hibernate-mapping>
     7     
     8     <class name="com.cy.beans.Person" table="person" catalog="j2ee">   <!-- catalog数据库 -->
     9     
    10               <id name="id" type="java.lang.Long"><!-- 此行的ID,为对象的属性ID -->
    11                   <column name="id"></column><!-- 此行的ID,为表字段ID -->
    12                   <generator class="increment"></generator><!-- 给id指定生成策略 -->
    13               </id>
    14     
    15               <property name="userName" type="java.lang.String">
    16                  <column name="userName"></column>
    17               </property>
    18               
    19          <!--站在主对象的一方来设置级联关系 -->
    20          <!-- cascade定义的是关系两端对象到对象的级联关系,cascade有四個取值,all,none,save-update,delete
    21                 all : 所有情况下均进行关联操作。 
    22                 none:所有情况下均不进行关联操作。这是默认值。 
    23                 save-update:在执行save/update/saveOrUpdate时进行关联操作。 
    24                 delete:在执行delete时进行关联操作。 -->
    25         <one-to-one name="card" class="com.cy.beans.Card" cascade="all"></one-to-one>
    26   
    27     
    28     </class>
    29      
    30     </hibernate-mapping>

    Card.hbm.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC 
     3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
     5     
     6     <hibernate-mapping>
     7     <class name="com.cy.beans.Card" table="card" catalog="j2ee">   <!-- catalog数据库 -->
     8               <id name="id" type="java.lang.Long"><!-- 此行的ID,为对象的属性ID -->
     9                  <column name="id"></column><!-- 此行的ID,为表字段ID -->
    10                    <generator class="foreign"><!-- foreign主键生成器 -->
    11                        <param name="property">person</param><!--类属性  -->
    12                    </generator>
    13               </id>
    14     
    15               <property name="cardNo" type="java.lang.String">
    16                  <column name="cardNo"></column>
    17               </property>
    18          <!--站在从对象的一方来设置交出约束  -->
    19          <!-- name:一对一节点  ,constrained: 约束(必须为true) -->
    20          <one-to-one name="person"  class="com.cy.beans.Person" constrained="true"></one-to-one>
    21   
    22     </class>
    23     </hibernate-mapping>

     在hibernate.cfg.xml里添加对象xml文件:

    1         <mapping resource="com/cy/xmls/Person.hbm.xml"/> 
    2         <mapping resource="com/cy/xmls/Card.hbm.xml"/> 

     工具类:

     1 package com.cy.tools;
     2 
     3 import org.hibernate.SessionFactory;
     4 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
     5 import org.hibernate.cfg.Configuration;
     6 import org.hibernate.service.ServiceRegistry;
     7 
     8 /**
     9  * session工厂的工具类
    10  * @author acer
    11  *
    12  */
    13 
    14 public class HibernateUtils {
    15     
    16     private static Configuration cfg;
    17     private static SessionFactory sessionFactory;
    18     private static ServiceRegistry serviceRegistry;
    19     
    20     static{
    21         
    22         cfg = new Configuration().configure();
    23         serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
    24         sessionFactory = cfg.buildSessionFactory(serviceRegistry);
    25     
    26     }
    27     
    28     public static SessionFactory getSessionFactory(){
    29         return sessionFactory;
    30     }
    31          
    32     
    33 
    34 }

    IPersonDao.java接口,定义方法:

     1 package com.cy.dao;
     2 
     3 import java.io.Serializable;
     4 
     5 import com.cy.beans.Person;
     6 
     7 public interface IPersonDao {
     8     /**
     9      * 添加
    10      * @param p
    11      */
    12     public void savePerson(Person p);
    13     /**
    14      * 修改
    15      * @param p
    16      */
    17     public void updatePerson(Person p);
    18     /**
    19      * 刪除
    20      * @param p
    21      */
    22     public void deletePerson(Person p);
    23     /**
    24      * 根据id查询数据
    25      * @param cls
    26      * @param pk
    27      * @return
    28      */
    29     public Person getPerson(Class<?> cls,Serializable pk);
    30     
    31     public void findPerson(Person p);
    32 
    33 }
    View Code

    写接口实现:PersonDaoImpl.java

     1 package com.cy.dao.impl;
     2 
     3 import java.io.Serializable;
     4 
     5 import org.hibernate.Session;
     6 import org.hibernate.Transaction;
     7 
     8 import com.cy.beans.Person;
     9 import com.cy.dao.IPersonDao;
    10 import com.cy.tools.HibernateUtils;
    11 
    12 public class PersonDaoImpl implements IPersonDao {
    13 
    14     @Override
    15     public void savePerson(Person p) {
    16         //获得Session
    17         Session session=null;
    18         Transaction transaction=null;
    19         
    20         try {
    21             session=HibernateUtils.getSessionFactory().openSession();//
    22             transaction=session.beginTransaction();//开启事务
    23             session.save(p);//添加
    24             transaction.commit();//提交事务
    25         } catch (Exception e) {
    26             e.printStackTrace();
    27             transaction.rollback();//回滚事务
    28         }finally{
    29             session.close();//关闭session
    30         }
    31 
    32     }
    33 
    34     @Override
    35     public void updatePerson(Person p) {
    36         Session session=null;
    37         Transaction transaction=null;
    38         
    39         try {
    40             session=HibernateUtils.getSessionFactory().openSession();
    41             transaction=session.beginTransaction();
    42             session.update(p);//修改
    43             transaction.commit();
    44         } catch (Exception e) {
    45             e.printStackTrace();
    46             transaction.rollback();
    47         }finally{
    48             session.close();
    49         }
    50 
    51     }
    52 
    53     @Override
    54     public Person getPerson(Class<?> cls, Serializable pk) {
    55         Session session=null;
    56         Transaction transaction=null;
    57         Person    person=null;
    58         try {
    59             session=HibernateUtils.getSessionFactory().openSession();
    60             transaction=session.beginTransaction();
    61             person=(Person) session.get(cls, pk);//根据id查询。pk这里指的就是id
    62             transaction.commit();
    63             
    64         } catch (Exception e) {
    65             e.printStackTrace();
    66             transaction.rollback();
    67         }finally{
    68             session.close();
    69         }
    70 
    71         return person;
    72     }
    73     @Override
    74     public void deletePerson(Person p) {
    75         Session session=null;
    76         Transaction transaction=null;
    77         
    78         try {
    79             session=HibernateUtils.getSessionFactory().openSession();
    80             transaction=session.beginTransaction();
    81             session.delete(p);//删除
    82             transaction.commit();
    83         } catch (Exception e) {
    84             e.printStackTrace();
    85             transaction.rollback();
    86         }finally{
    87             session.close();
    88         }
    89 
    90     }
    91 
    92 
    93     @Override
    94     public void findPerson(Person p) {
    95 
    96     }
    97 
    98 }
    View Code

     写IPersonServer.java接口

     1 package com.cy.server;
     2 
     3 import java.io.Serializable;
     4 
     5 import com.cy.beans.Person;
     6 
     7 public interface IPersonServer {
     8     /**
     9      * 添加
    10      * @param p
    11      */
    12     public void savePerson(Person p);
    13     /**
    14      * 修改
    15      * @param p
    16      */
    17     public void updatePerson(Person p);
    18     /**
    19      * 刪除
    20      * @param p
    21      */
    22     public void deletePerson(Long id);
    23     /**
    24      * 根据id查询
    25      * @param cls
    26      * @param pk
    27      * @return
    28      */
    29     public Person getPerson(Class<?> cls,Serializable pk);
    30     
    31     public void findPerson(Person p);
    32 }
    View Code

    写PersonServerImpl.java实现;

     1 package com.cy.server.impl;
     2 
     3 import java.io.Serializable;
     4 
     5 import com.cy.beans.Person;
     6 import com.cy.dao.IPersonDao;
     7 import com.cy.dao.impl.PersonDaoImpl;
     8 import com.cy.server.IPersonServer;
     9 
    10 public class PersonServerImpl implements IPersonServer {
    11     IPersonDao dao = new PersonDaoImpl();
    12 
    13     @Override
    14     public void savePerson(Person p) {
    15         dao.savePerson(p);
    16 
    17     }
    18 
    19     @Override
    20     public void updatePerson(Person p) {
    21         dao.updatePerson(p);
    22     }
    23 
    24     @Override
    25     public void deletePerson(Long id) {
    26         Person p = dao.getPerson(Person.class, id);
    27         if (p != null) {
    28             dao.deletePerson(p);
    29         }
    30 
    31     }
    32 
    33     @Override
    34     public Person getPerson(Class<?> cls, Serializable pk) {
    35 
    36         return dao.getPerson(cls, pk);
    37     }
    38 
    39     @Override
    40     public void findPerson(Person p) {
    41 
    42     }
    43 
    44 }
    View Code

     写个PersonAction测试;

     1 package com.cy.action;
     2 
     3 import com.cy.beans.Card;
     4 import com.cy.beans.Person;
     5 import com.cy.server.IPersonServer;
     6 import com.cy.server.impl.PersonServerImpl;
     7 
     8 public class PersonAction {
     9     public static void main(String[] args) {
    10         
    11 //        savePerson();    
    12 //        updatePerson();
    13           deletePerson();
    14     }
    15 
    16     private static void deletePerson() {
    17         IPersonServer ps=new PersonServerImpl();
    18         ps.deletePerson(Long.valueOf(1));
    19         
    20         
    21     }
    22 
    23     private static void updatePerson() {
    24         IPersonServer ps=new PersonServerImpl();
    25         Person p=ps.getPerson(Person.class, Long.valueOf(1));
    26         p.setUserName("小紅");
    27         ps.updatePerson(p);
    28         /*Hibernate: //这些hibernate所执行语句    修查询  后修改
    29             select
    30                 person0_.id as id1_1_0_,
    31                 person0_.userName as userName2_1_0_,
    32                 card1_.id as id1_0_1_,
    33                 card1_.cardNo as cardNo2_0_1_ 
    34             from
    35                 j2ee.person person0_ 
    36             left outer join
    37                 j2ee.card card1_ 
    38                     on person0_.id=card1_.id 
    39             where
    40                 person0_.id=?
    41         Hibernate: 
    42             update
    43                 j2ee.person 
    44             set
    45                 userName=? 
    46             where
    47                 id=?
    48         Hibernate: 
    49             update
    50                 j2ee.card 
    51             set
    52                 cardNo=? 
    53             where
    54                 id=?
    55 */
    56         
    57         
    58     }
    59 
    60     private static void savePerson() {
    61         IPersonServer ps=new PersonServerImpl();
    62         Person p=new Person();
    63         p.setUserName("小明");        
    64         Card c=new Card();
    65         c.setCardNo("511123************");
    66         //設置相互
    67         p.setCard(c);
    68         c.setPerson(p);
    69         ps.savePerson(p);
    70         /*Hibernate:   添加时 先查询主表的最大的id,先添加主表,在添加从表。   删除时则是先删除从表,在删除主表。
    71             select
    72                 max(id) 
    73             from
    74                 person
    75         Hibernate: 
    76             insert 
    77             into
    78                 j2ee.person
    79                 (userName, id) 
    80             values
    81                 (?, ?)
    82         Hibernate: 
    83             insert 
    84             into
    85                 j2ee.card
    86                 (cardNo, id) 
    87             values
    88                 (?, ?)
    89 
    90         
    91     */
    92         
    93     }
    94 }
  • 相关阅读:
    优化tableView加载cell与model的过程
    java.net.UnknownHostException: master
    Give root password for maintenance(or type control -D to continue)
    软件自动化部署脚本
    关于yum网络版仓库(本地yum仓库的安装配置,如果没网了,做一个局域网内的yum仓库)
    一脸懵逼学习keepalived(对Nginx进行热备)
    一脸懵逼学习Nginx及其安装,Tomcat的安装
    一脸懵逼学习Linux的Shell编程
    一脸懵逼学习KafKa集群的安装搭建--(一种高吞吐量的分布式发布订阅消息系统)
    一脸懵逼学习Storm的搭建--(一个开源的分布式实时计算系统)
  • 原文地址:https://www.cnblogs.com/hellokitty1/p/5050172.html
Copyright © 2011-2022 走看看