2

Hibernate doesn't want to save IDs for child entities. I have the following tables:

@Entity
@Table(name = "ct_orders")
data class Order(

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
    val id: Int = 0,

    @OneToMany(fetch = FetchType.LAZY, cascade = arrayOf(CascadeType.ALL), mappedBy = "order")
    val route: List<Route>? = null,

    ...

)

@Entity
@Table(name = "ct_routes")
@JsonIgnoreProperties("id", "order")
data class Route(

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int = 0,

    @Column
    val location: Point = GeoHelpers.point(),

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "order_id")
    val order: Order? = null,

    @Column
    val title: String = ""

)

ct_routes saving with null in order_id. Is there some problem with relationships? Or, may be there is something wrong in my code?

Here is the part of code, which saves an Order entity:

val order = orderRepository.save(Order(
    ...
    route = GeoHelpers.placesListToEntities(data.places),
    ...
))

fun placesListToEntities(points: List<PlaceDto>) = points.map {
    Route(
        location = Helpers.geometry(it.location.latitude, it.location.longitude),
        title = it.title
    )
}
Fernando Luiz
  • 131
  • 1
  • 2
  • 11

1 Answers1

3

You're modeling bidirectional @OneToMany and as shown in the example in the documentation you're responsible for setting the parent value on the child entity:

val order = orderRepository.save(Order(...).apply{
    ...
    route = GeoHelpers.placesListToEntities(this, data.places),
    ...
})

fun placesListToEntities(order:Order, points: List<PlaceDto>) = points.map {
    Route(
        order = order,
        location = Helpers.geometry(it.location.latitude, it.location.longitude),
        title = it.title
    )
}

PS. Since Route is an entity you could change your model a bit to enforce the constraints on the langauge level i.e:

class Route internal constructor() {
    lateinit var order: Order

    constructor(order: Order) : this() {
        this.order = order
    }
}

See this question for more details.

Community
  • 1
  • 1
miensol
  • 39,733
  • 7
  • 116
  • 112