Skip to content

Instantly share code, notes, and snippets.

@jboner
Created August 24, 2009 15:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jboner/173921 to your computer and use it in GitHub Desktop.
Save jboner/173921 to your computer and use it in GitHub Desktop.
Immutable Domain Model with JPA
// Sketch of an immutable domain model in Scala
// We used this scheme together with this JPA module:
// http://github.com/jboner/skalman/blob/d1e03a85be3964b9012f9e79dd726b0546342b2b/core/src/main/scala/JPA.scala
// ...and this GenericRepository:
// http://github.com/jboner/skalman/blob/d1e03a85be3964b9012f9e79dd726b0546342b2b/core/src/main/scala/GenericRepository.scala
abstract class Entity[T](val id: Int)
object User {
private val identityMap = new ConcurrentHashMap[Int, User]
def apply(id: Int) = identityMap.get(id)
def update(user: User) = identityMap.put(user.id, user)
// add generic repository stuff
}
class User(id: Int, val username: String, val password: String) extends Entity(id) {
User.update(this)
def withUsername(username: String): User = new User(id, username, password)
def withPassword(password: String): User = new User(id, username, password)
}
val updatedUser = User(34).withUsername("bill").withPassword("secret")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment