【问题标题】:String Builder Enum checking字符串生成器枚举检查
【发布时间】:2023-03-04 00:06:01
【问题描述】:

我在数据库中有一个包含字段的集合表:

published,name,descrption and collection_type.

而这个collection_type可以是三个不同的字符串值:Collection,Trend,Occasion

通过这个工作显示整个元素。

public List<Collection> list() {
   QueryParams queryParams = new QueryParams();
   queryParams.setWhere("published = true");
   return list(queryParams);
}

但显示特定元素,例如场合失败。如何修复代码以显示元素?

public List<Collection> occasions() {
    QueryParams queryParams = new QueryParams();
    final StringBuilder sb = new StringBuilder();
    sb.append("published = true ");
    sb.append("AND collection_type = '");
    sb.append("CollectionType.OCCASION.getName()'");
    queryParams.setWhere(sb.toString());       
    return list(queryParams);
}        

public enum CollectionType {           
    COLLECTION("COLLECTION"), TREND("TREND"), OCCASION("OCCASION");          
    private String name;          
    private CollectionType(String name) {
        this.name = name;
    }         
    public String getName() {
        return name;
    }           
}

【问题讨论】:

  • 我不能回答你的问题,因为我不确定你在做什么,但我知道Enum 已经有一个方法name,这正是你的getName方法可以。您只需要public enum CollectionType { COLLECTION, TREND, OCCASION }
  • 当你说sb.append("CollectionType.OCCASION.getName()'");时,你的意思是sb.append(CollectionType.OCCASION.getName()); sb.append("'")吗?或sb.append("OCCASION'");
  • 我有数据库中的元素列表。 db 中的这个表包含 collection_type(string)、name、description 等。我想显示 collection_type 例如 = "OCCASION"; 的元素
  • “如何修复错误”请说明错误是什么。
  • 没有错误。对不起,我今天有点累......我的意思是那个查询不起作用。使用此方法在现场没有输出。列出 场合()

标签: java sql hibernate jakarta-ee enums


【解决方案1】:

假设问题在于,您没有设置 ENUM 的名称,而是设置了“CollectionType.OCCASION.getName()'”字符串。尝试将您的代码更改为:

public List<Collection> occasions() {
    QueryParams queryParams = new QueryParams();
    final StringBuilder sb = new StringBuilder();
    sb.append("published = true ");
    sb.append("AND collection_type = '");
    sb.append(CollectionType.OCCASION.getName());
    sb.append("'");
    queryParams.setWhere(sb.toString());

    return list(queryParams);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多