讲述hibernate中关系
多对一:
在表中多写一个属性表示所属的ID。
用hibernate实现,就是先写一个Class,
public
class
Category {
public
int
getId() {
return
id;
}
public
void
setId(
int
id) {
this
.id = id;
}
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
int
id;
String name;
}
准备Category.hbm.xml
<?
xml
version
=
"1.0"
?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<
hibernate-mapping
package
=
"包名"
>
<
class
name
=
"Category"
table
=
"category_"
>//表示Category对应表category_会自动创建
<
id
name
=
"id"
column
=
"id"
>//表示类中的id对应表中的id
<
generator
class
=
"native"
>//表示id为主键
</
generator
>
</
id
>
<
property
name
=
"name"
/>//没有打column表示默认表中的name对应表中的name
</
class
>
</
hibernate-mapping
>
在Product.java中添加Category属性
Category category;
public
Category getCategory() {
return
category;
}
public
void
setCategory(Category category) {
this
.category = category;
}
在Product.hbm.xml中设置多对一关系
<
many-to-one
name
=
"category"
class
=
"Category"
column
=
"cid"
/> 默认对应Category中的主键
在hibernate.cfg.xml中增加Cayegory的映射
<
mapping
resource
=
"包名/Category.hbm.xml"
/>