我有一张有几行变量的表。此行中的一个链接到具有更多行的另一个表。
说清楚一点,1个表叫做Connection。变量是:
name, groupname, etc.
组名应链接到名为 ConnectionGroup 的第二个表。变量是:
name, id.
我的想法是按名称查询 ConnectionGroup 表。Connection 和 ConnectionGroup 的抽象类是这样的:
public abstract class Connection_ {
public static volatile SingularAttribute<Connection, String>name;
public static volatile SingularAttribute<Connection, String>host;
public static volatile SetAttribute<Connection, ConnectionGroup>connectionGroups;
}
public abstract class ConnectionGroup_ {
public static volatile SingularAttribute<ConnectionGroup, String> name;
public static volatile SingularAttribute<ConnectionGroup, Long> id;
}
要查询这个,我假设我必须加入这 2 个表,然后只查询它们。这是我尝试过的代码:
@PersistenceContext
private EntityManager em;
public List<Connection> retrieveAll( String groupFilter, int start, int length) {
ServiceUtil.requireAdmin();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Connection> q = cb.createQuery(Connection.class);
Root<Connection> c = q.from(Connection.class);
Join<Connection, ConnectionGroup> join = c.join(Connection_.connectionGroups);
q.select(c);
c.fetch(Connection_.connectionGroups).fetch(ConnectionGroup_.id);
Predicate groupPredicate = cb.equal(
c.get(Connection_.connectionGroups), "%" + groupFilter + "%");
q.where(groupPredicate);
List<Connection> results = em.createQuery(q).setFirstResult(start)
.setMaxResults(length).getResultList();
for (Connection conn : results) {
logger.info( "getconnectionGroups =["+ conn.getConnectionGroups() + "]");
for (ConnectionGroup conngroup : conn.getConnectionGroups()) {
logger.info("connectiongroups = [" + conngroup.getName() + "]");
}
}
}
我尝试过的事情,改变了这一点:
Predicate groupPredicate = cb.equal(
c.get(Connection_.connectionGroups), "%" + groupFilter + "%");
对此:
Predicate groupPredicate = cb.equal(join.get(ConnectionGroup_.name),
"%" + groupFilter + "%");
改变这个:
Join<Connection, ConnectionGroup> join = c
.join(Connection_.connectionGroups);
对此:
Join<Connection, ConnectionGroup> join = c.join("connectionGroups");
当我尝试这些方法时,我不断收到异常Cannot join to attribute of basic type
我还尝试将代码更改为:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Connection> q = cb.createQuery(Connection.class);
Root<Connection> c = q.from(Connection.class);
Join<Connection, ConnectionGroup> join = (Join<Connection, ConnectionGroup>) c.fetch(Connection_.connectionGroups);
q.select(c);
Predicate groupPredicate = cb.equal(join.get(ConnectionGroup_.name), "%" + groupFilter + "%");
q.where(groupPredicate);
List<Connection> results = em.createQuery(q).setFirstResult(start)
.setMaxResults(length).getResultList();
哪个返回异常:
query specified join fetching, but the owner of the fetched association was not present in the select list
我使用这些站点作为参考来编写代码:
JPA CriteriaBuilder 使用获取连接和结果对象
JPA 2 Criteria Fetch Path Navigation
如何从 ConnectionGroup 表中查询名称?我的方法错了吗?