HowTo create a basic CRUD

From Lift

Jump to: navigation, search

Basic Database Support

Lift provides a set of classes in the net.liftweb.mapper package that can be used to provide basic mappings to a database. Examples are provided in the cheat sheets and in the demo page on databases. At the core, you simply need to provide a class that extends net.liftweb.mapper.KeyedMapper and a companion object with the net.liftweb.mapper.KeyedMetaMapper trait.

To give the class fields which can also be persisted, you must make use of member objects that extend the various net.liftweb.mapper.Mapped* classes. As a simple example, the following class defines a model with the fields id and entry, where the companion object defines the table name to be entries and sets the default field order to be id and then entry.

object Entry extends Entry with KeyedMetaMapper[Long, Entry] {
    override def dbTableName = "entries"
    override def fieldOrder = id :: entry :: Nil
}


class Entry extends KeyedMapper[Long, Entry] {
  def getSingleton = Entry // what's the "meta" object
  def primaryKeyField = id

  object id extends MappedLongIndex(this)
  
  object entry extends MappedString(this, 8192)

}


Once this is done, you have access to the major CRUD operations exposed by KeyedMetaMapper. These include

 create: A 
 find(by: QueryParam[A]*): Can[A]
 findAll: List[A]
 findAll(by: QueryParam[A]*): List[A]
 save(toSave: A): Boolean

Note, in all of the above A is the type of the model the companion object is created for.

The QueryParam class is extended by the following case classes:

 Cmp[O<:Mapper[O], T](field: MappedField[T,O], opr: OprEnum.Value, value: Can[T], otherField: Can[MappedField[T, O]]) extends QueryParam[O]
 OrderBy[O<:Mapper[O], T](field: MappedField[T,O],ascending: boolean) extends QueryParam[O]
 ByList[O<:Mapper[O], T](field: MappedField[T,O], vals: List[T]) extends QueryParam[O]
 BySql[O<:Mapper[O]](query: String, params: Any*) extends QueryParam[O]
 MaxRows[O<:Mapper[O]](max: long) extends QueryParam[O]
 StartAt[O<:Mapper[O]](start: long) extends QueryParam[O]

Using just these, it is easy to see how a call to

 Entry.findAll(StartAt(0), MaxRows(10))

To keep from having to directly work with the case class Cmp, however, there are also many objects exposed which have an apply method to construct a Cmp class more easily These are:

 By
 NotBy 
 ByRef 
 NotByRef 
 By_>
 By_< 
 NullRef 
 NotNullRef

TODO continue getting stuff on here.

Personal tools