Using hibernate CriteriaQuery for entity which has ID ref to another table entity

1.16K views
0

I have a complex (for me) hibernate query I am trying to figure out and my head just can’t get wrapped around how to do this.

I need to find all Device entities which have an EntityRegistration.userName =~ “foo”.

Entity classes:

@Entity()
@Table
public class Device {
@Basic()
@Column(name = “HostName”)
private String hostName = null;
@Basic()
@Column(name = “RegistrationID”)
private String registrationID = null;
}

@Entity()
@Table
public class EntityRegistration {
@Basic()
@Column(name = “ID”)
private String iD = null;
@Basic()
@Column(name = “UserName”)
private String userName = null;
}

The Device.registrationID maps to EntityRegistration.iD. I do not want to change the table to have EntityRegistration as a OneToMany reference.

Here’s what I’ve tried based on similar queries where there is a OneToMany reference instead of a Basic type like in this case:

CriteriaBuilder builder = context.getBuilder();
Root<Device> root = context.getRoot();
Join<Device,EntityRegistration> joinReg = root.join(“registrationID”);
builder.lower(joinReg.get(“id”)), userName);

I understand why this code doesn’t work, but I can’t figure out how to write the query properly for this case where I have an ID reference.