【发布时间】:2021-06-16 20:06:44
【问题描述】:
我知道该主题中有几篇文章,但我只是找不到使用 Kotlin 数据类的文章。因此,我正在尝试使用 Spring Boot 在 Kotlin 中使用 H2 数据库制作 REST API,并且我也在使用 Postman。我的类的一些属性具有 List 类型。每次我尝试在 Postman 中为这些列表添加一些值然后尝试获取结果时,都会出现以下错误:
我有三个班级:
食谱.kt:
@Entity
data class Recipe(
@Id
@SequenceGenerator(name = RECIPE_SEQUENCE, sequenceName = RECIPE_SEQUENCE, initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0,
val name: String,
var cookTime: String?,
var servings: String?,
var directions: String?,
@OneToMany(cascade = [CascadeType.ALL], mappedBy = "recipe")
@JsonManagedReference
var ingredient: List<Ingredient>?,
@ManyToMany
@JsonManagedReference
@JoinTable(
name = "recipe_category",
joinColumns = [JoinColumn(name = "recipe_id")],
inverseJoinColumns = [JoinColumn(name = "category_id")]
)
var category: List<Category>?,
@Enumerated(value = EnumType.STRING)
var difficulty: Difficulty?
) { companion object { const val RECIPE_SEQUENCE: String = "RECIPE_SEQUENCE" } }
类别.kt
@Entity
data class Category(
@Id
@SequenceGenerator(name = CATEGORY_SEQUENCE, sequenceName = CATEGORY_SEQUENCE, initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
var name: String,
@ManyToMany(mappedBy = "category")
@JsonBackReference
var recipe: List<Recipe>?
) { companion object { const val CATEGORY_SEQUENCE: String = "CATEGORY_SEQUENCE" } }
成分.kt
@Entity
data class Ingredient(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
var description: String?,
var amount: BigDecimal?,
@ManyToOne
@JsonBackReference
var recipe: Recipe?,
var unitOfMeasure: String?
)
RecipeResponse.kt
data class RecipeResponse (var id:Long,
var name:String,
var cookTime:String?,
var servings:String?,
var directions:String?,
var ingredient:List<Ingredient>?,
var category: List<Category>?,
var difficulty: Difficulty?)
RecipeResource.kt
@RestController
@RequestMapping(value = [BASE_RECIPE_URL])
class RecipeResource(private val recipeManagementService: RecipeManagementService)
{
@GetMapping
fun findAll(): ResponseEntity<List<RecipeResponse>> = ResponseEntity.ok(this.recipeManagementService.findAll())
RecipeManagementService.kt
@Service
class RecipeManagementService (@Autowired private val recipeRepository: RecipeRepository,
private val addRecipeRequestTransformer: AddRecipeRequestTransformer) {
fun findAll(): List<RecipeResponse> = this.recipeRepository.findAll().map(Recipe::toRecipeResponse)
【问题讨论】:
标签: json spring-boot kotlin postman h2