gpt4 book ai didi

java - Spring jpa @OneToMany 一个方向始终为 null

转载 作者:行者123 更新时间:2023-12-02 10:33:59 24 4
gpt4 key购买 nike

@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 创建 OneToMany 关系至Phone

我正在尝试选择 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__),但我不知道为什么。

最佳答案

您必须将映射更正为:

@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")

关于java - Spring jpa @OneToMany 一个方向始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53433878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com