目前有关 Scala libraries 和框架相当多
有一些非ORM的数据库库,也有ORM的,下面列出一些:
ScalaQuery
The first one is ScalaQuery. It is the most mature one, and it tries to make queries use the same for-comprehension as Scala collections do. As an example of syntax style (which might be slightly out of date):
在试用了一下后,发现对MS SERVER 支持地不太好
import java.lang.Integer
import com.novocode.squery._
import com.novocode.squery.Implicit._
import com.novocode.squery.session._
import com.novocode.squery.session.SessionFactory._
// Define table:
object Users extends Table[(Integer, String, String)]("users") {
def id = intColumn("id", O.AutoInc, O.NotNull)
def first = stringColumn("first")
def last = stringColumn("last")
def * = id ~ first ~ last
}
// Basic usage
val sf = new DriverManagerSessionFactory("org.h2.Driver", "jdbc:h2:mem:test1")
sf withSession {
// Prepare a simple query
val q1 = for(u <- Users) yield u
// Print SQL statement to be executed:
println(q1.selectStatement) // displays SELECT t1.id,t1.first,t1.last FROM users t1
// Print query result:
for(t <- q1) println("User tuple: "+t)
// Query statements can also be used with updates:
val q = for(u <- Users if u.id is 42) yield u.first ~ u.last
q.update("foo", "bar")
}
Querulous
The second one is Querulous, which is a open source project from Twitter. This one gives you direct access to SQL, while dealing with a bunch of jdbc annoyances. Here's a simple example:
import com.twitter.querulous.evaluator.QueryEvaluator
val queryEvaluator = QueryEvaluator("host", "username", "password")
val users = queryEvaluator.select("SELECT * FROM users WHERE id IN (?) OR name = ?", List(1,2,3), "Jacques") { row =>
new User(row.getInt("id"), row.getString("name"))
}
queryEvaluator.execute("INSERT INTO users VALUES (?, ?)", 1, "Jacques")
queryEvaluator.transaction { transaction =>
transaction.select("SELECT ... FOR UPDATE", ...)
transaction.execute("INSERT INTO users VALUES (?, ?)", 1, "Jacques")
transaction.execute("INSERT INTO users VALUES (?, ?)", 2, "Luc")
}
Squeryl
The third one is Squeryl. Style-wise, it sits midway between ScalaQuery -- which hides SQL behind Scala comprehensions as much as possible -- and Querulous -- which uses SQL strings directly.
Squeryl provides a SQL-like DSL, which gives you type safety and give you a strong likelyhood that the statements won't fail at run-time if they compile at all. Again, a simple example:
// Defining tables and a schema:
import org.squeryl.PrimitiveTypeMode._
class Author(var id: Long,
var firstName: String,
var lastName: String)
class Book(var 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))
}
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]
}
// Basic usage
Class.forName("org.postgresql.Driver");
val session = Session.create(
java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5432/squeryl", "squeryl", "squeryl"),
new PostgreSqlAdapter
)
//Squeryl database interaction must be done with a using block :
import Library._
using(session) {
books.insert(new Author(1, "Michel","Folco"))
val a = from(authors)(a=> where(a.lastName === "Folco") select(a))
}
O/R Broker
http://code.google.com/p/orbroker/
The fourth is O/R Broker, which, despite the name, is not an ORM. Classes can be designed in any way desired. No interfaces/traits to implement, no conventions to uphold, no annotations needed.
可以快速开发,灵活性较高
case class Song(id: Option[Long], title: String, seconds: Short)
case class Album(id: Option[Long], title: String, year: Short, songs: IndexedSeq[Song])
case class Artist(id: Option[Long], name: String, albums: Set[Album])
Extractors are declarative, written in Scala. Can be reused in other queries that fit the expectation of the extractor.
object SongExtractor extends JoinExtractor[Song] {
val key = Set("SONG_ID")
def extract(row: Row, join: Join) = {
new Song(
row.bigInt("SONG_ID"),
row.string("TITLE").get,
row.smallInt("DURATION_SECONDS").get
)
}
}
object AlbumExtractor extends JoinExtractor[Album] {
val key = Set("ALBUM_ID")
def extract(row: Row, join: Join) = {
new Album(
row.bigInt("ALBUM_ID"),
row.string("TITLE").get,
row.smallInt("YEAR_ISSUED").get,
join.extractSeq(SongExtractor, Map("TITLE"->"SONG_TITLE"))
)
}
}
object ArtistExtractor extends JoinExtractor[Artist] {
val key = Set("ARTIST_ID")
def extract(row: Row, join: Join) = {
new Artist(
row.bigInt("ARTIST_ID"),
row.string("NAME"),
join.extractSeq(AlbumExtractor)
)
}
}
One could then use that like this:
val ds: javax.sql.DataSource = ...
val builder = new SQLFileBuilder(ds, new java.io.File("sql/"))
val broker = builder.build()
// Print all artists with their albums (if any)
val artists = broker.readOnly() { session =>
session.selectAll[Artist]('selectArtist) // ' I wish they could fix the Scala Symbol formatting
}
for (ar <- artists) {
println(a.name)
if (ar.albums.isEmpty)
println("\t<No albums>")
else for (al <- ar.albums) {
println("\t" + al.title)
for (s <- al.songs) {
println("\t\t" + (al.songs.indexOf(s)+1) + ". " + s.title)
}
}
}
Anorm
来自于Play框架,it ditches mappings and DSL completely, giving you direct access to SQL. 实例:
// Create an SQL query
val selectCountries = SQL("Select * from Country")
// Transform the resulting Stream[Row] as a List[(String,String)]
val countries = selectCountries().map(row =>
row[String]("code") -> row[String]("name")
).toList
It also supports pattern matching for row extraction:
val countries = SQL("Select name,population from Country")().collect {
case Row("France", _) => France()
case Row(name:String, pop:Int) if(pop > 1000000) => BigCountry(name)
case Row(name:String, _) => SmallCountry(name)
}
Binding variables in queries uses this syntax:
SQL(
"""
select * from Country c
join CountryLanguage l on l.CountryCode = c.Code
where c.code = {countryCode};
"""
).on("countryCode" -> "FRA")
And it also has support for use of parse combinators to translate queries or even table schemas into data structures. You can either define the parser yourself, or use some default conventions (like a case class mapping field names to column names) and let it do the work for you.
Circumflex ORM
网站上有例子如下:
class Category extends Record[Category] {
val id = field(Category.id)
val name = field(Category.name)
val books = oneToMany(Book.category) // allows navigating between associations transparently
}
object Category extends Table[Category] with LongIdPK[Category] {
val name = stringColumn("name") // creates a column
.notNull // creates NOT NULL constraint
.unique // creates UNIQUE constraint
.validateNotEmpty // adds NotEmpty validation
.validatePattern("^[a-zA-Z]{1,8}$") // adds Pattern validation
}
class Book extends Record[Book] {
val id = field(Book.id)
val title = field(Book.title)
val category = manyToOne(Book.category)
}
object Book extends Table[Book] with LongIdPK[Book] {
val title = stringColumn("title")
.notNull
.validateNotEmpty
val category = longColumn("category_id")
.references(Category) // creates an association with Category
.onDeleteSetNull // specifies a foreign-key action
.onUpdateCascade
}
new DDLExport(Category, Book).create // creates database schema
// find category by id
val c = Category.get(2l)
// find all books
val allBooks = Book.all
// find books for category
val cBooks = c.get.books
// find books by title
Book.criteria.add("title" like "a%").list
select()
.from(Category as "c" join (Book as "b"), Category as "c1")
.where("c1.name" like "a%")
.addOrder(asc("c.name"))
.list
select(count("b.id"), "c.name").from(Category as "c" join (Book as "b")).list
以上资料摘至
http://stackoverflow.com/questions/1362748/wanted-good-examples-of-scala-database-persistence
分享到:
相关推荐
Domala是Scala的数据库访问库。 这包装了 。 Domala使用生成代码并在编译时验证sql映射。 Select语句由您自己编写。 它被自动映射到Option[ Entity ] , Seq[ Entity ] , Stream[ Entity ] , Seq[Map[String, ...
目录人工智能名称描述GitHub活动类型安全,纯功能的计算智能CIlib社区驱动的教程数据库Scala中的数据库访问库。 名称描述GitHub活动 akka-persistence-gcp-datastore是日记和快照存储插件,用于在数据存储模式下使用...
该项目使用 Play 框架在 Scala 中实现,Slick 用于数据库访问,Silhouette 用于身份验证库。 多亏了 Manmosu 比原来的Mamute 支持更多的社交登录提供者。 该项目当前使用原始数据库架构并保留相同的 url,因此可以...
该库背后的动机是为 DynamoDB 提供一个简单的异步数据访问层,并利用 Play 框架的原生 json 解析。 尽管 AWS sdk 确实有异步方法,但它使用了 java 期货,这会影响性能并且与 Play 不兼容。 此外,在 Java 中创建...
Scala编程项目 这是Packt发布的的代码库。 使用流行的Scala框架... 使用Slick访问关系数据库 如果您觉得这本书适合您,请立即获取! 说明和导航 所有代码都组织在文件夹中。 例如,Chapter02。 该代码将如下所示:
寿命-Scala和NoSQL的持久性框架。将开发重点放在域模型上,而不是数据库模型上。 长寿将您的域转换为自然,易于理解的数据库模型。 您的持久对象存储为JSON,并且我们添加了其他所有保持快速性能所需的数据库模式。 ...
Sentry Hadoop集群元数据和数据存储提供集中、细粒度的访问控制项⽬ 14 数据可视化 Kibana ⽤于和 Elasticsearch ⼀起使⽤的开源的分析与可视化平台 15 数据挖掘 Mahout 基于hadoop的机器学习和数据挖掘的⼀个分布式...
提供数据库读写分离、及读负载均衡,并且允许配置多个不同的数据库,甚至允许在运行期间增加新的数据库配置,并自动映射ORM。允许执行标准的SQL或存储过程,同时提供了一个简单、轻量的ORM工具,并集成Hibernate、...
REST应该很容易-Respite是一个React性和模块化的微框架,适用于用Scala编写的REST应用程序。 特征 设计遵循原则的架构 式的路由DSL由 可扩展的REST缓存支持和DSL API使用率指标 通过Reactive Mongo和Akka开箱即用地...
Laravel易于访问,功能强大,并提供大型,强大的应用程序所需的工具。 学习Laravel Laravel拥有所有现代Web应用程序框架中最广泛,最全面的和视频教程库,因此轻而易举地开始使用该框架。 如果您不想读书,可以...
Play Framework是一种高效的Java和Scala Web应用程序框架,该框架集成了...Play不受数据库访问的限制,并且与许多对象关系映射(ORM)层集成。它开箱即用地支持Anorm,Slick和JPA,但是许多客户使用NoSQL或其他ORM。
9、它提供了REST API,可以被任何编程语言(如Java,Spring,Scala等)访问 10、它提供了可以通过任何UI MVC框架(如Node JS)访问的Java脚本 11、它支持两种Java API:Cypher API和Native Java API来开发Java应用...
Play 框架和 Slick 数据库和 bootstrap3 访问库的激活器模板。 您还可以从首页执行“slick code generetor”。
怎么跑安装JDK和Play框架(请参阅 ) 设置PostgreSQL数据库在启动时添加对conf/application.conf的数据库访问权限或覆盖其某些键(请参阅 ) activator run (dev)或activator stage ,然后是./target/universal/...
编程语言/框架/平台 安卓 . AngularJS 主干JS C++ C C♯ 。网 Clojure 咖啡脚本 CSS 姜戈 EmberJS 二郎 高朗 HTML 离子 IOS Java JavaScript KnockoutJS 较少的 Lisp 节点 目标-C PHP Python Ruby on Rails ReactJS ...
编程语言/框架/平台 安卓 . AngularJS 主干JS C++ C C♯ 。网 Clojure 咖啡脚本 CSS 姜戈 EmberJS 二郎 高朗 HTML 离子 IOS Java JavaScript KnockoutJS 较少的 Lisp 节点 目标-C PHP Python Ruby on Rails ReactJS ...
使用Slick访问JDBC数据库。 实现表分页和排序功能。 带有嵌入式JS和CSS库。 基于Play和Scala的模板引擎实现 与CSS框架集成(Twitter Bootstrap 3.1.1)。 Twitter Bootstrap需要与Play表单助手生成的默认布局...
编程语言/框架/平台 安卓 . AngularJS 主干JS C++ C C♯ 。网 Clojure CSS 姜戈 EmberJS 二郎 高朗 HTML 离子 IOS Java JavaScript KnockoutJS 较少的 Lisp 节点 目标-C PHP Python Ruby on Rails ReactJS Ruby 萨斯...
你可以从得到创建一个名为test的数据库如果尚未安装Typesafe Activator,请安装它。 您可以从这里获取: : 执行./activator clean compile以构建产品执行./activator run以执行产品现在应该可以在localhost:9000上...