Skip to content

Instantly share code, notes, and snippets.

@johanvergeer
Last active March 30, 2018 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanvergeer/eb0827595c490f742ce3dc9d4ef306c3 to your computer and use it in GitHub Desktop.
Save johanvergeer/eb0827595c490f742ce3dc9d4ef306c3 to your computer and use it in GitHub Desktop.
Simple way to encapsulate a collection in a Kotlin Spring Entity
import javax.persistence.*
@Entity
data class OrderEntity(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: Long? = -1,
var firstName: String,
var lastName: String
) {
@OneToMany(cascade = [(CascadeType.ALL)], fetch = FetchType.LAZY, mappedBy = "order")
private val _lineItems = mutableListOf<LineItem>()
@Transient
val lineItems = _lineItems.toList()
fun addLineItem(newItem: LineItem) = this._lineItems.plusAssign(newItem)
}
@Entity
data class LineItem(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
val id: Long? = -1,
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "order_id")
val order: OrderEntity? = null
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment