gpt4 book ai didi

java - JPA 和 Hibernate 缺少 INNER JOIN ON 子句

转载 作者:行者123 更新时间:2023-11-30 02:04:04 25 4
gpt4 key购买 nike

我试图找出我在 JPA/Hibernate 方面做错了什么。

我有一个包含两个表的数据库:banner 和bannerlinks。

 banner
+-------------------------------------------+
| id | logo | studyId | textColor | bgColor |
+-------------------------------------------+
| 1 | xx | 17 | green | red |
+-------------------------------------------+

bannerlink
+----------------------------------------+
| id | bannerId| label | text | image |
+----------------------------------------+
| 1 | 1 | About| Abt..| xxx |
+----------------------------------------+
| 2 | 1 | Beta | Bet..| xxx |
+----------------------------------------+
| 2 | 1 | Cont | Ctc..| xxx |
+----------------------------------------+

以及每个的实体类

@Entity
@Table(name="bannerlink")
public class BannerLink{
@Id
@GeneratedValue
private int id;
private String label;

@ManyToOne
@JoinColumn(name = "bannerId")
private Banner banner;
...
}


@Entity
@Table(name = "banner")
public class Banner {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String logo;
private String textColor;
private String backgroundColor;
private int studyId;

@OneToMany(
mappedBy = "banner",
cascade = CascadeType.ALL,
fetch=FetchType.LAZY,
targetEntity = BannerLink.class
)
private List<BannerLink> links;

public Banner() {
}
...
}

我还定义了一个 DAO。

public interface BannerDAO extends JpaRepository<Banner, Integer> {

@Query("select distinct banner FROM Banner banner join BannerLink bl where banner.studyId = :studyId")
Banner getBannerByStudyId(@Param("studyId") int studyId);
}

但是,当我运行 DAO 方法 getBannerByStudyId 时,出现异常 “com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的 SQL 语法有错误;请检查与您的 MariaDB 服务器版本相对应的手册,以了解在第 1 行的“wherebanner0_.studyId=17”附近使用的正确语法”

打印 Hibernate 生成的 RAW SQL 显示 INNER JOIN ON 子句中缺少参数。

 Hibernate: 
select
distinct banner0_.id as id1_0_,
banner0_.backgroundColor as backgrou2_0_,
banner0_.logo as logo3_0_,
banner0_.studyId as studyId4_0_,
banner0_.textColor as textColo5_0_
from
banner banner0_
inner join
bannerlink bannerlink1_
on
where
banner0_.studyId=?

知道我做错了什么吗?

最佳答案

您的查询有误。正确的查询是 >

"select distinct banner FROM Banner banner fetch join banner.links where banner.studyId = :studyId"

我理解你的问题的方式是,你想要获取一个 StudyId 的所有横幅及其相应的链接。如果我错了请纠正我。上面的查询正在完成这项工作。

关于java - JPA 和 Hibernate 缺少 INNER JOIN ON 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51865256/

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