首页 > Web开发 > 详细

hibernate实体注解 @OneToMany、@OneToOne、@ManyToOne、@ManyToMany

时间:2021-08-16 23:02:26      阅读:58      评论:0      收藏:0      [点我收藏+]

hibernate注解关联查询:一对多、一对一、多对一、多对多

两张表UserTest、AddressTest

技术分享图片

 

 技术分享图片

 

 

一对多:@OneToMany

  实体注解:

@Fetch(FetchMode.SUBSELECT)
@OneToMany(targetEntity = AddressTest.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ADDRESS_USERID", referencedColumnName = "USER_ID", insertable = false, updatable = false)
 private List<AddressTest> machineMapperList;


ADDRESS_USERID字段是ADDRESS_TEST表中的关联字段
USER_ID字段位USER_TEST表中的主键

结果:UserTest{userId=‘H320210816161029000001‘, userName=‘张三‘,
machineMapperList=[AddressTest{addressId=‘H320210816161316000001‘, userId=‘H320210816161029000001‘, addressInfo=‘北京市‘, state=1},
AddressTest{addressId=‘H320210816161350000001‘, userId=‘H320210816161029000001‘, addressInfo=‘南京市‘, state=1}]}

多对一:@ManyToOne

  实体注解

@ManyToOne(targetEntity = UserTest.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ADDRESS_USERID", referencedColumnName = "USER_ID", insertable = false, updatable = false)
private UserTest userTest

ADDRESS_USERID这个是ADDRESS_TEST表中的关联字段,这里正好于一对多的相反
USER_ID这是USER_TEST表中的主键

一对一:@OneToOne

  实体注解

@OneToOne(targetEntity = UserTest.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ADDRESS_USERID", referencedColumnName = "USER_ID", insertable = false, updatable = false)
 private UserTest userTest

这里的映射值同多对一的一样

多对多:@ManyToMany

@ManyToMany(targetEntity = UserTest.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "A_U" , joinColumns = { @JoinColumn(name ="ADDRESS_USERID" )}, inverseJoinColumns = { @JoinColumn(name = "USER_ID") })
private List<UserTest> userTest


A_U是中间表
ADDRESS_USERID本表的外键
USER_ID是USER_TEST的主键

  

hibernate实体注解 @OneToMany、@OneToOne、@ManyToOne、@ManyToMany

原文:https://www.cnblogs.com/javabianhua/p/15149214.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!