![](/img/trans.png)
[英]Use JSON_EXTRACT to get value from JSON in Spring JPA Custom Query for custom DTO
[英]How to get JSON List of string from column of mysql table using custom Dto query
我想使用 dto 從表的特定列查詢列表,我的實際查詢非常復雜,包含 3 個連接,我為問題陳述添加了虛擬代碼。
我正面臨這個錯誤:
org.springframework.dao.InvalidDataAccessApiUsageException:無法在 class 上找到合適的構造函數:com.example.demo.persistence.mysql.dto.StudentDto; 嵌套異常是 java.lang.IllegalArgumentException: Could not locate appropriate constructor on class: 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();
}
如果您想直接從數據庫導入為 dto object,則可以使用自定義查詢。
例如 -> @Query("SELECT new com.demo.dtos.userInfoDTO(user.id, user.username) FROM User user")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.