gpt4 book ai didi

java - 如何使用 Hibernate 填充实体的两个字段?

转载 作者:行者123 更新时间:2023-12-04 07:50:08 26 4
gpt4 key购买 nike

我正在构建一个 API 来返回两个字段:

{
currentPoints: 325,
badgeName: "Some Badge"
}
但是,我在使用 hibernate 来填充这两个字段时遇到了麻烦。我做了两次尝试,都抛出错误。这两个错误都可以在它们各自的存储库文件中找到。在第二次尝试中,我使用了 native=true并且能够使用 SELECT * 让它工作.但是,我试图只填充和返回实体的两个字段。
我想到的一个解决方案是使用带有 SELECT * 的第二种方法并创建另一个名为 response 的包。与 CurrentInfoResponse类,然后返回该类。但是,我想看看是否有办法使用我现有的模型来避免这种情况。
可能的解决方案:
@Getter
@AllArgsConstructor
public class CurrentInfoResponse{
private Integer currentPoints;
private String badgeName
}
封装结构:
Package Structure
Controller .java:
@GetMapping("/current-badge/{userId}")
public CurrentBadgeInfoModel getCurrentBadge(@PathVariable Integer userId){
return currentBadgeInfoService.getCurrentBadge(userId);
}
ServiceImpl.java:
@Override
public CurrentBadgeInfoModel getCurrentBadge(Integer userId){
return currentBadgeInfoRepository.getCurrentBadge(userId);
}
CurrentBadgeInfoModel.java:
@Getter
@Entity
@Table(name = "user_current_badge_info")
public class CurrentBadgeInfoModel {

@Id
@Column(name = "user_current_info_id")
private Integer userCurrentBadgeInfo;

@Column(name = "user_id")
private Integer userId;

@Column(name = "current_points")
private Integer currentPoints;

@ManyToOne
@JoinColumn(name = "badge_id")
private BadgeModel badgeModel;
}
徽章模型.java
@Getter
@Entity
@Table(name = "badge_info")
public class BadgeModel {
@Id
@JoinColumn(name= "badge_id")
private Integer badgeId;

@Column(name = "badge_name")
private String badgeName;
}
Repository.java - 尝试 1:
@Repository
public interface CurrentBadgeInfoRepository extends JpaRepository<CurrentBadgeInfoModel, Integer> {

@Query("SELECT cbim.currentPoints, cbim.badgeModel.badgeName FROM CurrentBadgeInfoModel cbim JOIN
cbim.badgeModel WHERE cbim.userId=?1")
CurrentBadgeInfoModel getCurrentBadge(Integer userId);
}

//Error: No converter found capable of converting from type [java.lang.Integer] to type [com.timelogger.model.CurrentBadgeInfoModel]
Repository.java - 尝试 2:
@Repository
public interface CurrentBadgeInfoRepository extends JpaRepository<CurrentBadgeInfoModel, Integer> {

@Query(value = "SELECT current_points, badge_name FROM user_current_badge_info ucbi JOIN badge_info bi ON ucbi.badge_id=bi.badge_id WHERE user_id=?1", nativeQuery = true)
CurrentBadgeInfoModel getCurrentBadge(Integer userId);
}

//Error: Column 'user_current_info_id' not found

最佳答案

使用 SELECT clause HQL 应该在这里帮助你。
如果你没有那个构造函数,你可以添加它

@Query("SELECT new CurrentBadgeInfoModel(cbim.currentPoints, cbim.badgeModel.badgeName) FROM CurrentBadgeInfoModel cbim JOIN 
cbim.badgeModel WHERE cbim.userId=?1")
注意 new CurrentBadgeInfoModel(cbim.currentPoints, cbim.badgeModel.badgeName)的用法

关于java - 如何使用 Hibernate 填充实体的两个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67029166/

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