Java JPA“编译查询时出错”当它使用枚举时
以下 JPA 查询无法编译:
@NamedQuery(name = "PSA.findBySourceSystem",
query = "SELECT p FROM PSA p WHERE p.sourceSystem.id = :sourceSystemId")
p.sourceSystem 是以下枚举:
public enum SourceSystem {
FIRST(3, "ABC"), SECOND(9, "DEF"), THIRD(17, "GHI");
private int id;
private String code;
...
}
并映射到 PSA 的 base 类中:
public class PsaBase implements Serializable {
@Column(name = "sourceSystemId")
@Enumerated(EnumType.ORDINAL)
protected SourceSystem sourceSystem;
...
}
如果我将查询中的 p.sourceSystem.id 替换为更良性的东西。
预先感谢您的帮助。
The following JPA query doesn't compile:
@NamedQuery(name = "PSA.findBySourceSystem",
query = "SELECT p FROM PSA p WHERE p.sourceSystem.id = :sourceSystemId")
p.sourceSystem is the following enum:
public enum SourceSystem {
FIRST(3, "ABC"), SECOND(9, "DEF"), THIRD(17, "GHI");
private int id;
private String code;
...
}
and is mapped in PSA's base class:
public class PsaBase implements Serializable {
@Column(name = "sourceSystemId")
@Enumerated(EnumType.ORDINAL)
protected SourceSystem sourceSystem;
...
}
The query compiles and runs fine if I replace p.sourceSystem.id in the query with something more benign.
Thank you in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不应该编译。
您必须先手动解析所需的枚举值,然后再将其作为查询参数传递:
。
。
编辑:
由于
sourceSystem
被注释为@Enumerated(EnumType.ORDINAL)
,它作为相应枚举值的序数存储在数据库中,因此FIRST
存储为0
。 JPA 不直接支持使用枚举值的任意字段来在数据库中标识它。如果您的数据库模式假设是这样,您可以执行以下技巧来将对象的状态与数据库模式分离:It shouldn't compile.
You have to resolve the required enum value manually before passing it as a query parameter:
.
.
EDIT:
Since
sourceSystem
is annotated as@Enumerated(EnumType.ORDINAL)
, it's stored in the database as the ordinal numbers of the corresponding enum values, thereforeFIRST
is stored as0
. JPA doesn't directly support using arbitrary field of the enum value to identify it in the database. If your database schema assumes so, you can do the following trick to decouple state of your object from the database schema: