org.hibernate.hql.ast.QuerySyntaxException: 无法找到合适的构造函数

org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate constructor

我有 2 个 table 映射到实体 UserGroup

@Entity
@Table(name = "T_COM_USER")
public class User {
    private String userName;
    @Column(name="F_USERNAME", length=60)
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}
@Entity
@Table(name="T_COM_USERGROUP")
public class UserGroup{
    private String groupName;
    @Column(name="F_GROUPNAME", length=60)
    public String getGroupName() {
        return groupName;
    }
    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }
}

一个User可以有很多Group。我需要对它们进行建模,以便在前端的 table 中显示用户及其所有组,如下所示:

+-------+----------------------+
| Users |        Groups        |
+-------+----------------------+
| User1 | Group1,Group2,Group3 |
| User2 | Group1,Group2        |
| User3 | Group2,Group4        |
+-------+----------------------+

所以我创建了这个 DTO:

public class UserGroupsBean {
    private List<String> groupName;
    private String userName;
    public UserGroupsBean(String userName, List<String> groupName) {
        this.userName = userName;
        this.groupName = groupName;
    }
    // Getters
    public List<String> getGroupName() { return groupName; }
    public String getUserName() { return userName; }            
    // Setters
    public void setGroupName(List<String> groupName) { this.groupName = groupName; }
    public void setUserName(String userName) { this.userName = userName;}
}

我使用此查询 return 每个用户的所有组:

String hql = "select new odatabase.service.beans.UserGroupsBean(userName,(select groupName from UserGroup) ) from User";

但是我得到了:

org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [UserGroupsBean]

虽然我有构造函数UserGroupsBean(String userName, List < String > groupName)

这是怎么引起的,我该如何解决?

JPQL 构造函数表达式只支持平面结果,所以你运气不好。您可以使用 SELECT u.userName, g.groupName FROM User u JOIN u.userGroups g 之类的查询,但您必须自己 减少 结果集。

你想做的事Blaze-Persistence Entity Views都能很好地完成。这里有一些示例代码。

@EntityView(User.class)
public interface UserGroupsBean {
    // The id of the user
    @IdMapping("id") int getId();

    String getUserName();

    @Mapping("userGroups.name")
    List<String> getGroupNames();
}

这本质上是一个带有一些元数据的 DTO。这是查询代码:

EntityManager entityManager = // jpa entity manager
CriteriaBuilderFactory cbf = // query builder from Blaze-Persistence
EntityViewManager evm = // manager that can apply entity views to query builders

CriteriaBuilder<User> builder = cbf.create(entityManager, User.class);
List<UserGroupsBean> result = evm.applySetting(
    builder, 
    EntityViewSetting.create(UserGroupsBean.class)
).getResultList();

这将生成类似于此的查询

SELECT u.id, u.userName, g.groupName FROM User u JOIN u.userGroups g

并自动将结果映射到 DTO 中。