使用Spring Boot JPA反序列化JSON类Kotlin的问题



我有一个Rest API与Spring Boot JPA和Kotlin的问题。每次尝试使用POST端点插入新记录时都会抛出错误。

出现的错误日志:

JSON解析错误:不能构造com.lp3bmobi.paintcar_workshop_api.model.VehicleType的实例(尽管至少存在一个Creator):没有int/int参数构造器/工厂方法来反序列化Number value (3)

<<p>VehicleType类/strong>
@Entity
@Table(name="vehicle_types")
@EntityListeners(AuditingEntityListener::class)
@JsonDeserialize
data class VehicleType (
@NotBlank
@Column(name = "type_name")
var typeName: String ?= null
//@JsonProperty("typeName") var typeName: String ?= null
) {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
var id: Long ?= null
//@JsonProperty("id") var id: Long = 0
constructor(id: Long, typeName: String?): this(typeName) {
this.id = id
}
//    @JsonCreator constructor(id: Long, typeName: String?): this(typeName) {
//        this.id = id
//    }
}
<<p>汽车类/strong>
@Entity
@Table(name="vehicles")
@EntityListeners(AuditingEntityListener::class)
data class Vehicle (
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
var id: Long ?= null,
@NotBlank
@Column(name = "model_name")
var modelName: String ?= null,
@NotBlank
@Column(name = "year")
var year: Int ?= null,
@NotBlank
@Column(name = "brand_id")
var brand: Int ?= null,
@NotBlank
@Column(name = "description")
var description: String ?= null,
@NotBlank
@Column(name = "approved")
var approved: Boolean ?= null,
@OneToOne(fetch = FetchType.LAZY) //cascade = arrayOf(CascadeType.ALL)
@JoinColumn(name = "vehicle_type_id", referencedColumnName = "id")
var vehicleType: VehicleType,
//@JsonProperty("vehicleType") var vehicleType: VehicleType ?= null,
)

VehicleController

@PostMapping("/vehicle/new")
fun createVehicle(@RequestBody vehicle: Vehicle): ResponseEntity<Vehicle?>? { //EntityModel<Vehicle>
try {
val _vehicle: Vehicle = vehicleRepository
//.save(Vehicle(vehicle.content))
//.save(Vehicle(0, vehicle.modelName, vehicle.year, vehicle.brand,
//              vehicle.description, false, vehicle.vehicleType))
.save(vehicle)
return ResponseEntity<Vehicle?>(_vehicle, HttpStatus.CREATED)
} catch (e: java.lang.Exception) {
return ResponseEntity<Vehicle?>(null, HttpStatus.INTERNAL_SERVER_ERROR)
}
}

错误消息似乎是说,Spring找不到VehicleType的构造函数接受单个Int参数,所以显而易见的事情是给它一个!

可以通过添加另一个二级构造函数来实现:

constructor(id: Int): this(null) {
this.id = id.toLong()
}

(免责声明:我自己没有试过……请告诉我们它是否有效!)

如果现有的辅助形参是Int型而不是Long型,那么另一种选择是为它的其他形参提供默认值。(在这种情况下,您还需要添加一个@JvmOverloads注释,以确保它在字节码中生成额外的构造函数。)

我不知道为什么它试图使用Int当属性被定义为一个长;也许这与referencedColumnName = "id"列有关?在任何情况下,Kotlin对于long型和int型(以及其他数值类型)之间的区别都比Java或C等语言要严格一些。

最新更新