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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM