Ral*_*lph 4 java jpa criteria-api
我正在与以下问题争吵两天,希望你能给我一个正确的方向.我在研究过程中发现的教程和示例总是只显示如何在标准api中轻松加入工作.首先,我有两个班:
@Entity
public class Offer {
private String name;
@ManyToOne private Location location;
private String tags;
}
Run Code Online (Sandbox Code Playgroud)
和
@Entity
public class Location {
private String name;
private string tags;
}
Run Code Online (Sandbox Code Playgroud)
因为我需要避免循环引用,所以这些类之间的连接只是单向的.这个类中有很多其他属性,我想根据我的搜索过滤器构建动态查询.以下SQL语句将解释我喜欢做什么:
SELECT l
FROM Offer o
JOIN o.location l
WHERE o.tags LIKE :sometag AND l.tags LIKE :someothertag
Run Code Online (Sandbox Code Playgroud)
用标准api实现这个后,我得到了这段代码:
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Location> criteriaQuery = criteriaBuilder.createQuery(Location.class);
criteriaQuery = criteriaQuery.distinct(true);
Join location;
ArrayList<Predicate> whereList = new ArrayList<Predicate>();
// if filter by offer, use offer as main table and join location table
if (filter.getOfferTags() != null) {
Root<Offer> offer = criteriaQuery.from(Offer.class);
location = offer.join("location");
// limit to offering tags
Path<String> tagPath = offer.get("tags");
for (String tag : filter.getOfferTags()) {
Predicate whereTag = criteriaBuilder.like(tagPath, "%" + tag + "%");
whereList.add(whereTag);
}
} else {
// else use location table as base
location = (Join<Location, Location>) criteriaQuery.from(Location.class);
}
Run Code Online (Sandbox Code Playgroud)
但是如果我执行此操作,我会从H2数据库中收到以下错误消息:
Column "LOCATION.ID" not found; SQL statement:
SELECT DISTINCT LOCATION.ID, LOCATION.NAME
FROM OFFER t0, LOCATION t1
WHERE t0.TAGS LIKE ? AND t1.TAGS LIKE ?
Run Code Online (Sandbox Code Playgroud)
数据库期望t1.ID和t1.NAME在select子句中而不是LOCATION.ID和LOCATION.NAME.如何告诉JPA创建"正确"的请求?我在代码中遗漏了什么吗?
我正在使用带有Eclipse Link和H2数据库的Glassfish 3.1.1.
| 归档时间: |
|
| 查看次数: |
7705 次 |
| 最近记录: |