DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Use Of "immutable" Scala Entities With Hibernate
Here you can see how to use "immutable" scala objects with Hibernate:
val some = "Alexey"
val another = "John"
connect { (manager, tx) =>
val person = new Person(name=some)
tx { () => manager.persist(person) }
var result = manager
.createQuery("SELECT p FROM Person p WHERE p.name = :name")
.setParameter("name", some)
.getSingleResult
.asInstanceOf[Person]
tx { () => manager.merge(result.copy(name=another)) }
}
Entity class can be defined in the following way. Hibernate will use default constructor to create instance of the class and will initialize implicit fields.
import javax.persistence._
import java.io.Serializable
@Entity
class Person (
@Id @GeneratedValue
val id: Integer = null,
val name: String = null
) extends Serializable {
def this() = this(id = null)
}
The previous snippet uses the helper function:
def connect(body: (EntityManager, (() => Unit) => Unit) => Unit) {
val factory = Persistence.createEntityManagerFactory("yourunitname")
val manager = factory.createEntityManager
body(manager, { txBody =>
manager.getTransaction.begin()
txBody()
manager.getTransaction.commit()
})
manager.close()
factory.close()
}




