user2146141
user2146141

Reputation: 155

how to query embedded object in Hibernate?

I have classes A, B

class A{
@Embedded
private B objB; 
}

@Embeddable 
class B{
Integer x;
Integer y;
float z;
}

Now I have a bunch of class A objs Set, I want to query the database, so that rows contain same x and y in Class B (z is not important in comparison in this case) should be selected, how do I achieve that?

It's like "In" in SQL, but since I am comparing embedded objects, how should I do with it ? Many thanks!!

Upvotes: 0

Views: 8996

Answers (1)

Bruno Manzo
Bruno Manzo

Reputation: 374

Given the classes:

public class RandomEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Embedded
    private EmbeddableEntity embedded;
}

and

@Embeddable
public class EmbeddableEntity {
    private Long valueA;
    private Long valueB;
}

You can query it like:

session.createQuery( "select a from RandomEntity a where a.embedded.valueA=:value" ).setParameter( "value", 1L ).list();

Hibernate: select randomenti0_.id as id1_2_, randomenti0_.valueA as valueA2_2_, randomenti0_.valueB as valueB3_2_ from RandomEntity randomenti0_ where randomenti0_.valueA=?

or:

session.createQuery( "select a from RandomEntity a where a.embedded.valueA in (:value)" ).setParameterList( "value", Arrays.asList( 1L, 2L ) ).list();

Hibernate: select randomenti0_.id as id1_2_, randomenti0_.valueA as valueA2_2_, randomenti0_.valueB as valueB3_2_ from RandomEntity randomenti0_ where randomenti0_.valueA in (?)

Upvotes: 3

Related Questions