英文:
JPA Query for @JoinTable
问题
场景:
我有两个实体,用户(User)和程序(Program)。
@Entity
@Table(name = "user")
public class UserEntity implements Serializable {
@Id
public Long id;
public String firstName;
public String email;
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(
name = "user_program",
joinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "id")
},
inverseJoinColumns = {
@JoinColumn(name = "program_id", referencedColumnName = "id")
}
)
public ProgramEntity program;
}
JPQL:
SELECT
Program.name,
COUNT(user.id) AS user_count
FROM UserEntity AS user
INNER JOIN ProgramEntity AS program on ________ GROUP BY Program.name
我尝试获取每个程序中的用户数量,但由于JoinTable
(中间表)不是实体,所以无法得到结果。有人能提供一个连接联接表的JPQL查询吗?
英文:
Scenario:
I have two entities User and Program
@Entity
@Table(name = "user")
public class UserEntity implements Serializable{
@Id
public Long id;
public String firstName;
public String email;
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(
name = "user_program",
joinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "id")
},
inverseJoinColumns = {
@JoinColumn(name = "program_id", referencedColumnName = "id")
}
)
public ProgramEntity program;
}
JPQL:
SELECT
Program.name,
COUNT(user.id) AS user_count
FROM UserEntity AS user
INNER JOIN ProgramEntity AS program on ________ GROUP BY Program.name
I tried to get the number of users in each program but I couldn't get the result due to the JoinTable
(intermediate table) is not an entity. Can anyone suggest a JPQ to connect the join table?
答案1
得分: 0
你可以使用实体对象进行连接,不必使用 'ON'。对于你的示例,
SELECT prg.name, COUNT(user.id) AS user_count FROM UserEntity AS user INNER JOIN user.program AS prg GROUP BY prg.name
英文:
You can join using the entity object, 'ON' is not necessary. For you example,
SELECT prg.name, COUNT(user.id) AS user_count FROM UserEntity AS user INNER JOIN user.program AS prg GROUP BY prg.name
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论