【问题标题】:Why is Scala searching persistence.xml instead of hibernate.cfg.xml?为什么 Scala 搜索 persistence.xml 而不是 hibernate.cfg.xml?
【发布时间】:2019-05-07 08:32:53
【问题描述】:

我不是休眠方面的专家,但我正在尝试使用 Scala 来学习它。到目前为止,我只能找到 Java 的 hibernate 文档,但没有 scala。

我的困惑是什么时候应该使用 persistence.xml,什么时候应该使用 hibernate.cfg.xml。

我有这个疑问,因为我看到了这两个例子,我的代码有时抱怨找不到persistence.xml,当它找到它时又抱怨找不到休眠属性......所以我感到困惑。我觉得 Scala/Java 或不同标准之间有一种摩擦……

有什么建议吗?

这是我的主要应用:

package nl.busa.jpa


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

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
    println(allBuddies);

    entityManager.close();
}
}

这是我的 hibernate.cfg.xml

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory name="hibernate.cfg.xml">
    <property name = "hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name = "hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name = "hibernate.connection.url">jdbc:mysql://localhost/test</property>
    <property name = "hibernate.connection.username">root</property>
    <property name = "hibernate.connection.password"></property>
    <property name="hibernate.hbm2ddl.auto">create"</property>
</session-factory>
</hibernate-configuration>

我的错误信息是这样的:

在类路径中找不到任何 META-INF/persistence.xml 文件

【问题讨论】:

标签: scala hibernate


【解决方案1】:

很可能这个问题至少是部分重复的

what is the purpose of two config files for Hibernate?

但潜在的问题要广泛得多:简而言之:persistence.xml 用于 JPA 模式下的 Hibernate,hibernate.cfg.xml 用于 Hibernate 的本机 API)。乍一看,您的代码看起来像 JPA,因此您需要 persistence.xml。您最好的做法可能是首先学习 JPA,除非您有充分的理由想要使用专有的 Hibernate API。互联网上有很多关于 JPA 的好资源,例如 official Oracle tutorialLars Vogel's

JPA 在许多 ORM 中实现(不仅是 Hibernate,还包括 EclipselinkOpenJPA - 有关更多信息,请参阅 What is a JPA implementation?。在我看来,学习/使用 Hibernate 仅在您打算使用 Hibernate 作为您的 ORM 解决方案。

如果您计划有一天使用应用程序服务器,它们通常带有嵌入式 JPA 实现,使用和管理这些内置设施比提供另一个 ORM 容易得多。

【讨论】:

    猜你喜欢
    • 2018-11-22
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多