Hibernate的组件(Component)映射

  在学习Hibernate框架时碰到了许多实际的问题,比如一个Name是由FirstName和LastName组成,或者说一个Address是有Province,City,County和The detailed address组成,那么这么复杂的属性作为实际设计中是不应该出现在一个类里,那么组件映射就出现了

  下面展示组件映射的实例,User对象中的Name属性

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.dao">

    <class name="User" table="User">
        <id name="id">
            <generator class="native" />
        </id>
 
        <component name="name">
            <property name="firstname" column="first_name"/>
            <property name="lastname" column="last_name" />
        </component>
        
        <property name="birthday" />

    </class>

</hibernate-mapping>

 

User.java代码

 1 package com.dao;
 2 
 3 import java.util.Date;
 4 
 5 public class User {
 6     private int id;
 7     private Name name;
 8     private Date birthday;
 9 
10     public void setName(Name name) {
11         this.name = name;
12     }
13 
14     public int getId() {
15         return id;
16     }
17 
18     public void setId(int id) {
19         this.id = id;
20     }
21 
22     public Name getName() {
23         return name;
24     }
25 
26     public Date getBirthday() {
27         return birthday;
28     }
29 
30     public void setBirthday(Date birthday) {
31         this.birthday = birthday;
32     }
33 }

 

Name的代码

package com.dao;

public class Name {
    private String firstname;
    private String lastname;
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。