2014-09-29 87 views
2

我需要通过枚举类型从数据库中获取数据。 我有以下枚举:冬眠通过枚举类型查询

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; 

回答

4

当你设置你的枚举为序数,那么在查询中你应该使用序数。例;

@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()方法是最终的,你可以肯定不能被覆盖。

+0

结果应该取决于接收findByType方法Param类型,你编辑的几分钟前刚刚硬编码VANS型 – user3127896 2014-09-29 19:26:48

+0

:) – 2014-09-29 19:28:38

+0

看起来更好,谢谢=) – user3127896 2014-09-29 19:34:46

4

只是字符串转换为枚举和使用命名查询参数

@Transactional 
public List<Shop> findByType(String type) { 
    ShopType enumType = shopTypeFromString(type); 
    return sessionFactory.getCurrentSession().createQuery("from Shop where type=:p_type") 
     .setParameter("p_type", enumType).list(); 
} 

private ShopType shopTypeFromString(String type) { 
    // You can implement this convertion in your own way 
    return ShopType.valueOf(type); 
} 
+0

我猜这不是很好=) – user3127896 2014-09-29 19:35:39