我需要通过枚举类型从数据库中获取数据。 我有以下枚举:
public enum ShopType {
VANS("VANS"), ATTICUS("ATTICUS"), FAMOUS("FAMOUS")
ShopType(String label) {
this.label = label;
}
private String label;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
在我的 DAO 类中,我有一个方法,它按 jsp
页面上的选定类型返回对象列表。在 jsp
页面上,我发送选定的值,例如 String
,对吗?
我的方法看起来怎么样
@Transactional
public List<Shop> findByType(String type) {
return sessionFactory.getCurrentSession().createQuery("from Shop where type=" + ..... .list();
}
我不知道如何创建正确的查询。我像 tinyint 一样存储在我的数据库中的枚举。
这是一个模型。
@Column(name = "type")
@Enumerated(EnumType.ORDINAL)
private ShopType type;
最佳答案
当您将枚举设置为序数时,那么在查询中您应该使用序数。示例;
@Transactional
public List<Shop> findByType(String type) {
return sessionFactory.getCurrentSession().createQuery("from Shop where type=" + ShopType.valueOf(type).ordinal()).list();
}
如果您更改@Enumerated(EnumType.STRING)
,那么您的查询将如下所示;
@Transactional
public List<Shop> findByType(String type) {
return sessionFactory.getCurrentSession().createQuery("from Shop where type=" + ShopType.valueOf(type).name()).list();
}
ShopType.valueOf(type)
,这仅在字符串类型与枚举名称相同时有效。
此外,如果您的标签与枚举名称相同,则您不需要标签。
ShopType.VANS.name()
等于"VANS"
并且name()
方法是final的,你可以确定不能覆盖。
关于java - 如何使用 JPA 和 Hibernate 使用映射为 ORDINAL 的枚举参数进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26106557/