Hibernate一对一关联映射(注解)

hibernate一对一关联映射有两种方式,一种是基于外键方式(常用),一种是基于主键方式

一、首先我们来看基于外键一对一关联映射:

 

1.数据表关联映射图


基于外键的一对一关联映射,维护端(有外键方)可以维护双方关联,对双方进行删除操作,而被维护端(无外键方)则不可以

2.Customer实体类,维护端(有外键方)

[java]  view plain  copy
  1. @Entity  
  2. @Table(name = "T_FOREIGN_CUSTOMER")  
  3. public class Customer {  
  4.     private int id;  
  5.     private String name;  
  6.     private Referee referee;  
  7.   
  8.     @Id  
  9.     @GeneratedValue(strategy = GenerationType.TABLE, generator = "T_FOREIGN_CUSTOMER_GEN")  
  10.     @TableGenerator(name = "T_FOREIGN_CUSTOMER_GEN", table = "TB_GENERATOR", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VALUE", pkColumnValue = "T_FOREIGN_CUSTOMER_GEN", allocationSize = 1)  
  11.     public int getId() {  
  12.         return id;  
  13.     }  
  14.   
  15.     public void setId(int id) {  
  16.         this.id = id;  
  17.     }  
  18.   
  19.     public String getName() {  
  20.         return name;  
  21.     }  
  22.   
  23.     public void setName(String name) {  
  24.         this.name = name;  
  25.     }  
  26.   
  27.     /** 
  28.      * 默认外键名referee_id 
  29.      * @OneToOne public Referee getReferee() { return referee; } 
  30.      * @return 
  31.      */  
  32.   
  33.     /** 
  34.      * /使用新的外键名:referee1_id 
  35.      * @OneToOne 
  36.      * @JoinColumn(name="referee1_id") public Referee getReferee() { return 
  37.      * @return 
  38.      */  
  39.     @OneToOne  
  40.     @JoinColumn(name = "referee_id")  
  41.     // 维护端  
  42.     public Referee getReferee() {  
  43.         return referee;  
  44.     }  
  45.   
  46.     /** 
  47.      * 从上面的代码可以看出,getReferee方法使用了@OneToOne进设置 
  48.      * 在装载Customer对象的同时,Referee对象会被同时装载,而默认的外键字段就是Customer类中的referee属性名+"_"+id 
  49.      * 也就是referee_id 
  50.      * @param referee 
  51.      */  
  52.     public void setReferee(Referee referee) {  
  53.         this.referee = referee;  
  54.     }  
  55.   
  56. }  
 3.Referee实体类:被维护端(无外键方)
[java]  view plain  copy
  1. @Entity  
  2. @Table(name="T_FOREIGN_REFEREE")  
  3. public class Referee {  
  4.     private int id;  
  5.     private String name;  
  6.     private Customer customer;  
  7.       
  8.     @Id  
  9.     @GeneratedValue(strategy = GenerationType.TABLE, generator = "T_FOREIGN_REFEREE_GEN")  
  10.     @TableGenerator(name = "T_FOREIGN_REFEREE_GEN", table = "TB_GENERATOR", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VALUE", pkColumnValue = "T_FOREIGN_REFEREE_GEN", allocationSize = 1)  
  11.     public int getId() {  
  12.         return id;  
  13.     }  
  14.     public void setId(int id) {  
  15.         this.id = id;  
  16.     }  
  17.     public String getName() {  
  18.         return name;  
  19.     }  
  20.     public void setName(String name) {  
  21.         this.name = name;  
  22.     }  
  23.     //mappedBy表示被维护端  
  24.     @OneToOne(mappedBy="referee")  
  25.     public Customer getCustomer() {  
  26.         return customer;  
  27.     }  
  28.     public void setCustomer(Customer customer) {  
  29.         this.customer = customer;  
  30.     }  
  31.       
  32. }  
 4.CustomerService服务类:
[java]  view plain  copy
  1. @Service("customerService")  
  2. @Transactional  
  3. public class CustomerService {  
  4.     @Resource  
  5.     private SessionFactory sessionFactory;  
  6.   
  7.     public void saveForgin() {  
  8.   
  9.         Customer customer = new Customer();  
  10.         customer.setName("微软");  
  11.   
  12.         Referee referee = new Referee();  
  13.         referee.setName("赵军");  
  14.         customer.setReferee(referee);  
  15.         referee.setCustomer(customer);  
  16.         // 先保存无外键方  
  17.         sessionFactory.getCurrentSession().persist(referee);  //如果这里不想一个对象一个对象保存,想要级联自动保存,需要在保存的对象那一方添加cascade=CascadeType.ALL来级联保存操作
  18.         sessionFactory.getCurrentSession().persist(customer);  
  19.   
  20.     }  
  21.   
  22.     public Customer getCustomer(int id) {  
  23.         return (Customer) sessionFactory.getCurrentSession().get(  
  24.                 Customer.class, id);  
  25.     }  
  26.       
  27.   
  28.     public Referee getReferee(int id) {  
  29.         return (Referee) sessionFactory.getCurrentSession().get(Referee.class,  
  30.                 id);  
  31.     }  
  32.       
  33.           
  34.     /** 
  35.      * 维护端(有外键方)可以维护关系 移除关联关系 
  36.      */  
  37.     public void RemoveRelationForeign() {  
  38.         Customer customer = (Customer) sessionFactory.getCurrentSession().get(  
  39.                 Customer.class1);  
  40.         customer.setReferee(null);  
  41.         sessionFactory.getCurrentSession().persist(customer);  
  42.     }  
  43.   
  44.     /** 
  45.      * 被维护端(无外键方),无法维护关系 ,不可以维护关联关系,所以删除Referee时,如果有关联的Customer,就会抛异常 导致双方都删除不成功 
  46.      */  
  47.     public void RemoveRelationNoForeign() {  
  48.         sessionFactory.getCurrentSession().delete(  
  49.                 sessionFactory.getCurrentSession().get(Referee.class1));  
  50.     }  
  51.     /** 
  52.      * 维护端(外键方)可以维护关系, 
  53.      * 会先移除关联关系 
  54.      * 删除有外键方, 
  55.      */  
  56.     public void RemoveRelationForeignOne()  {  
  57.         sessionFactory.getCurrentSession().delete(  
  58.                 sessionFactory.getCurrentSession().get(Customer.class1));  
  59.     }  
  60.     public void deleteFromNoforeign(){  
  61.         先删除有外键方  
  62.         sessionFactory.getCurrentSession().delete(  
  63.                 sessionFactory.getCurrentSession().get(Referee.class1));  
  64.     }  
  65.     public void deleteFromForeign(){  
  66.         先删除有外键方  
  67.         sessionFactory.getCurrentSession().delete(  
  68.                 sessionFactory.getCurrentSession().get(Customer.class1));  
  69.     }  
  70.     public void DeleteForeignTow()   {  
  71.         先删除有外键方  
  72.         sessionFactory.getCurrentSession().delete(  
  73.                 sessionFactory.getCurrentSession().get(Customer.class1));  
  74.         //再删除无外键方  
  75.         sessionFactory.getCurrentSession().delete(  
  76.                 sessionFactory.getCurrentSession().get(Referee.class1));  
  77.     }  
  78.     @SuppressWarnings("unchecked")  
  79.     public List<Customer> getCustomers(){  
  80.         return sessionFactory.getCurrentSession().createQuery("from Customer").list();  
  81.     }  
  82.       
  83.     @SuppressWarnings("unchecked")  
  84.     public List<Referee> getReferees(){  
  85.         return sessionFactory.getCurrentSession().createQuery("from Referee").list();  
  86.     }  
  87.       
  88.   
  89. }  
 5.测试类:

[java]  view plain  copy
  1. public class CustomerServiceTest {  
  2.     private static CustomerService customerService;  
  3.   
  4.     @BeforeClass  
  5.     public static void setUpBeforeClass() throws Exception {  
  6.         try {  
  7.             ApplicationContext applicationContext = new ClassPathXmlApplicationContext(  
  8.                     "beans.xml");  
  9.             customerService = (CustomerService) applicationContext  
  10.                     .getBean("customerService");  
  11.         } catch (RuntimeException e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15.   
  16.     // 测试保存  
  17.     @Test  
  18.     public void testSaveForgin() {  
  19.         customerService.saveForgin();  
  20.     }  
  21.   
  22.     // 测试获取关联对象的属性值  
  23.     // 两个sql,有外键方  
  24.     @Test  
  25.     public void testGetCustomer() {  
  26.         Customer customer = customerService.getCustomer(1);  
  27.         System.out.println(customer.getReferee().getName());  
  28.     }  
  29.   
  30.     // 测试获取关联对象的属性值  
  31.     // 1条sql,无外键方  
  32.     @Test  
  33.     public void testGetReferee() {  
  34.         Referee referee = customerService.getReferee(1);  
  35.         System.out.println(referee.getCustomer().getName());  
  36.     }  
  37.   
  38.     // 2条sql  
  39.     @Test  
  40.     public void testGetReferees() {  
  41.         for (Referee r : customerService.getReferees()) {  
  42.             System.out.println(r.getName());  
  43.         }  
  44.     }  
  45.   
  46.     // 3条sql  
  47.     @Test  
  48.     public void testGetCustomers() {  
  49.         for (Customer c : customerService.getCustomers()) {  
  50.             System.out.println(c.getName());  
  51.         }  
  52.     }  
  53.   
  54.     // 测试移除关联有关系  
  55.     // 维护端(外键方)可以维护关系 移除关联关系  
  56.     @Test  
  57.     public void testRemoveRelationForeign() {  
  58.         customerService.RemoveRelationForeign();  
  59.     }  
  60.   
  61.     // 测试移除关联有关系  
  62.     // 被维护端(无外键方),无法维护关系 ,不可以维护关联关系,所以删除Referee时,  
  63.     // 如果有关联的Customer,就会抛异常 导致双方都删除不成功  
  64.     @Test  
  65.     public void testRemoveRelationNoForeign() {  
  66.         customerService.RemoveRelationNoForeign();  
  67.   
  68.     }  
  69.   
  70.     // 删除被维护端(无外键方),不能删除  
  71.     @Test  
  72.     public void testdeleteFromNoforeign() {  
  73.         customerService.deleteFromNoforeign();  
  74.     }  
  75.   
  76.     // 删除维护端(有外键方),可以删除  
  77.     @Test  
  78.     public void testDeleeteForeignOne() {  
  79.         customerService.deleteFromForeign();  
  80.     }  
  81.   
  82.     // 两个再时删除,先删除有维护端(有外键方),再删除被维护端(外键方)  
  83.     @Test  
  84.     public void testDeleteForeignTow() {  
  85.         customerService.DeleteForeignTow();  
  86.     }  
  87. }  

二、基于主键一对一关联映射

       基于主键一对一关联,双方都不可以维护关联(不如基于外键的一对一关联),有外键方可以进行删除(双方都删除),无外键方不能进行删除

     

1.数据表关联映射图



 2.CustomerPrimary实体类,关联维护端(有外键方)

[java]  view plain  copy
  1. @Entity  
  2. @Table(name = "T_PRIMARY_CUSTOMER")  
  3. public class CustomerPrimary {  
  4.     private int id;  
  5.     private String name;  
  6.     private RefereePrimary referee;  
  7.   
  8.     @Id  
  9.     // 标注表示这个id属性是外键,并且依赖于customer属性相对应的实体bean的id属性值(主键值)  
  10.     @GeneratedValue(strategy = GenerationType.TABLE, generator = "T_PRIMARY_CUSTOMER_GEN")  
  11.     @TableGenerator(name = "T_PRIMARY_CUSTOMER_GEN", table = "TB_GENERATOR", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VALUE", pkColumnValue = "T_PRIMARY_CUSTOMER_GEN", allocationSize = 1)  
  12.     public int getId() {  
  13.         return id;  
  14.     }  
  15.   
  16.     /** 
  17.      * 注意: 由于t_referee表的id自增类型已经去掉而且该类依赖于t_customers表的id字段值 
  18.      * ,因此就不能直接持久化referee对象了,而是持久化customer对象的同时,ejb3容器会自动将referee持久化的 
  19.      *  
  20.      * @param id 
  21.      */  
  22.     public void setId(int id) {  
  23.         this.id = id;  
  24.     }  
  25.   
  26.     public String getName() {  
  27.         return name;  
  28.     }  
  29.   
  30.     public void setName(String name) {  
  31.         this.name = name;  
  32.     }  
  33.   
  34.     // 共享主键  
  35.     @OneToOne(cascade = CascadeType.ALL)  
  36.     @PrimaryKeyJoinColumn  
  37.     public RefereePrimary getReferee() {  
  38.         return referee;  
  39.     }  
  40.   
  41.     public void setReferee(RefereePrimary referee) {  
  42.         this.referee = referee;  
  43.     }  
  44.   
  45. }  

3. RefereePrimary实体类:关系被维护端(无外键方)

[java]  view plain  copy
  1. @Entity  
  2. @Table(name="T_PRIMARY_REFEREE")  
  3. public class RefereePrimary {  
  4.     private int id;  
  5.     private String name;  
  6.     private CustomerPrimary customer;  
  7.     @OneToOne  
  8.     @PrimaryKeyJoinColumn  
  9.     public CustomerPrimary getCustomer() {  
  10.         return customer;  
  11.     }  
  12.     public void setCustomer(CustomerPrimary customer) {  
  13.         this.customer = customer;  
  14.     }  
  15.     //采用基于主键的一对一映射时,要把主键生成策略改为foreign  
  16.     //属性对应customer  
  17.     @Id  
  18.     @GeneratedValue(generator="pkGenerator")  
  19.     @GenericGenerator(name="pkGenerator",strategy="foreign",  
  20.     parameters=@Parameter(name="property",value="customer"))  
  21.       
  22.     public int getId() {  
  23.         return id;  
  24.     }  
  25.     public void setId(int id) {  
  26.         this.id = id;  
  27.     }  
  28.     public String getName() {  
  29.         return name;  
  30.     }  
  31.     public void setName(String name) {  
  32.         this.name = name;  
  33.     }  
  34. }  

 4.CustomerPrimaryService服务类

[java]  view plain  copy
  1. @Service("customerPrimaryService")  
  2. @Transactional  
  3. public class CustomerPrimaryService  {  
  4.     @Resource  
  5.     private SessionFactory sessionFactory;  
  6.     //测试保存  
  7.     public void savePrimary() {  
  8.         CustomerPrimary customer = new CustomerPrimary();  
  9.         customer.setName("微软");  
  10.   
  11.         RefereePrimary referee = new RefereePrimary();  
  12.         referee.setName("赵军");  
  13.         // 关联起来  
  14.         // 使用基于主键的一对一时:也是只有有外键方可以保存关联关系  
  15.         customer.setReferee(referee);  
  16.         referee.setCustomer(customer);  
  17.         // 先保存无外键方,先保存主键方  
  18.         sessionFactory.getCurrentSession().persist(customer);  
  19.         // 再保存有外键方,因为有外键方要引用无外键方的主键值  
  20.         sessionFactory.getCurrentSession().persist(referee);  
  21.   
  22.     }  
  23.     //测试根据id获取  
  24.     public CustomerPrimary getCustomerPrimary(int id) {  
  25.         return (CustomerPrimary) sessionFactory.getCurrentSession().get(  
  26.                 CustomerPrimary.class1);  
  27.     }  
  28.     //测试根据id获取  
  29.     public RefereePrimary getRefereePrimary(int id) {  
  30.         return (RefereePrimary) sessionFactory.getCurrentSession().get(  
  31.                 RefereePrimary.class1);  
  32.     }  
  33.   
  34.     // 移除关联关系  
  35.     // 使用基于主键的一对一时,双方都不可以移除关联关系  
  36.     public void RemoveRelationPrimary() {  
  37.         CustomerPrimary customer = (CustomerPrimary) sessionFactory  
  38.                 .getCurrentSession().get(CustomerPrimary.class1);  
  39.         customer.setReferee(null);  
  40.         sessionFactory.getCurrentSession().persist(customer);  
  41.     }  
  42.   
  43.     // 移除关联关系  
  44.     // 使用基于主键的一对一时,双方都不可以移除关联关系  
  45.     public void RemoveRelationNoPrimary() {  
  46.         RefereePrimary referee = (RefereePrimary) sessionFactory  
  47.                 .getCurrentSession().get(RefereePrimary.class1);  
  48.         referee.setCustomer(null);  
  49.         sessionFactory.getCurrentSession().persist(referee);  
  50.     }  
  51.   
  52.     // 因为RefereePrimary是无外键言,不可以维护关联关系,所以删除RefereePrimary时,如果有关联的Customer,就会抛异常  
  53.     // 因为CustomerPrimary的id有引用RefereePrimary的id  
  54.     public void DeleteNoForeign() {  
  55.         sessionFactory.getCurrentSession()  
  56.                 .delete(sessionFactory.getCurrentSession().get(  
  57.                         RefereePrimary.class1));  
  58.     }  
  59.     //删除就同时删除CustomerPrimary与RefereePrimary记录  
  60.     public void DeleteForeign() {  
  61.         sessionFactory.getCurrentSession().delete(  
  62.                 sessionFactory.getCurrentSession()  
  63.                         .get(CustomerPrimary.class1));  
  64.     }  
  65.     //测试删除  
  66.     public void DeleteAll() {  
  67.         // 先删除有外键方  
  68.         sessionFactory.getCurrentSession().delete(  
  69.                 sessionFactory.getCurrentSession()  
  70.                         .get(CustomerPrimary.class2));  
  71.   
  72.     }  
  73.     //测试获取列表信息  
  74.     @SuppressWarnings("unchecked")  
  75.     public List<CustomerPrimary> getCustomerPrimarys(){  
  76.         return sessionFactory.getCurrentSession().createQuery("from CustomerPrimary").list();  
  77.     }  
  78.     //测试获取列表信息  
  79.     @SuppressWarnings("unchecked")  
  80.     public List<RefereePrimary> getRefereePrimarys(){  
  81.         return sessionFactory.getCurrentSession().createQuery("from RefereePrimary").list();  
  82.     }  
  83.       
  84.     //测试根据id获取  
  85.     public CustomerPrimary loadCustomerPrimary(int id) {  
  86.         return (CustomerPrimary) sessionFactory.getCurrentSession().get(  
  87.                 CustomerPrimary.class1);  
  88.     }  
  89.     //测试根据id获取  
  90.     public RefereePrimary loadRefereePrimary(int id) {  
  91.         return (RefereePrimary) sessionFactory.getCurrentSession().get(  
  92.                 RefereePrimary.class1);  
  93.     }  
  94. }  
 5.测试类

[java]  view plain  copy
  1. public class CustomerPrimaryServiceTest {  
  2.     private static CustomerPrimaryService customerPrimaryService;  
  3.   
  4.     @BeforeClass  
  5.     public static void setUpBeforeClass() throws Exception {  
  6.         try {  
  7.             ApplicationContext applicationContext = new ClassPathXmlApplicationContext(  
  8.                     "beans.xml");  
  9.             customerPrimaryService = (CustomerPrimaryService) applicationContext  
  10.                     .getBean("customerPrimaryService");  
  11.         } catch (RuntimeException e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15.     //测试保存  
  16.     @Test  
  17.     public void testSavePrimary() {  
  18.         customerPrimaryService.savePrimary();  
  19.     }  
  20.     //测试获取关联获取值  
  21.     //一条sql  
  22.     @Test   
  23.     public void testGetPrimaryCustomer(){  
  24.         CustomerPrimary customer=customerPrimaryService.getCustomerPrimary(1);  
  25.         System.out.println(customer.getReferee().getName());  
  26.     }  
  27.     //测试获取关联获取值  
  28.     //一条sql  
  29.     @Test   
  30.     public void testGetPrimaryReferee(){  
  31.         RefereePrimary referee=customerPrimaryService.getRefereePrimary(1);  
  32.         System.out.println(referee.getCustomer().getName());  
  33.     }  
  34.     //测试移除关系关系  
  35.     @Test  
  36.     public void testRemoveRelationPrimary(){  
  37.         customerPrimaryService.RemoveRelationPrimary();  
  38.     }  
  39.     //测试移除关系关系  
  40.     @Test  
  41.     public void testRemoveRelationNoPrimary(){  
  42.         customerPrimaryService.RemoveRelationNoPrimary();  
  43.     }  
  44.     //无外键方,不可以删除  
  45.     @Test  
  46.     public void testDeleteNoForeign(){  
  47.         customerPrimaryService.DeleteNoForeign();  
  48.     }  
  49.     // 有外键方 可以删除,删除是删除两个表的信息  
  50.       
  51.     @Test  
  52.     public void testDeleteForeign(){  
  53.         customerPrimaryService.DeleteForeign();  
  54.     }  
  55.     //n+1条  
  56.     //测试获取列表信息  
  57.     @Test  
  58.     public void testGetCustomerPrimarys(){  
  59.         for(CustomerPrimary c:customerPrimaryService.getCustomerPrimarys()){  
  60.             System.out.println(c.getName());  
  61.         }  
  62.     }  
  63.     //n+1条  
  64.     //测试获取列表信息  
  65.     @Test  
  66.     public void testGetPrimaryReferees(){  
  67.         for(RefereePrimary r:customerPrimaryService.getRefereePrimarys()){  
  68.             System.out.println(r.getName());  
  69.         }  
  70.     }  
  71. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值