组件映射

来源:互联网 发布:比思论坛永久域名 编辑:程序博客网 时间:2024/05/22 11:30

组件映射

         在Hibernate的持久化类的设计上,我们还可以采取细粒度的对象模型设计(fine-grained Object model),对持久化类的设计进行细化。所谓的细粒度的对象模型,就是与前面章节所讲解的把数据库中一个表映射成一个持久化类相比较,可以把一个表映射成两个或者多个类这些被细分出来的类,可以称为组件(Component)

    

    采用一定的细粒度对象模型设计后,一方面,设计上更加合理;另一方面,还可以在一定程度上提高Hibernate的运行效率在具体的实现上,组件与持久化类的区别在于组件没有标识符属性,只作为一个逻辑组成,完全从属于持久化对象

   

1、在Oracle数据库中创建表usersSQL语句如下,有下面8个字段:

create table users

(

id number(8) not null primary key,

username varchar2(40),

password varchar2(40),

phone varchar2(16),

mobile varchar2(11),

email varchar2(100),

address varchar2(200),

postcode varchar2(8)

);

其中id,username,password是比较常用的,其余的信息使用得比较少。平常我们会把这些属性全部写在一个持久化类中,

现在,我们这样来设计:

设计一个Profile类来存储不常用的属性,Profile类就是“组件”,代码如下:


package com.anbo.po;

public class Profile implements java.io.Serializable{

private String email;

private String phone;

private String mobile;

private String address;

private String postcode;

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public String getMobile() {

return mobile;

}

public void setMobile(String mobile) {

this.mobile = mobile;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

public String getPostcode() {

return postcode;

}

public void setPostcode(String postcode) {

this.postcode = postcode;

}

}

然后在User这个持久化类中包含了Profile这个组件,如下:

package com.anbo.po;

public class User implements java.io.Serializable{

private Integer id;

private String username;

private String password;

private Profile profile;

public User() {

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public Profile getProfile() {

return profile;

}

public void setProfile(Profile profile) {

this.profile = profile;

}

}

UserProfile类之间的关系是组合(component)关系,一个User对象包含一个Profile对象, 同时User对象和Profile对象具有相同的生命周期。

2User.hbm.xml文件如下:

组件component中的name="profile"设定组件映射对象在User类中的属性名为profileclass="com.anbo.po.Profile"设置profile属性的类型为com.anbo.po.Profile

组件中<property>标签用于配置Profile类的属性与users表中字段的映射关系

下面是测试类中的部分代码:

运行程序

结果如下:

控制台打印的Sql语句

Oracle数据库Users表中的一条记录



说明:该例子是组合的单项导航。只能由
User类访问Profile(组件类)。
0 0
原创粉丝点击