Skip to content

Instantly share code, notes, and snippets.

@kevinlynx
Last active December 25, 2015 06:39
Show Gist options
  • Save kevinlynx/6934219 to your computer and use it in GitHub Desktop.
Save kevinlynx/6934219 to your computer and use it in GitHub Desktop.
package squtest
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.Schema
import org.squeryl.annotations.Column
import org.squeryl.SessionFactory
import org.squeryl.Session
import org.squeryl.KeyedEntity
import org.squeryl.adapters.H2Adapter
import java.util.Date
import java.sql.Timestamp
class Author(val firstName: String, val lastName: String,
val email: Option[String]) extends KeyedEntity[Long] {
def this() = this("", "", Some(""))
val id: Long = 0
}
// fields can be mutable or immutable
class Book(val id: Long,
var title: String,
@Column("AUTHOR_ID") // the default 'exact match' policy can be overriden
var authorId: Long,
var coAuthorId: Option[Long]) {
def this() = this(0, "", 0, Some(0L))
}
class Borrowal(val id: Long,
val bookId: Long,
val borrowerAccountId: Long,
val scheduledToReturnOn: Date,
val returnedOn: Option[Timestamp],
val numberOfPhonecallsForNonReturn: Int)
object Library extends Schema {
//When the table name doesn't match the class name, it is specified here :
val authors = table[Author]("AUTHORS")
val books = table[Book]
val borrowals = table[Borrowal]
on(borrowals)(b => declare(
b.numberOfPhonecallsForNonReturn defaultsTo (0),
b.borrowerAccountId is (indexed),
columns(b.scheduledToReturnOn, b.borrowerAccountId) are (indexed)))
on(authors)(s => declare(
s.id is (autoIncremented),
s.email is (unique, indexed("idxEmailAddresses")), //indexes can be named explicitely
s.firstName is (indexed),
s.lastName is (indexed, dbType("varchar(255)")), // the default column type can be overriden
columns(s.firstName, s.lastName) are (indexed)))
}
object Test {
def main(args: Array[String]) = {
Class.forName("org.h2.Driver");
SessionFactory.concreteFactory = Some(()=>
Session.create(java.sql.DriverManager.getConnection("jdbc:h2:test.db"), new H2Adapter))
//Squeryl database interaction must occur in a transaction block :
transaction {
Library.authors.insert(new Author("Michel","Folco", None))
val a = from(Library.authors)(a => where(a.lastName === "Folco") select(a))
a.foreach(A => println(A.id + "-> " + A.firstName + " " + A.lastName))
if (a.size >= 3) {
Library.drop
Library.create
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment