免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3778 | 回复: 0
打印 上一主题 下一主题

Java persistence with Hibernate [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-12-29 21:38 |只看该作者 |倒序浏览
hibernate的精华不是配置,但对于目前的我来说,配置是第一个要解决的问题.
网络学习: http://www.6suv.com/20080619/14559/
http://www.javadby.com/yuyanjichu/20071114/2977_2.html

主要学习hibernate注释的配置,其次是xml文件的配置.(只是摘记了一些对自己存在疑问的信息)
Let’s see what that looks like in an example. Annotate the Item entity source
code again:
package auction.model;
import javax.persistence.*;
@Entity
@Table(name = "ITEM")
@org.hibernate.annotations.BatchSize(size = 10)
@org.hibernate.annotations.DiscriminatorFormula(
"case when ITEM_IS_SPECIAL is not null then A else B end"
)
public class Item {
...
}
This example contains two Hibernate annotations. The first, @BatchSize, is a
fetching option that can increase performance in situations we’ll examine later
in this book. The second, @DiscriminatorFormula, is a Hibernate mapping
annotation that is especially useful for legacy schemas when class inheritance
can’t be determined with simple literal values (here it maps a legacy column
ITEM_IS_SPECIAL—probably some kind of flag—to a literal value). Both annotations
are prefixed with the org.hibernate.annotations package name.     

Mapping the identifier property
XML形式
id" column="CATEGORY_ID" type="long">  (long相当于大部分数据库里的bigint)
native"/>(产生主键的方式)
...
Annotations形式
@Entity
@Table(name="CATEGORY")
public class Category {
private Long id;
...
@Id
@GeneratedValue(strategy = GenerationType.AUTO)  产生主键方式即native,默认就是这个,可省略.
@Column(name = "CATEGORY_ID")  数据库里的列
....
}
可以在标实符里添加参数
Some of the built-in identifier generators can be configured with options. In a
native Hibernate XML mapping, you define options as pairs of keys and values:
MY_SEQUENCE
INCREMENT BY 1 START WITH 1
You can use Hibernate identifier generators with annotations, even if no direct
annotation is available:
@Entity
@org.hibernate.annotations.GenericGenerator(
name = "hibernate-uuid",
strategy = "uuid"
)
class name MyEntity {
@Id
@GeneratedValue(generator = "hibernate-uuid")
@Column(name = "MY_ID")
String id;
}
还可以写在一个文件里,再引用.
4.3 Class mapping options
Dynamic generation of CRUD SQL statements(在启动时运行的)
Two attributes for disabling CRUD SQL generation on startup are available on
the  mapping element:
dynamic-insert="true"
dynamic-update="true">
...
The dynamic-insert attribute tells Hibernate whether to include null property
values in an SQL INSERT, and the dynamic-update attribute tells Hibernate
whether to include unmodified properties in the SQL UPDATE.
就是说如果设置成true,这个值为空,就不会加入sql语句中.从
insert into Users (age, firstname, lastname) values (?, ?, ?)变成
insert into Users (age) values (?),同理update.可以节省内存(参考http://www.cublog.cn/u/1096/showart_371961.html)
@Entity
@org.hibernate.annotations.Entity(
dynamicInsert = true, dynamicUpdate = true
)
public class Item {}
Making an entity immutable
mutable="false">
...

@Entity
@org.hibernate.annotations.Entity(mutable = false)
@org.hibernate.annotations.AccessType("field")
public class Bid { ...}
mutable (可选,默认值为true): 表明该类的实例是可变的或者不可变的。
Naming entities for querying
rename="IAuditable"/>
@Entity(name="AuctionItem")
public class Item { ... }
目前还是有点疑问,应该就是重命名了,也就是相当于namespace的作用.
4.4.1 Mapping basic properties
也可以将column单独提取出来成为元素,而不是一个属性.
@Basic(optional = false)
@Column(nullable = false)
public BigDecimal getInitialPrice { return initialPrice; }
The @Basic annotation marks the property as not optional on the Java object
level.
如果访问类型为property access就要在getter方法上进行注解声明,如果访问类型为 field access就要在字段上进行注解声明
column="DESCR"
access="field"/>
Or, you can set the access strategy for all class mappings inside a root
element with the default-access attribute.
Generated and default property values
1
column="LAST_MODIFIED"
update="false"
insert="false"
generated="always"/>

@Column(updatable = false, insertable = false)
@org.hibernate.annotations.Generated(
org.hibernate.annotations.GenerationTime.ALWAYS
)
private Date lastModified;
2
dynamic-insert="true" dynamic-update="true">  //动态的,但为空的产生认为null
...
default="'1'"                          //默认值为1
generated="insert"/>
...

Item newItem = new Item(...);
session.save(newItem);
newItem.getInitialPrice(); // is null
session.flush(); // Trigger an INSERT
// Hibernate does a SELECT automatically
newItem.getInitialPrice(); // is $1
@Column(name = "INITIAL_PRICE",
columnDefinition = "number(10,2) default '1'")
@org.hibernate.annotations.Generated(
org.hibernate.annotations.GenerationTime.INSERT
)
private BigDecimal initalPrice;
Component mapping in XML
即在user里加入address(Component).
component name="homeAddress" class="Address">
column="HOME_STREET" not-null="true"/>
column="HOME_CITY" not-null="true"/>
column="HOME_ZIPCODE" not-null="true"/>
component name="billingAddress" class="Address">
如果在此处加入,则可以利用Address.getUser()
column="BILLING_STREET" not-null="true"/>
column="BILLING_CITY" not-null="true"/>
column="BILLING_ZIPCODE" not-null="true"/>
...

A Hibernate component can own other components and even associations to
other entities.
component name="homeAddress" class="Address">
component name="location" class="Location">
The design of the Location class is equivalent to the Address class. You now have
three classes, one entity, and two value types, all mapped to the same table.
Annotating embedded classes
@Entity
@Table(name = "USERS")
public class User {
...
@Embedded
private Address homeAddress;
...
}
This is what the embeddable class looks like:
@Embeddable
public class Address {
@Column(name = "ADDRESS_STREET", nullable = false)
private String street;
...
}
you can rename the columns:
@Entity
@Table(name = "USERS")
public class User {
...
@Embedded
@AttributeOverrides( {
@AttributeOverride(name = "street",
column = @Column(name="HOME_STREET") ),   //完全覆盖了, Note that all attributes on the embedded @Column annotation
                                      are replaced, so they’re no longer nullable = false.
@AttributeOverride(name = "zipcode",
column = @Column(name="HOME_ZIPCODE") ),
@AttributeOverride(name = "city",
column = @Column(name="HOME_CITY") )
})
private Address homeAddress;
...
}
In a JPA XML descriptor, a mapping of an embeddable class and a composition
looks like the following:
...
attribute-override name="street">
Inheritance and custom types
5.1.1 Table per concrete class with implicit polymorphism
见图193,pdf 228
You need to annotate the superclass to
enable embedding of its properties in the concrete subclass tables:
@MappedSuperclass        
public abstract class BillingDetails {
@Column(name = "OWNER", nullable = false)
private String owner;
...
}
Now map the concrete subclasses:
@Entity
@AttributeOverride(name = "owner", column =
@Column(name = "CC_OWNER", nullable = false)   //You rename the OWNER column to CC_OWNER in
the CREDIT_CARD table.
)
public class CreditCard extends BillingDetails {
@Id @GeneratedValue
@Column(name = "CREDIT_CARD_ID")
private Long id = null;
@Column(name = "NUMBER", nullable = false)
private String number;
...
}
Let’s repeat the same mapping in a JPA XML descriptor:
mapped-superclass class="auction.model.BillingDetails" //抽象类
access="FIELD">
...
CreditCard" access="FIELD">  //实体类
           //覆盖
...
...
5.1.2 Table per concrete class with unions

name="BillingDetails"   //抽象类
abstract="true">
id             //共享,所以实体类中不存在.
name="id"
column="BILLING_DETAILS_ID"
type="long">
property
name="name"
column="OWNER"
type="string"/>
...
union-subclass            //实体类
name="CreditCard" table="CREDIT_CARD">
union-subclass            //实体类
name="BankAccount" table="BANK_ACCOUNT">
...
In JPA annotations, this strategy is known as TABLE_PER_CLASS(可选):
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BillingDetails {        //抽象类
@Id @GeneratedValue
@Column(name = "BILLING_DETAILS_ID")
private Long id = null;
@Column(name = "OWNER", nullable = false)
private String owner;
...
}

@Entity
@Table(name = "CREDIT_CARD")
public class CreditCard extends BillingDetails {     //实体类
@Column(name = "NUMBER", nullable = false)
private String number;
...
}
The same mapping looks like this in a JPA XML descriptor:
BillingDetails" access="FIELD">
TABLE_PER_CLASS"/>
...
CreditCard" access="FIELD"/>
BankAccount" access="FIELD"/>
For example, a query for BillingDetails executes the following
SQL statement:
select
BILLING_DETAILS_ID, OWNER,
NUMBER, EXP_MONTH, EXP_YEAR,  // CreditCard独有的
ACCOUNT, BANKNAME, SWIFT // BankAccount独有的
CLAZZ_
from
( select
BILLING_DETAILS_ID, OWNER,
NUMBER, EXP_MONTH, EXP_YEAR,
null as ACCOUNT, null as BANKNAME, null as SWIFT,
1 as CLAZZ_
from
CREDIT_CARD
union
select
BILLING_DETAILS_ID, OWNER,
null as NUMBER, null as EXP_MONTH, null as EXP_YEAR, ...
ACCOUNT, BANKNAME, SWIFT,
2 as CLAZZ_
from
BANK_ACCOUNT
)
5.1.3 Table per class hierarchy
This mapping strategy is a winner in terms of both performance and simplicity.
It’s the best-performing way to represent polymorphism—both polymorphic and
nonpolymorphic queries perform well.就是存在问题有比较多的属性都存在为null.
the loss of NOT NULL constraints may be a serious problem.
Another important issue is normalization.
图见书199页,pdf234页.
In Hibernate, you use the  element to create a table per class hierarchy
mapping,
name="BillingDetails"
table="BILLING_DETAILS">
name="id"
column="BILLING_DETAILS_ID"
type="long">
discriminator              //The column name is   BILLING_DETAILS_TYPE, and the values are
strings—in this case, “CC” or “BA”.为了区别persistence class.
column="BILLING_DETAILS_TYPE"          //特殊的列
type="string"/>
name="owner"
column="OWNER"
type="string"/>
...
name="CreditCard"
discriminator-value="CC">
name=”BankAccount”
discriminator-value=”BA”>
...
This mapping strategy is also available in JPA, as SINGLE_TABLE:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(           //特殊列
name = "BILLING_DETAILS_TYPE",
discriminatorType = DiscriminatorType.STRING
)
public abstract class BillingDetails {
@Id @GeneratedValue
@Column(name = "BILLING_DETAILS_ID")
private Long id = null;
@Column(name = "OWNER", nullable = false)
private String owner;
...
}
Credit-Card is a concrete class:
@Entity
@DiscriminatorValue("CC")
public class CreditCard extends BillingDetails {
@Column(name = "CC_NUMBER")
private String number;
...
}
This is the equivalent mapping in JPA XML descriptors:
BillingDetails" access="FIELD">
discriminator-column name="BILLING_DETAILS_TYPE"
discriminator-type="STRING"/>
...
CreditCard" access="FIELD">
CC
...
5.1.4 Table per subclass
书204页,pdf 239页 图
name="BillingDetails"
table="BILLING_DETAILS">
name="id"
column="BILLING_DETAILS_ID"
type="long">

name="owner"
column="OWNER"
type="string"/>
...
joined-subclass
name="CreditCard"
table="CREDIT_CARD">
key column="CREDIT_CARD_ID"/>
name="BankAccount"
table="BANK_ACCOUNT">
...
Let’s map the hierarchy with the same strategy and annotations, here called
the JOINED strategy:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class BillingDetails {
@Id @GeneratedValue
@Column(name = "BILLING_DETAILS_ID")
private Long id = null;
...
}

@Entity
@PrimaryKeyJoinColumn(name = "CREDIT_CARD_ID")  //可省略
public class CreditCard {
...
}
Finally, this is the equivalent mapping in JPA XML descriptors:
...
5.1.5 Mixing inheritance strategies
209,pdf 244
利用join.
name="CreditCard"
discriminator-value="CC">
join table="CREDIT_CARD" fetch="select">     
CREDIT_CARD_ID"/>
...

@Entity
@DiscriminatorValue("CC")
@SecondaryTable(
name = "CREDIT_CARD",
pkJoinColumns = @PrimaryKeyJoinColumn(name = "CREDIT_CARD_ID")
)
public class CreditCard extends BillingDetails {
@Column(table = "CREDIT_CARD",
name = "CC_NUMBER",
nullable = false)
private String number;
...
}
Binary and large value mapping types
If you want to map a java.lang.String, char[], Character[], or even a
java.sql.Clob typed property to a CLOB column, you need to map it with the@Lob annotation:
@Lob
@Column(name = "ITEM_DESCRIPTION")
private String description;
@Lob
@Column(name = "ITEM_IMAGE")
private byte[] image;
Hibernate中日期的表示
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false, updatable = false)
private Date startDate;
The equivalent JPA XML descriptor is as follows:
...
temporal>TIMESTAMP
5.3 Creating custom mapping types
5.3.4 Creating a UserType
写自己的类,继承hibernate,暂时用不到,先略一下.




本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/31712/showart_453182.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP