CrudRepository-如何通过映射键和值查找对象

时间:2020-04-10 11:06:51

标签: java hibernate spring-boot hashmap repository

我在使用CrudRepository“选择”值时遇到问题。

例如:

我有Client类:

@Entity
public class Client {

@Id
private Long id;

@ManyToMany
Map<AttributeType, Attribute> map = new HashMap<>();
}

AttributeType类:

@Entity
public class AttributeType {
    @Id
    private Long id;

    @Column(unique = true)
    private String name;
}

“属性”是抽象实体,具有字符串和布尔值的“子类型”(AttributeBoolean,AttributeString),并且都具有两个字段IDVAL(取决于String val或Boolean val在“ className”上)。

因此,如果我要选择在地图中具有“ AttributeType”的客户端列表,则可以使用:

public interface ClientRepository extends CrudRepository<Client, Long> {
  @Query("select cli from Client cli where KEY(cli.map) = :attributeType ")
    List<Client> selectByAttributeType(@Param("attributeType ") AttributeType attributeType );
}

但是我对“选择AttributeType等于x而该Attribute等于y的客户端”有疑问。

我正在尝试使用:

@Query("select cli from Client cli \n" +
            "where KEY(cli.map) = :attributeType \n" +
            "and VALUE(cli.map).val = :val")
List<Client> selectByAttributeTypeAndParam(
@Param("attributeType") AttributeType attributeType, @Param("val") String val);

但是会引发异常:Caused by: java.lang.IllegalArgumentException: Parameter value [xxxxxxxx] did not match expected type [java.lang.Boolean (n/a)]

因此,问题是: 您有什么想法,我该如何选择每个客户,其中: AttributeType = x 和map中的值(针对该AttributeType)= y?

//编辑... 为了更好地了解:

我们遇到这样的情况:

AttributeType at1 =...  //does not matter what is it
AttributeType at2 =...  //does not matter what is it
AttributeType at3 =...  //does not matter what is it

Client c1 = new Client();
Map<AttributeType, Attribute> map1 = c1.getMap();
map1.put(at1, new AttributeString("123456789");
map1.put(at2, new AttributeBoolean(true);

Client c2 = new Client();
Map<AttributeType, Attribute> map2 = c2.getMap();
map2.put(at1, new AttributeString("111111111");
map2.put(at3, new AttributeBoolean(true);

所以,我想要带有2个参数的CrudRepository函数。

1)AttributeType 2)SomeValue(可以是String或Boolean)

如果此功能如下:

@Query("some query - no idea how to write it")
List<Client> selectByAttributeTypeAndParam(
@Param("attributeType") AttributeType attributeType, @Param("val") String val);

如果我跑步:

List<Client> someList = selectByAttributeTypeAndParam(at1, "12345679");

我希望someList拥有1条记录,即c1

如果我具有布尔搜索的等效功能并且运行:

List<Client> someList = selectByAttributeTypeAndParam(at2, true);

我不希望someList同时拥有c1c2记录。

0 个答案:

没有答案