简体   繁体   中英

Difficulty converting this hibernate Criteria to JPA Criteria, issues with multiple associated entities

The hibernate criteria query I'm trying to change looks like this

Criteria crit = 
session.createCriteria(device.class)
.createCriteria("deviceConfigurationTemplate")
.createCriteria("deviceModel");

I want to simply change this to use JPA CriteriaQueries instead. The issue I'm having is how javax.persistence to create a query with multiple assoicated entities passed in as strings. I wanted to use JPA root criteria and multiselect them using the criteriaQuery like this

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Device> cq = cb.createQuery(Device.class);
Root<DeviceModel> model = cq.from(DeviceModel.class);
Root<"deviceConfigurationTemplate"> model2 = 
cq.from("deviceConfigurationTemplate");
cq.multiselect(model);

The issue here is you can't pass in a string as a parameter to the root object. I'm not sure how else to go about creating a query like this.

Why would you try to pass a string as the type parameter? Once you join along an association, the resulting Join or Path should be parameterized with the association's target type.

Is the query supposed to be equivalent to SELECT d.deviceConfigurationTemplate.deviceModel FROM Device d ? If so, the equivalent Criteria query would be:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<DeviceModel> criteria = cb.createQuery(DeviceModel.class);
Path<DeviceModel> model = criteria.from(Device.class).get("deviceConfigurationTemplate").get("model");
criteria.select(model);

With typing made a bit more explicit:

CriteriaQuery<DeviceModel> criteria = cb.createQuery(DeviceModel.class);
Root<Device> from = criteria.from(Device.class);
Path<ConfigurationTemplate> configTemplate = from.get("template");
Path<DeviceModel> model = configTemplate.get("model");
criteria.select(model);

You could also use from.join() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM