Java 持久化规范允许你插入非实体的Java对象在实体组件中并且映射的嵌入对象属性值到实本表中的栏位.这些对象没有任何标识并且被包含的实体组件类所专有.@EmbeddedId主键的规则非常的简单如同前面的例子.我们首先定义一个内部对象:
package com.titan.domain;
import javax.persistence.*;
@Embeddable
public class Address implements java.io.Serializable {
private String street;
private String city;
private String state;
public String getStreet( ) { return street; }
public void setStreet(String street) { this.street = street; }
public String getCity( ) { return city; }
public void setCity(String city) { this.city = city; }
public String getState( ) { return state; }
public void setState(String state) { this.state = state; }
}
内部的Address类有@Column映射定义在里面.其次,使用@javax.persistence.Embedded注释在Customer组件类内的嵌入实例Address,类:
package javax.persistence;
public @interface Embedded {}
同样的@EmbeddedId,@Embedded注释能够被联合同@AttributeOverrides注释一同使用如果你想覆盖指定嵌入类的信息.下面的例子显示如果覆盖.如果你不想覆.省去@AttributeOverrides注释.
package com.titan.domain;
import javax.persistence.*;
@Entity
@Table(name="CUSTOMER_TABLE")
public class Customer implements java.io.Serializable {
private long id;
private String firstName;
private String lastName;
private Address address;
...
@Embedded
@AttributeOverrides({
@AttributeOverride
(name="street",
column=@Column(name="CUST_STREET")),
@AttributeOverride(name="city", column=@Column(name="CUST_CITY")),
@AttributeOverride(name="state", column=@Column(name="CUST_STATE"))
})
public Address getAddress( ) {
return address;
}
...
}
在本例中,我们映射Address类属性到Customer_table表中的栏位.如果你不想指定@Embedded注释和Address类是序列化的,那么持久化提供者假定它是@Lob类型与序列化的字节流到Customer_table 表中的栏位.
看一下XML映射文件:
<entity-mappings>
<embeddable class="com.titan.domain.Address" access-type="PROPERTY"/>
<entity class="com.titan.domain.Customer" access="PROPERTY">
<attributes>
<id name="id"/>
<embedded name="address">
<attribute-override name="street">
<column name="CUST_STREET"/>
</attribute-override>
<attribute-override name="city">
<column name="CUST_CITY"/>
</attribute-override>
<attribute-override name="state">
<column name="CUST_STATE"/>
</attribute-override>
</embedded>
</attributes>
</entity>
</entity-mappings>
这个看起来非常准确的<embedded-id>映射,除了映射一个指定的属性使用<embedded>元素,其它的都相同.
简而言之,都是关于基本的属性映射.在下一章中,我们将讨论怎样映射复杂的关在多个实体组件之间.
我的联系方式:
QQ:495585885
Email:[email protected]
我的博客:http://hi.baidu.com/vsandjava
下载地址:
主页公布邮箱或
http://lyh007.gbaopan.com/files/2d0f192dbab34ded90da94796b21d4ec.gbp