组件映射

Husband 中 有一个 Wife 属性,数据库不生成Wife表,仅将Wife的所有字段都加到Husband表中。

  Annotation 配置:

 

    如果 Husband 类的属性比如 husband 的 name 属性和 wife 的name属性冲突,有两种解决方案:

      1、将 wife的name属性改为 wifeName;

      2、通过 @AttributeOverrides 自己一个一个对wife的属性进行设置就可以了,如下:

  @Embedded
    @AttributeOverrides(value = { 
            @AttributeOverride(name="wifeName", column=@Column(name="wifName2")),//别名
            @AttributeOverride(name="age", column=@Column(name="wifeAge"))
    })
    public Wife getWife() {
        return wife;
    }

Husband 类:

 1 package com.bjsxt.hibernate;
 2 
 3 import javax.persistence.Embedded;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.Id;
 7 
 8 @Entity
 9 public class Husband {
10     
11     private Integer id;
12     
13     private String name;
14 
15     private Wife wife;
16     
17     @Id
18     @GeneratedValue
19     public Integer getId() {
20         return id;
21     }
22 
23     public String getName() {
24         return name;
25     }
26 
27     @Embedded
28     public Wife getWife() {
29         return wife;
30     }
31 
32     public void setId(Integer id) {
33         this.id = id;
34     }
35 
36     public void setName(String name) {
37         this.name = name;
38     }
39 
40     public void setWife(Wife wife) {
41         this.wife = wife;
42     }
43 }

    Wife 类:

 1 package com.bjsxt.hibernate;
 2 
 3 public class Wife {
 4     
 5     private String wifeName;
 6     
 7     private int age;
 8 
 9     public String getWifeName() {
10         return wifeName;
11     }
12 
13     public void setWifeName(String wifeName) {
14         this.wifeName = wifeName;
15     }
16 
17     public int getAge() {
18         return age;
19     }
20 
21     public void setAge(int age) {
22         this.age = age;
23     }
24 }

生成的SQL语句

XML 配置:

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5 
 6 <hibernate-mapping package="com.bjsxt.hibernate">
 7     <class name="Husband" table="husband">
 8         <id name="id" column="id">
 9             <generator class="native"/>
10         </id>
11         
12         <property name="name" column="name" />
13         
14         <component name="wife">
15             <property name="wifeName" column="wifeName" />
16             <property name="age" column="wifeAge" />
17         </component>
18     </class>
19 </hibernate-mapping>

生成的SQL语句:

jar包链接: https://pan.baidu.com/s/1kUARge7 密码: nsyb

代码链接: https://pan.baidu.com/s/1o7QZZOA 密码: stbv

posted @ 2017-04-19 17:34  流年如水烟雨随风  阅读(241)  评论(0编辑  收藏  举报