Spring JPA annotation关于一对多,多对一的那些纠结

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

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值