查询@ElementCollection地图

时间:2018-05-28 09:17:19

标签: java spring jpa spring-data-jpa

我的实体使用数据类型为Map的参数字段。我可以毫无问题地将这些对象保存到DB。但我该如何查询它们呢?

@Entity
public class ActionData {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ElementCollection
    @CollectionTable(name = "parameter")
    private Map<String, String> parameter = new HashMap<>();

    @ManyToOne
    @JoinColumn(name = "work_id", referencedColumnName = "id", nullable = false)
    private Work work;

    @NotBlank
    private String actionName;

    private Instant requestTime;
    private Instant startTime;
    private Instant endTime;

    // ...
}

我用这种方式尝试了一个存储库:

public interface ActionRepository extends CrudRepository<ActionData, Integer> {

    ActionData findFirstByWorkAndActionNameAndParameter(Work work, String actionName, Map<String,String> parameter);

    // ...
}

我尝试使用参数查询特定的ActionData:

Work work1 = new Work("xyz", "title1");

Map<String, String> parameter1 = new HashMap<>();
parameter1.put("key1", "value1");

ActionData actionData = actionRepository.findFirstByWorkAndActionNameAndParameter(work1, "action1", parameter1);

比我得到这个例外:

Caused by: java.lang.IllegalArgumentException: Parameter value [{key1=value1}] did not match expected type [java.lang.String (n/a)]

Spring想要一个String类型,但它是一个Map。为什么它不起作用以及如何使其工作?

Java 8,Spring 5,Spring Boot 2

0 个答案:

没有答案