多对一
//Product的类
package com.spike.pojo;
import com.spike.pojo.Category;
public class Product{
private int id;
private String name;
private Category category;
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setCategory(Category category){
this.category = category;
}
public int getId(){ return this.id; }
public String getName(){ return this.name; }
public Category getCategory(){ return this.category; }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Product" table="product_">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property>
<many-to-one class="Category" name="category" column="cid"></many-to-one>
</class>
</hibernate-mapping>
其中标签中
name=“category” 对应 Product 中的category属性
class=“Category” 对应 category对应的Category类
column=“cid” 对应 product_表的cid数据
一对多
package com.spike.pojo;
import com.spike.pojo.Product;
import java.util.Set;
public class Category{
private int id;
private String name;
private Set<Product> products;
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setProducts(Set<Product> products){
this.products = products;
}
public int getId(){ return this.id; }
public String getName(){ return this.name; }
public Set<Product> getProducts(){ return this.products; }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Category" table="category_">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property>
<set name="products" lazy="false">
<key column="cid"></key>
<one-to-many class="Product"></one-to-many>
</set>
</class>
</hibernate-mapping>
<“set”>标签中
name 对应于 Category 属性products
<“key”>中
column 中的 cid 与 category_表中的 id 一致
多对多
Java代码就按照UML图就行了
XML代码
Product差异
<set name="users" table="user_product" lazy="false">
<key column="pid"></key>
<many-to-many class="User" column="uid"></many-to-many>
</set>
set标签中
name对应于Product属性中的users
table中的表 user_product , 根据多对多原则,将Product中的主码id与User中的主码id合成的一个新表
key标签中
product_表中的id对应user_product中的pid
many-to-many标签中
class对应类User 其id对应user_product中的uid
这是基于对how2J代码的理解,错误的麻烦指正
更多教程
转载:https://blog.csdn.net/bushiroad/article/details/102013087
查看评论