Hibernate4一对多关系映射

2018年12月16日 次阅读 0 条评论 0 人点赞

示例:一个类别(Category)下面有多个商品(Product),多个商品对应对应同一类别public class Category { priva

示例:一个类别(Category)下面有多个商品(Product),多个商品对应对应同一类别

public class Category {  
  
       private Integer id;  
    private String name;  
    private Set products = new HashSet();  
  
    // getter and setter  
}     
public class Product {  
  
    private Integer id;  
    private String name;  
    private Double price;  
    private Category category;  
      
    // getter and setter  
}  

 用XML映射

  
      
          
              
          
          
          
              
              
          
      
  
  
      
          
              
          
          
          
          
      
  

 用@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 products = new HashSet();  
  
    // 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  
        (?, ?, ?)  

 

由Cavien发布

没有天生的高手,更没有永远的菜鸟

文章评论(0)