近日用到了Hibernate JPA 一对多,多对一的功能,一上午时间各种错误不断涌现,现在终于得到解决,现在写下来,以作备忘。
Channel.class 父类
@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "channel")
private List<Content> contentList;
public List<Content> getContentList() {
return contentList;
}
public void setContentList(List<Content> contentList) {
this.contentList = contentList;
}
Content.class 子类
@ManyToOne
@JoinColumn(name = "channelId", insertable = false, updatable = false)
private Channel channel;
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
===================================其它注解的小结==================================
注解的@Id可以放在属性上和get方法上, 建议放在方法上
一般采用jpa的注解, 因为移植性好
了解常用注解
@Entity
@Table
@GeneratedValue 默认情况下会采用auto生成方式
如果要采用uuid的生成方式,由于jpa注解不支持此种方法,则要用hibernate的注解联合起来使用
具体的用法如下:
@GenericGenerator(name="idGenerator", strategy="uuid") //这个是hibernate的注解
@GeneratedValue(generator="idGenerator") //使用uuid的生成策略
对于普通属性的注解
@Column(name="username", nullable=false, unique=true, length=30) 不为空, 唯一, 长度30
对于不想进行持久化的属性的注解
@Transient
hibernate JPA多对一关联映射
采用@ManyToOne来映射多对一
关于关联对象在表中的维护, JPA采用关联对象+ "_" + "id"方式作为字段加入表中.
一对多关联映射
mappedBy在那一端, 那一端就不维护关系
相当于hibernate中的inverse=true
采用@OneToMany
了解mappedBy属性
JoinColumn属性
TargetEntity属性
采用manyToMany映射
采用@JoinTable指定第三方表