sstoeferle
sstoeferle

Reputation: 37

How to query @ElementCollection HashMap

I have an entity with different fields:

@Entity
public class TestEntity {

    private int id;
    private String name;
    private String description;

    @ElementCollection
    private Map<String, String> parameter = new HashMap<>();
}

The resulting tables are the following: TestEntity(id, name, description) TestEntity_parameter(TestEntity_id, parameter, parameter_KEY)

Now I want to create a named query for this TestEntity that checks if there exists a parameter_KEY of value "test" and with a parameter :parameter.

I tried something like this:

select te from TestEntity te join TestEntity_parameter tep where tep.parameter_KEY = test AND tep.parameter = :parameter

But when I try to deploy, I get an error.

I'm relatively new to hibernate and java ee. Maybe my approach is wrong but I did not find anything how to access the fields of a map with a named query since it creates a new table for that map. So i thought that I need to join those tables.

Hope you guys can help me :) Thanks a lot :)

Greetings Simon

Upvotes: 2

Views: 2934

Answers (1)

Pallav Jha
Pallav Jha

Reputation: 3619

You could use the below query.

SELECT te FROM TestEntity te INNER JOIN te.parameter p WHERE KEY(p) = :YOUR_KEY 
AND VALUE(p) = :YOUR_VALUE

Upvotes: 6

Related Questions