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