JPA 计算相关实体而不加入它们
JPA count related entities without joining them
我有两个实体:
@Entity
class X {
@Id
int id;
}
@Entity
class Y {
@Id
int id;
@ManyToOne
@JoinColumn(name = "x_id")
X x;
}
我想计算 y table 中 x_id 的不同值。我试过:
select count(distinct Y.x) from Y;
它有效,但在 sql 中,我加入了 x table,这是 uneccesery:
select count(distinct x.id) from y, x where y.x_id = x.id;
这个连接对我来说是不必要的,而且成本很高。没有原生查询有什么办法可以避免吗?
您可以尝试使用 select count(distinct Y.x.id) from Y
(T.x.id 而不是 Y.x)。我不确定,但智能 JPA 实现应该发现只有 id 是必需的,不会添加连接。
另一种方法是将一个 int 字段添加到 Y,并将只读映射到 x_id 列:
@Entity
class Y {
@Id
int id;
@ManyToOne
@JoinColumn(name = "x_id")
X x;
@Column(name = "x_id", insertable = false, updatable = false, nullable = false)
int xId;
}
而您的查询将只是 select count(distinct Y.xId) from Y
对于 JPA 存储库中的计数,您甚至可以使用:
假设有两个实体:EntityA
和 EntityB
。如果 EntityA
与 EntityB
有任何关系,那么您可以在
中使用计数
@Entity
@Table(name = "entity_a")
public class EntityA {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ea_id")
private Long eaId;
@ManyToOne
@JoinColumn(name = "eb_id")
private EntityB entityB;
...
}
还有一个EntityB
@Entity
@Table(name = "entity_b")
public class EntityB {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "eb_id")
private Long ebId;
...
}
为此,您可以在 EntityA
的 JPARepository
中使用以下方法来获取计数。请记住 _
是存储库中方法签名的 .
的替代品。
int countByEntityB_EbId(long ebId);
我有两个实体:
@Entity
class X {
@Id
int id;
}
@Entity
class Y {
@Id
int id;
@ManyToOne
@JoinColumn(name = "x_id")
X x;
}
我想计算 y table 中 x_id 的不同值。我试过:
select count(distinct Y.x) from Y;
它有效,但在 sql 中,我加入了 x table,这是 uneccesery:
select count(distinct x.id) from y, x where y.x_id = x.id;
这个连接对我来说是不必要的,而且成本很高。没有原生查询有什么办法可以避免吗?
您可以尝试使用 select count(distinct Y.x.id) from Y
(T.x.id 而不是 Y.x)。我不确定,但智能 JPA 实现应该发现只有 id 是必需的,不会添加连接。
另一种方法是将一个 int 字段添加到 Y,并将只读映射到 x_id 列:
@Entity
class Y {
@Id
int id;
@ManyToOne
@JoinColumn(name = "x_id")
X x;
@Column(name = "x_id", insertable = false, updatable = false, nullable = false)
int xId;
}
而您的查询将只是 select count(distinct Y.xId) from Y
对于 JPA 存储库中的计数,您甚至可以使用:
假设有两个实体:EntityA
和 EntityB
。如果 EntityA
与 EntityB
有任何关系,那么您可以在
@Entity
@Table(name = "entity_a")
public class EntityA {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ea_id")
private Long eaId;
@ManyToOne
@JoinColumn(name = "eb_id")
private EntityB entityB;
...
}
还有一个EntityB
@Entity
@Table(name = "entity_b")
public class EntityB {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "eb_id")
private Long ebId;
...
}
为此,您可以在 EntityA
的 JPARepository
中使用以下方法来获取计数。请记住 _
是存储库中方法签名的 .
的替代品。
int countByEntityB_EbId(long ebId);