我使用 Micronaut Data 和 JPA,有两个实体。第一个实体是 Recipe
:
@Entity
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@ManyToOne
private Category category;
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private Set<Step> steps;
// + other fields, getters and setters
}
第二个是
ParseError
,它与Recipe
有关。@Entity
@Table(name = "parse_error")
public class ParseError implements Serializable {
@Id
@ManyToOne(fetch = FetchType.LAZY)
private Recipe recipe;
@Id
@Enumerated(EnumType.ORDINAL)
@Column(name = "problem_area")
private ProblemArea problemArea;
private String message;
// + other fields, getters and setters
}
现在我希望在API中提供DTO,并且使用
ParseError
属性而不是整个Recipe
实体,因为它包含了ManyToOne和OneToMany关系,在这种情况下是不必要的。所以我为此创建了投影DTO。@Introspected
public class ParseErrorDto {
private Integer recipeId;
private String recipeName;
private ParseError.ProblemArea problemArea;
private String message;
// + getters and setters
}
并将listAll()
方法添加到ParseErrorRepository
中:
@Repository
public interface ParseErrorRepository extends CrudRepository<ParseError, Integer> {
List<ParseErrorDto> listAll();
}
但是似乎Micronaut Data无法从嵌套实体中投影属性,或者我在DTO或存储库方法中错过了某些东西:
ParseErrorRepository.java:22:错误:无法实现仓库方法:ParseErrorRepository.listAll()。实体中不存在属性recipeId:ParseError
我还尝试创建RecipeDto
:
@Introspected
public class RecipeDto {
private Integer id;
private String name;
// + getters and setters
}
并相应更新ParseErrorDto
:
@Introspected
public class ParseErrorDto {
private RecipeDto recipe;
private ParseError.ProblemArea problemArea;
private String message;
// + getters and setters
}
再次失败:
ParseErrorRepository.java:22: 错误:无法实现Repository方法:ParseErrorRepository.listAll()。类型为[RecipeDto]的属性[recipe]与实体中声明的等效属性不兼容:ParseError。
Micronaut Data能否通过DTO投影来处理此用例?如果不能,则是否有其他方式可以在Micronaut Data中解决此问题?