Created
August 19, 2012 08:53
-
-
Save holograph/3393789 to your computer and use it in GitHub Desktop.
Followup sample code for SCL-4559
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.tomergabel.examples | |
import org.squeryl.PrimitiveTypeMode._ | |
import org.squeryl.{Session, SessionFactory, KeyedEntity, Schema} | |
import java.sql.Timestamp | |
/** | |
* Created by tomer on 7/2/12. | |
*/ | |
object MySchema extends Schema { | |
class Book( val title: String, val authorId: Int, val price: Float, | |
val genre: String, val updatedAt: Timestamp = new Timestamp( System.currentTimeMillis() ) ) | |
extends KeyedEntity[ Int ] { | |
val id = Int.MinValue | |
} | |
class Author( val name: String ) extends KeyedEntity[ Int ] { | |
val id = Int.MinValue | |
} | |
val books = table[ Book ]( "BOOK" ) | |
val authors = table[ Author ]( "AUTHOR" ) | |
on( books )( book => declare( book.id is( primaryKey, autoIncremented ), book.updatedAt is( indexed ) ) ) | |
on( authors )( author => declare( author.id is( primaryKey, autoIncremented ) ) ) | |
} | |
object ORMDoneRight { | |
def main( args: Array[ String ] ) { | |
// Setup Squeryl | |
new org.h2.Driver | |
SessionFactory.concreteFactory = Some( () => new Session( | |
java.sql.DriverManager.getConnection( "jdbc:h2:mem:sample" ), | |
new org.squeryl.adapters.H2Adapter | |
) ) | |
import MySchema._ | |
def countBooksByAuthor( authorId: Int ) = | |
from( books )( book => where( book.authorId === authorId ) compute( count ) ) | |
inTransaction { | |
// Create schema and add some data | |
MySchema.create | |
val brust = authors.insert( new Author( "Steven Brust" ) ) | |
val heinlein = authors.insert( new Author( "Robert A. Heinlein" ) ) | |
books.insert( new Book( "The Moon Is a Harsh Mistress", heinlein.id, 10.87f, "Sci-Fi" ) ) | |
books.insert( new Book( "The Book of Jhereg", brust.id, 10.88f, "Fantasy" ) ) | |
// Run some tests | |
assert( countBooksByAuthor( brust.id ) > 0 ) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment