@JoinTable 的 JPA 查询
JPA Query for @JoinTable
场景:
我有两个实体用户和程序
@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
(中间 table)不是实体,所以无法获取结果。任何人都可以建议一个 JPQ 来连接连接 table?
您可以使用实体对象加入,'ON'不是必需的。例如,
SELECT prg.name, COUNT(user.id) AS user_count FROM UserEntity AS user INNER JOIN user.program AS prg GROUP BY prg.name
场景: 我有两个实体用户和程序
@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
(中间 table)不是实体,所以无法获取结果。任何人都可以建议一个 JPQ 来连接连接 table?
您可以使用实体对象加入,'ON'不是必需的。例如,
SELECT prg.name, COUNT(user.id) AS user_count FROM UserEntity AS user INNER JOIN user.program AS prg GROUP BY prg.name