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 = "AU_TEST" , joinColumns = { @JoinColumn(name ="ADDRESS_ID" )}, inverseJoinColumns = { @JoinColumn(name = "USER_ID") }) private List<UserTest> userTest AU_TEST是中间表 joinColumns 定义中间表与ADDRESS_TEST表的外键关系 中间表AU_TEST的ADDRESS_ID列是ADDDRESS_TEST表的主键列对应的外键列,inverseJoinColumns 属性定义了中间表与另外一端(USER_TEST)的外键关系。