【问题标题】:How to get JSON List of string from column of mysql table using custom Dto query如何使用自定义 Dto 查询从 mysql 表的列中获取字符串的 JSON 列表
【发布时间】:2022-11-24 19:07:12
【问题描述】:

我想使用 dto 从表的特定列查询列表,我的实际查询非常复杂,包含 3 个连接,我为问题陈述添加了虚拟代码。

我正面临这个错误:

org.springframework.dao.InvalidDataAccessApiUsageException:无法在类上找到合适的构造函数:com.example.demo.persistence.mysql.dto.StudentDto;嵌套异常是 java.lang.IllegalArgumentException:无法在类上找到适当的构造函数:com.example.demo.persistence.mysql.dto.StudentDto

Students.java

@SqlResultSetMapping(name = "StudentMapping", classes = {
        @ConstructorResult(targetClass = StudentDto.class, columns = {
                @ColumnResult(name = "friendList", type = List.class)})})

@Data
@Table(name = "student")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "name", nullable = false, length = 100)
    private String name;

    @Type(type = "json")
    @Column(name = "friend_list", columnDefinition = "json")
    @Builder.Default
    private List<String> friendsName = new ArrayList<>();
}

StudentDto.java

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StudentDto implements Serializable {

    @Type(type = "json")
    @Column(name = "friend_list", columnDefinition = "json")
    List<String> friends;
}

StudentsCustomRepository.java

public StudentsDto fetchStudentFriends(Long id) {
        String rawQuery = String.format(
                "select friend_list as friends from student where id = '%s';",
                id);
        Query query = entityManager.createNativeQuery(rawQuery, "StudentMapping");
        return (StudentDto) query.getResultList();
    }

【问题讨论】:

    标签: java mysql hibernate repository dto


    【解决方案1】:

    如果您想直接从数据库导入为 dto 对象,则可以使用自定义查询。

    例如 -> @Query("SELECT new com.demo.dtos.userInfoDTO(user.id, user.username) FROM User user")

    【讨论】:

      猜你喜欢
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 2022-07-06
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多