gpt4 book ai didi

java - 如何正确实现涉及两个表之间 JOIN 的 Spring Data JPA 命名查询?

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:21 25 4
gpt4 key购买 nike

我正在使用 Spring Data JPA 开发 Spring 应用程序。我实现了命名查询方法来实现我的查询。我在尝试实现涉及 2 个表\实体类之间的联接的命名查询时遇到一些困难。

所以我有这两个实体类:

1) Room 代表住宿的房间:

@Entity
@Table(name = "room")
public class Room implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@ManyToOne
@JoinColumn(name = "id_accomodation_fk", nullable = false)
private Accomodation accomodation;

@ManyToOne
@JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;

@Column(name = "room_number")
private String number;

@Column(name = "room_name")
private String name;

@Column(name = "room_description")
@Type(type="text")
private String description;

@Column(name = "max_people")
private Integer maxPeople;

@Column(name = "is_enabled")
private Boolean isEnabled;

// CONSTRUCTOR, GETTER AND SETTER METHODS
}

正如你所看到的,这个类包含这个字段:

@ManyToOne
@JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;

将许多 Room 实例链接到 RoomTipology 实例。

2)然后我有RoomTipology实体类:

@Entity
@Table(name = "room_tipology")
public class RoomTipology implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "tipology_name")
private String name;

@Column(name = "tipology_description")
private String description;

@Column(name = "time_stamp")
private Date timeStamp;

@OneToMany(mappedBy = "roomTipology")
private List<Room> rooms;

@OneToOne(mappedBy = "roomTipology")
private RoomRate roomRate;

// CONSTRUCTOR, GETTER AND SETTER METHODS
}

然后我有 RoomTipology 实体类的存储库类,如下所示:

@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface RoomTipologyDAO extends JpaRepository<RoomTipology, Long> {

RoomTipology findByRoomTipology_Room(Room room);

}

我已经尝试过这种方式,但它不起作用,并且收到以下错误消息:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roomTipologyDAO': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property roomTipology found for type RoomTipology!

我想从Room开始检索相关的RoomTipology实例。基本上我想将此 SQL 查询转换为 Spring Data JPA 命名查询:

SELECT * 
FROM `room_tipology` rt
INNER JOIN room r
ON rt.id = r.id_room_tipology_fk
WHERE r.id = 7

其中 r.id 是 Room 实体的 id 字段的值。

我知道,如果我已经有一个 Room 对象,我可以通过以下方式获取此信息:

room.getRoomTipology()

但有时我只有 Room 实例的 ID,我想直接检索相关的 RoomTipology 对象。

如何使用命名查询来做到这一点?

最佳答案

按照您认为最好的方式命名您的方法,传递 roomId 而不是房间,因为那是您的实际搜索参数,并使用注释该方法

@Query("select t from Room r join r.roomTypology t where r = :roomId")

关于java - 如何正确实现涉及两个表之间 JOIN 的 Spring Data JPA 命名查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40876281/

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