无法从users表中获取userRole =“ManagerRole”的所有位置

时间:2016-01-23 17:29:23

标签: java jpql named-query

这是我的实体类。

@NamedQueries({ @NamedQuery(name = UsersEntity.NAMED_QUERY_SELECT_ALL_BY_MANAGER_ROLE, 
                    query = "SELECT e FROM " + UsersEntity.ENTITY_NAME + " e WHERE e." + 
                                    UsersEntity.FIELD_NAME_USER_ROLE + " = '" +
                                    UsersVO.USER_ROLE + "'") })

@Column(name = "USER_ROLE", nullable = false, length = 30)
    private String userRole;
    public static final String FIELD_NAME_USER_ROLE = "userRole";

这是我执行查询的java类

@GET
@Path("/userrole")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public UsersListVO getUsers(@QueryParam("userRole") String userRole) {
 // public UsersListVO getUsers(){
    System.out.println(">>>>>here");
    UsersListVO usersListVO = new UsersListVO();
    try {
        List<UsersEntity> usersEntityList = em.createNamedQuery(UsersEntity.NAMED_QUERY_SELECT_ALL_BY_MANAGER_ROLE, UsersEntity.class).setParameter(UsersEntity.FIELD_NAME_USER_ROLE, userRole).getResultList();

测试用例是: -

@Test
public void testGetUsers() {
    System.out.println("Start test ");
    UsersListVO usersListVO = baseWebTarget.path("userrole").queryParam("userRole", "AppSystemManagerUserRole").request(MediaType.APPLICATION_JSON).get(UsersListVO.class);
    if (usersListVO.getStatusType().equals(StatusTypeVO.FAILURE)) {
        Assert.fail(usersListVO.getMessage());
    } else {
        System.out.println(usersListVO.getMessage());        
    }
}

我想从users表中获取其角色为managerRole的所有管理器。但是在我的jdeveloper中执行测试用例时出错。我得到的错误是

  

java.lang.AssertionError:您试图设置参数值   使用查询字符串中不存在的userRole名称   SELECT e FROM UsersEntity e WHERE e.userRole =   'AppSystemManagerUserRole'。

1 个答案:

答案 0 :(得分:0)

错误

java.lang.AssertionError: You have attempted to set a parameter value using a name of userRole that does not exist in the query string SELECT e FROM UsersEntity e WHERE e.userRole = 'AppSystemManagerUserRole'表示您正在尝试设置一个在您的命名查询中不存在的参数。

您的命名查询:

query = "SELECT e FROM " + UsersEntity.ENTITY_NAME + " e WHERE e." + 
 UsersEntity.FIELD_NAME_USER_ROLE + " = '" + UsersVO.USER_ROLE + "'"
字符串连接后

导致:

query = "SELECT e FROM UsersEntity e WHERE e.userRole = 'AppSystemManagerUserRole'"

如您所见,您可以设置名称参数。当您尝试调用setParameter(UsersEntity.FIELD_NAME_USER_ROLE, userRole)时,它会抛出异常。

您需要在命名查询中引入如下所示的命名参数,以便稍后在代码中进行设置。

query = "SELECT e FROM " + UsersEntity.ENTITY_NAME + " e WHERE e." + 
 UsersEntity.FIELD_NAME_USER_ROLE + " = :" + UsersEntity.FIELD_NAME_USER_ROLE

会导致

query = "SELECT e FROM UsersEntity e WHERE e.userRole = :userRole"

有了这个,您应该能够设置参数并且应该可以工作。