赞
踩
首先介绍我们的表结构,便于理解我们的demo,从而了解两个标签的使用
pet表,id主键,name宠物名,owner主人,age年纪,category_id外键关联category表
这里一个category对应多个pet,所以category是我们的一端,pet是我们的多端
category表,id主键,category_name种类名,category_code种类编码
@OneToMany的使用在一端的集合属性上面,用于指定与之关联的多个实体
代码:
CategoryEntity实体类
@Entity @Table(name = "category") public class CategoryEntity extends BaseEntity{ @Column private String categoryName; @Column private String categoryCode; @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY) @JoinColumn(name = "category_id ") private Set<PetEntity> pets; public CategoryEntity() { } public CategoryEntity(String categoryName, String categoryCode, Set<PetEntity> pets) { this.categoryName = categoryName; this.categoryCode = categoryCode; this.pets = pets; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getCategoryCode() { return categoryCode; } public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; } public Set<PetEntity> getPets() { return pets; } public void setPets(Set<PetEntity> pets) { this.pets = pets; } }
@OneToMany中mappedBy属性的作用跟@Join Column标签一样,都是由于指定关联键的,mappedBy指定的是实体类中的属性,@JoinColumn指定的是数据表里面的字段
例:
我们在@JoinColumn中name设置为实体中的属性“categoryId”便会报错:找不到表中对应的categoryId
同样我们在mappedBy中应该使用实体属性,使用表字段也会报错
PetEntity实体类
@Entity @Table(name = "pet") public class PetEntity extends BaseEntity{ @Column private String name; @Column private String owner; @Column private String age; @Column(name = "category_id") private String categoryId; public PetEntity() { } public PetEntity(String name, String owner, String age,String categoryId) { this.name = name; this.owner = owner; this.age = age; this.categoryId=categoryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。