Java 休眠和 Scala
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1494792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate and Scala
提问by UberAlex
I have been toying with Scala and I was wondering if anyone had had any experience with using hibernate and mysql as a persistent store for scala objects? Does it work out of the box or is there a lot to do?
我一直在玩 Scala,我想知道是否有人有使用 hibernate 和 mysql 作为 Scala 对象的持久存储的经验?它是开箱即用的还是有很多事情要做?
采纳答案by shaolang
Most of the time, Scala + Hibernate works quite well, with minor bumps which could be overcome easily. For exmaple, when dealing with collections, Hibernate requires the use of java.util interfaces. But you could import scala.collection.jcl.Conversions._ if you want to tap on Scala's more powerful library.
大多数情况下,Scala + Hibernate 运行良好,可以轻松克服一些小问题。例如,在处理集合时,Hibernate 需要使用 java.util 接口。但是如果你想利用 Scala 更强大的库,你可以导入 scala.collection.jcl.Conversions._。
You may want to check out Frank Sommers' post for more information.
您可能需要查看Frank Sommers的帖子以获取更多信息。
回答by UberAlex
I have not used Hibernate with scala directly, but I am using JPA. Hibernate provides a JPA implementation, and the way you define JPA persistent classes or Hibernate ones is not much different, so I think using Hibernate without the JPA layer is possible
我没有直接将 Hibernate 与 scala 一起使用,但我正在使用 JPA。Hibernate 提供了一个 JPA 实现,你定义 JPA 持久化类和 Hibernate 的方式没有太大区别,所以我认为使用没有 JPA 层的 Hibernate 是可能的
回答by andyczerwonka
There are issues. Because some features of JPA leverage nested annotations, e.g. collections, you're in trouble because Scala does not yet support nested annotations. That'll go away when 2.8 comes out.
有问题。因为 JPA 的某些特性利用了嵌套注释,例如集合,所以您会遇到麻烦,因为 Scala 尚不支持嵌套注释。当 2.8 出现时,这种情况就会消失。
See Wille Faler's Blogfor more on this topic plus other incompatibilities.
有关此主题的更多信息以及其他不兼容性,请参阅Wille Faler 的博客。
回答by Phil
Scala Query is not Hibernate but may be interesting.
Scala Query 不是 Hibernate,但可能很有趣。
回答by user369563
Note that Scala 2.8, now in RC5 and expected to release shortly, supports nested annotations. The release has many other cool features as well.
请注意,Scala 2.8(现在在 RC5 中并有望很快发布)支持嵌套注释。该版本还有许多其他很酷的功能。
回答by takacsot
Have a look at Scala version of Play Frameworkwhere there is full JPA adaptation for Scala.
查看Play Framework 的 Scala 版本,其中有针对 Scala 的完整 JPA 改编。
回答by natbusa
It is definitely not a lot of work. A simple hibernate + scala example can be defined in a few tens of lines. Scala and Java can be mixed up in the same project. In particular, the hibernate-scala combination makes possible to combine the JPA framework, and a very flexible orm layer with the elegance of immutable structures and functional programming as provided by scala.
这绝对不是很多工作。一个简单的 hibernate + scala 示例可以在几十行中定义。Scala 和 Java 可以在同一个项目中混合使用。特别是,hibernate-scala 组合可以将 JPA 框架和非常灵活的 orm 层与 Scala 提供的不可变结构和函数式编程的优雅结合起来。
The easiest way to experiment with hibernate and scala is by using an in-memory hsqldb database via hibernate/jpa. First off, let's define the domain model. In this case, a scala class annotated according to hibernate style, about my buddies.
试验 hibernate 和 scala 的最简单方法是通过 hibernate/jpa 使用内存中的 hsqldb 数据库。首先,让我们定义域模型。在这种情况下,一个按照hibernate风格注释的scala类,关于我的伙伴。
package nl.busa.jpa
import javax.persistence._
@Entity
@Table(name = "buddy")
class Buddy(first: String, last: String) {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Int = _
var firstName: String = first
var lastName: String = last
def this() = this (null, null)
override def toString = id + " = " + firstName + " " + lastName
}
Note how the scala class, is much more compact than the java class, since we don't need the typical getter/setter boilerplate code. Now let's make sure, that the jpa modules and the database model is loaded. According to the hibernate specification, let's add the well known hibernate configuration file: resources/META-INF/persistence.xml:
请注意 scala 类如何比 java 类紧凑得多,因为我们不需要典型的 getter/setter 样板代码。现在让我们确保加载了 jpa 模块和数据库模型。根据hibernate的规范,我们添加众所周知的hibernate配置文件:resources/META-INF/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="nl.busa.jpa.HibernateJpaScalaTutorial">
<description>
Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
</description>
<class>nl.busa.jpa.HibernateJpaScalaTutorial</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:JpaScala"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
After defining the persistency configuration, let's move on the main scala file:
定义持久性配置后,让我们继续主要的 scala 文件:
package nl.busa.jpa
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.Persistence
import scala.collection.JavaConversions._
object HibernateJpaScalaTutorial {
var entityManagerFactory: EntityManagerFactory = Persistence.createEntityManagerFactory( "nl.busa.jpa.HibernateJpaScalaTutorial" )
var entityManager: EntityManager = entityManagerFactory.createEntityManager()
def main( args : Array[String]) {
entityManager.getTransaction().begin()
entityManager.persist( new Buddy( "Natalino", "Busa" ) )
entityManager.persist( new Buddy( "Angelina", "Jolie" ) )
entityManager.persist( new Buddy( "Kate", "Moss" ) )
entityManager.getTransaction().commit()
entityManager.getTransaction().begin();
val allBuddies = entityManager.createQuery("From Buddy", classOf[Buddy]).getResultList.toList
entityManager.getTransaction().commit();
allBuddies foreach println
entityManager.close();
}
}
The code is quite straightforward. Once the JPA EntityManager is created via the factory, the data model is available for insertion, deletion, query, using the methods defined in the documentation of hibernate and jpa.
代码非常简单。通过工厂创建 JPA EntityManager 后,数据模型可用于插入、删除、查询,使用 hibernate 和 jpa 文档中定义的方法。
This example has been set up using sbt. After retrieving the necessary packages, and compiling the source, running the tutorial will produce the following log:
这个例子是使用 sbt 设置的。获取必要的包并编译源代码后,运行教程将产生以下日志:
HibernateJpaScalaTutorial:-:1.0.0> run
[info] Running nl.busa.jpa.HibernateJpaScalaTutorial
1 = Natalino Busa
2 = Angelina Jolie
3 = Kate Moss
[success] Total time: 4 s, completed Dec 9, 2012 4:18:00 PM
回答by Marek Zebrowski
I am using hibernate with Scala. The real problem that I had to solve was how to persist Enumerations in hibernate. I've put my working solution on github
我在 Scala 中使用休眠。我必须解决的真正问题是如何在休眠状态下持久化枚举。我已将我的工作解决方案放在 github 上
Basically one needs to define own UserType
基本上需要定义自己的 UserType
abstract class EnumerationAbstractUserType(val et: Enumeration) extends UserType {
....
override def nullSafeGet(resultSet: ResultSet, names: Array[String], session: SessionImplementor, owner: Object): Object = {
val value = resultSet.getString(names(0))
if (resultSet.wasNull()) null
else et.withName(value)
}
override def nullSafeSet(statement: PreparedStatement, value: Object, index: Int, session: SessionImplementor): Unit = {
if (value == null) {
statement.setNull(index, Types.VARCHAR)
} else {
val en = value.toString
statement.setString(index, en)
}
}