我有一个网络应用程序,其中包含一个数据库
Customer
实体和Car
实体。
我在ManyToMany
和Car
之间有Customer
个关系(或者至少我打算),并且我的BookedCar
课程中有BookedCar
个关系。
@Entity
@Table(name = "booked_cars")
data class BookedCar(@Column(name = "car_id") var carId: Int = 0,
@Column(name = "customer_id") var customerId: Int = 0,
@Column var startDate: Date = Date(),
@Column var endDate: Date = Date()) {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int = 0
}
Car
@Entity
@Table(name = "cars")
data class Car(@Column var name: String = "",
@Column var price: Int = 0,
@Column(length = 1000) var imgURL: String = "") {
fun getPriceForPeriodPerDay(days: Int) = when (days) {
in 0..3 -> this.price
in 3..8 -> this.price - 7
in 8..15 -> this.price - 15
in 15..Int.MAX_VALUE -> this.price - 20
else -> this.price
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int = 0
@ManyToMany(cascade = [CascadeType.ALL])
@JoinTable(name = "booked_cars",
joinColumns = [(JoinColumn(name = "car_id", referencedColumnName = "id"))],
inverseJoinColumns = [JoinColumn(name = "customer_id", referencedColumnName = "id")])
lateinit var customers: Set<Customer>
}
Customer
@Entity
@Table(name = "customers")
data class Customer(@Column var phoneNumber: String = "",
@Column var name: String = "") {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int = 0
@ManyToMany(mappedBy = "customers")
lateinit var bookedCars: Set<Car>
}
...
val customer = this.customerRepository.findOneByPhoneNumber(phoneNumber)
?: Customer(phoneNumber, "")
val car = this.carRepository.findOne(id)
val bookedCar = BookedCar(car.id,customer.id, startDate, endDate)
this.requestedCarRepository.saveAndFlush(bookedCar)
...
在我的一个控制器中,我有一个带有一些映射和代码的函数:
this.requestedCarRepository.saveAndFlush(bookedCar)
问题恰好出现在这一行
上java.sql.SQLException: Field 'id' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965) ~[mysql-connector-java-5.1.45.jar:5.1.45]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.45.jar:5.1.45]
...
at com.rentautosofia.rentacar.controller.FrontCarController.orderProcess(FrontCarController.kt:113) ~[classes/:na]
...
和错误是
JoinColumn
我不认为我正确地写了spring.datasource.url = jdbc:mysql://localhost:3306/rentacar?...&createDatabaseIfNotExist=true
。总的来说,任何帮助将受到高度赞赏
我尝试重新创建数据库。
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
# Using "create" will delete and recreate the tables every time the project is started
spring.jpa.hibernate.ddl-auto = update
Jpa DDL自动增量:
Listing_01_01_Gold.groovy
答案 0 :(得分:1)
您无法将连接表与实体混合
您将BookedCar
定义为一个实体...您真的需要这个吗?或者您只需要一个连接表来完成客户和汽车之间的多对多连接...如果您需要更多列在预订的汽车(不是强制性ID,我的意思是一个包含一些业务的列)然后确定它是一个实体,否则只是使它成为一个连接列
如果您决定将其作为一个实体,那么您将需要从每个客户和汽车到booking_car的一对多关系,以及从scheduled_car到他们每个人的多对一......而不是这个ManyToMany关系你在汽车和客户中使用