@Data
@Entity
@Table(name = "member")
public class MemberEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany
@JoinColumn(name = "memberId")
private List<PhoneEntity> phoneEntities;
}
@Data
@Entity
@Table(name = "phone")
public class PhoneEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private Integer memberId;
}
@Repository
public interface MemberRepository extends JpaRepository<MemberEntity, Integer> {
@Query("select m from MemberEntity m join fetch m.phoneEntities where m.id=?1")
MemberEntity findByIdWithPhone(Integer id);
}
创建从Member
到Phone
的OneToMany关系
im试图使用Member
查询选择Phone
与@Query("select m from MemberEntity m join fetch m.phoneEntities where m.id=?1")
提取联接
此查询的创建方式类似于在my-sql查询下
SELECT
memberenti0_.id as id1_0_0_,
phoneentit1_.id as id1_1_1_,
phoneentit1_.member_id as member_i2_1_1_,
phoneentit1_.member_id as member_i2_1_0__,
phoneentit1_.id as id1_1_0__
from member memberenti0_
inner join phone phoneentit1_ on memberenti0_.id=phoneentit1_.member_id
where memberenti0_.id=?
并且结果MemberEntity
不为空(这意味着插入和内部联接有效!),但MemberEntity#phoneEntities
始终为空
我试图更改List<PhoneEntity>
Collections<PhoneEntity>
Set<PhoneEntity>
的所有集合类型无效。
我怀疑在生成的查询中,“电话”表中的列调用两次(member_i2_1_1_,member_i2_1_0__),但我不知道为什么。
答案 0 :(得分:1)
您必须将映射更正为:
@Data
@Entity
@Table(name = "member")
public class MemberEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany(
mappedBy = "member"
)
private List<PhoneEntity> phoneEntities;
}
@Data
@Entity
@Table(name = "phone")
public class PhoneEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY) // Or Eager
@JoinColumn(name = "member_id")
private MemberEntity member;
}
并且无需在查询中指定连接:
@Query("select m from MemberEntity m where m.id=?1")