Member-only story
How to write complex QueryDSL queries with attribute maps
In this article, I’ll show you how to write queries to JPA entities with attribute maps (fields marked with @ElementCollection) using QueryDSL.
Note that this is not a guide on how to structure your entity model. In most cases, you don’t even need a set of arbitrary attributes in your entity. But when you do (due to different reasons — legacy data structures, additional flexibility etc.), then the queries can get really tricky.
Suppose we have the following User entity with a map of arbitrary attributes:
@Entity
public class User implements Serializable { @Id
@GeneratedValue
private Long id; @ElementCollection
@MapKeyColumn(name = "key")
@Column(name = "value")
private Map<String, String> attributes = new HashMap<>(); // getters and setters skipped
}
We create an entity and persist it:
Map<String, String> attributes = new HashMap<>();
attributes.put(“name”, “Mary”);
attributes.put(“birthDate”, “18–10–1983”);
attributes.put(“personalNumber”, “42”);User user = new User();
user.setAttributes(attributes);
entityManager.persist(user);