hibernate 学习笔记一
Hibernate中的数据类型
---------------------------
Java中的数据类型
1、基本数据类型
2、对象类型
Hibernate中的数据类型
1、值类型(int double string):没有对应的映射文件不能单独被映射
2、实体类型:有对应的映射文件,可以单独被映射
-------------------------------------------------------
关联关系映射
---------------------------
一对一映射
1、唯一外键关联
表上:
table usertable adddress
id<PK> id<PK>
name city
age street
address_id<FK>
类上:
class Userclass Address
id id
name city
age street
Address User
映射文件上:
User.hbm.xml
<many-to-one name = "address" class = "Address" column = "address_id" unique = "true"/>
Address.hbm.xml
<one-to-one name = "user" class = "User"/>
2、主键关联
表上:
table usertable address
id<PK> id<PK><FK>
name city
age street
类上:
class Userclass Address
id id
name city
age street
Address User
映射文件上:
User.hbm.xml
<one-to-one name = "address" class = "Address"/>
Address.hbm.xml
<one-to-one name = "user" class = "User"/>
<id name = "id" column = "id">
<generator class = "foreign">
<param name = "property">user</param>
</generator>
</id>
一对多关联
1、单向关联(unidirectional)
表上:
table usertable address
id<PK> id<PK>
name city
age street
address_id<FK>
类上:
class Userclass Address
id id
name city
age street
Address
映射文件上:
User.hbm.xml
<many-to-one name = "address" column = "address_id"/>
Address.hbm.xml
不需特殊处理
2、双向关联(bidirectional)
表上:
table usertable address
id<PK> id<PK>
name city
age street
address_id<FK>
类上:
class Userclass Address
id id
name city
age street
Address Set<User>
映射文件上:
User.hbm.xml
<many-to-one name = "address" column = "address_id"/>
Address.hbm.xml
<set name = "users" inverse = "true">
<key column = "address_id"/>
<one-to-many class = "User"/>
</set>
<inverse>:在映射双向关联关系时,可以将父表所对应映射文件中的inverse属性设为true,以避免双方都对关联
进行维护,可以减少update语句,提高性能
在映射一对多的双向关联时,应该在"one"方把inverse属性设为true,这样可以提高应用的性能,并且
在建立两个对象的双向关联时,应该同时修改关联两端的对象的相应属性
<cascade>:设置级联关系
save-update:级联保存、更新
delete:级联删除
all:包括save-update,delete
none:不级联
多对多关联
1、单向关联
2、双向关联
表上:
tabe usertable user_addresstable address
id<PK> user_id<PK,FK> id<PK>
name address_id<PK,FK> city
age street
类上:
class Userclass Address
id id
name city
age street
Set<Address> Set<User>
映射文件中:
User.hbm.xml
<set name = "addresses" inverse = "true" table = "user_address>
<key column = "user_id"></key>
<many-to-many column = "address_id" class = "Address"></many-to-many>
</set>
Address.hbm.xml
<set name = "users" inverse = "true" table = "user_address>
<key column = "address_id"></key>
<many-to-many column = "user_id" class = "User"/>
</set>