近日用到了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指定第三方表