【问题标题】:Spring data JPA/hibernate query over java.util.Map keys?对 java.util.Map 键的 Spring 数据 JPA/hibernate 查询?
【发布时间】:2021-08-23 13:45:56
【问题描述】:

我正在构建一个本地化的应用程序。有 4 个实体使用这个可本地化的系统,我为此使用了 java.util.Maps,例如:

public class ProductDAO extends AbstractDAO {

    private static final long serialVersionUID = 2036153197095739149L;

    @ElementCollection
    @MapKeyColumn(name = "lang")
    @Column(name = "title")
    @CollectionTable(name = "product_title", joinColumns = @JoinColumn(name = "product_id"), indexes = @Index(columnList = "lang", unique = true))
    private Map<String, String> title;

    @ElementCollection
    @MapKeyColumn(name = "lang")
    @Column(name = "description")
    @CollectionTable(name = "product_description", joinColumns = @JoinColumn(name = "product_id"), indexes = @Index(columnList = "lang", unique = true))
    private Map<String, String> description;

    @CollectionTable(name = "topics")
    @ElementCollection(fetch = FetchType.EAGER)
    private Set<String> topics;
    private float price;
}

如何在 spring 中生成一个查询(很确定我不能使用自动生成的,我必须使用@Query),它为我提供了具有特定本地化的实体?例如我有这个类的投影:

public class ProductProjection {

    private String title;
    private String description;
    private Set<String> topics;
    private float price;
}

我的目标是给定 id(在第一类的 AbstractDAO 扩展中)和语言,例如英语,我可以使查询工作:

@Query("some query i have no idea how to make here")
Optional<ProductProjection> findByIdAndLanguage(String id, String lang);

【问题讨论】:

    标签: java mysql spring spring-data


    【解决方案1】:

    我不知道是否有任何兴趣,但我开发了一个解决方案:

    @Query("select new com.example.demo.ProductProj(p.id, p.version, p.price, VALUE(l).name, VALUE(l).description) from Product p join p.localizations as l where (VALUE(l).name) like %:name% and (KEY(l)) = :lang")
    

    基本上是把基本产品stull放在投影中,然后在查询匹配时加上value(l)的属性。您应该查询键以确保只有一个值。如果您需要更多值,可以将 Value(l) 直接作为集合传递

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 2012-05-04
      • 2021-02-17
      • 1970-01-01
      • 2018-03-17
      • 2020-07-23
      相关资源
      最近更新 更多