【问题标题】:How to get List<String> inside of a POJO with MyBatis Mapper?如何使用 MyBatis Mapper 在 POJO 中获取 List<String>?
【发布时间】:2021-06-09 04:14:20
【问题描述】:

我的目标是使用 'UsersMapper' MyBatis Mapper 填充 UserDto POJO。

public class UserDto {
  private String username;
  private String password;
  private List<String> authorities;

  public String getUsername() {
    return username;
  }

  public String getPassword() {
    return password;
  }

  public Set<SimpleGrantedAuthority> getAuthorities() {
    return authorities.stream()
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toSet());
  }
}
@Mapper
public interface UsersMapper {
  @Select("SELECT users.username, users.password, role_authorities.authority " +
          "FROM users " +
          "JOIN role_members ON role_members.username = users.username " +
          "AND users.username=#{username} " +
          "JOIN role_authorities ON role_authorities.role_uuid = role_members.role_uuid")
  Optional<UserDto> getUsers(String username);
}

这就是我直接运行 SQL 语句时的样子。

我的预期结果是:MyBatis 成功填充UserDto POJO。

我的实际结果是我遇到了异常

org.springframework.security.authentication.InternalAuthenticationServiceException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3

【问题讨论】:

标签: java mysql spring spring-boot mybatis


【解决方案1】:

此 POJO 有一个类型为 List 的字段。 @Select 还不够,你有两种方法可以解决这个问题:

  1. 添加@Results声明此查询返回的所有字段,然后使用@Resultmany属性链接另一个子查询。
  2. 通过 XML,在您的“ResultMap”XML 标记中使用 &lt;Collection&gt; 标记。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2012-06-08
    • 2021-07-15
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多