0

我有一个使用 Spring MVC 3 开发并使用 Maven 3 构建的 Hibernate 项目。我使用 JPA 管理持久性,特别是 Hibernate Framework;我想为 OpenJpa 配置我现有的源并不难,但我是新手,我想知道配置我的项目以一致的方式从 Hibernate 切换到 OpenJpa 的步骤是什么。

问候

4

1 回答 1

1

请按照以下步骤操作:

要切换到注释,您需要:

Add hibernate-annotations and JPA jars
Annotate your classes
Modify hibernate.cfg.xml to use classes instead of mapping files
Modify your HibernateUtil class to use a different configuration (this is the step that tripped me up)

为了添加正确的 jar,我使用了 Maven 并添加了以下附加依赖项:

<dependency>

  <groupId>javax.persistence</groupId>

  <artifactId>persistence-api</artifactId>

  <version>1.0</version>

</dependency>

<dependency>

 <groupId>org.hibernate</groupId>

  <artifactId>hibernate-annotations</artifactId>

  <version>3.3.1.GA</version>

</dependency>

JPA 注释上有很多很好的资源可用,所以我不打算详细讨论这个。您将拥有如下所示的内容:

@Entity

@Table(name = “USERS”)

public class User {

@Id @GeneratedValue

@Column(name = “USER_ID”)

private Long id;

@Column(name = “FIRST_NAME”)

private String firstName;

@Column(name = “LAST_NAME”)

private String lastName;

@Column(name = “EMAIL”)

private String email;

// etc

}

要更新 hibernate.cfg.xml 文件,您需要更改如下行:

<mapping resource="org/terracotta/reference/exam/domain/User.hbm.xml"/>

像这样:

<mapping class="org.terracotta.reference.exam.domain.User">

如果你做了所有这些并停在那里,你可能会看到这样的异常:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.terracotta.reference.exam.domain.HibernateUtil.<clinit>(HibernateUtil.java:15)
    at org.terracotta.reference.exam.domain.Main.main(Main.java:12)
Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="org.terracotta.reference.exam.domain.User"/>
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1600)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1555)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1534)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1508)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
    at org.terracotta.reference.exam.domain.HibernateUtil.<clinit>(HibernateUtil.java:13)

而且,像我一样,你会感到困惑。事实证明,在使用注解时需要使用 AnnotationConfiguration,它是 Configuration 的子类,专门用于注解。因此,您的 HibernateUtil 可能看起来像这样:

package org.terracotta.reference.exam.domain;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

private static SessionFactory sessionFactory;

static {

try {

sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

} catch(Throwable t) {

throw new ExceptionInInitializerError(t);

}

}

public static SessionFactory getSessionFactory() {

return sessionFactory;

}

public static void shutdown() 
{

getSessionFactory().close();

}

}

希望有帮助!!

于 2013-05-09T12:59:43.590 回答