示例:一个类别(Category)下面有多个商品(Product),多个商品对应对应同一类别
- public class Category {
- private Integer id;
- private String name;
- private Set<Product> products = new HashSet<Product>();
- // getter and setter
- }
- public class Product {
- private Integer id;
- private String name;
- private Double price;
- private Category category;
- // getter and setter
- }
用XML映射
- <hibernate-mapping package="org.monday.hibernate4.domain">
- <class name="Category" table="tbl_category">
- <id name="id">
- <generator class="identity" />
- </id>
- <property name="name" />
- <set name="products" inverse="true">
- <key column="category_id" />
- <one-to-many class="Product" />
- </set>
- </class>
- </hibernate-mapping>
- <hibernate-mapping package="org.monday.hibernate4.domain">
- <class name="Product" table="tbl_product">
- <id name="id">
- <generator class="identity" />
- </id>
- <property name="name" />
- <property name="price" />
- <many-to-one name="category" class="Category"
- column="category_id" not-null="true"/>
- </class>
- </hibernate-mapping>
用@Annotation映射
- @Entity
- @Table(name = "tbl_category")
- public class Category {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- private String name;
- // 使用泛型的话,targetEntity可以不制定
- @OneToMany(mappedBy = "category")
- private Set<Product> products = new HashSet<Product>();
- // getter and setter
- }
- @Entity
- @Table(name = "tbl_product")
- public class Product {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- private String name;
- private Double price;
- @ManyToOne
- @JoinColumn(name = "category_id", nullable = false)
- private Category category;
- // getter and setter
- }
测试代码
- Product p = new Product();
- p.setName("hibernate");
- p.setPrice(99.9);
- Category c = new Category();
- c.setName("book");
- c.getProducts().add(p);
- p.setCategory(c);
- session.save(c); // 先插入一的一方
- session.save(p);
SQL schema
- Hibernate:
- create table tbl_category (
- id integer not null auto_increment,
- name varchar(255),
- primary key (id)
- )
- Hibernate:
- create table tbl_product (
- id integer not null auto_increment,
- name varchar(255),
- price double precision,
- category_id integer,
- primary key (id)
- )
- Hibernate:
- alter table tbl_product
- add index FK2BA956E5535EE4C (category_id),
- add constraint FK2BA956E5535EE4C
- foreign key (category_id)
- references tbl_category (id)
- Hibernate:
- insert
- into
- tbl_category
- (name)
- values
- (?)
- Hibernate:
- insert
- into
- tbl_product
- (name, price, category_id)
- values
- (?, ?, ?)
-