这是我的实体类。

@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());
    }
}


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


  java.lang.AssertionError:您尝试设置参数值
  使用查询字符串中不存在的userRole名称
  从UsersEntity中选择e在哪里e.userRole =
  “ AppSystemManagerUserRole”。

最佳答案

错误

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"


这样,您应该可以设置参数并且可以正常工作。

关于java - 无法从用户表中获取所有userRole =“ManagerRole”的地方,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34966550/

10-10 20:13