我使用Spring MVC 3开发了一个Hibernate项目,并使用Maven 3构建。我使用JPA特别是Hibernate Framework管理持久性;我想配置OpenJpa的现有源代码并不是那么困难,但我是新手,我想知道将项目配置为从Hibernate到OpenJpa的一致方式的步骤是什么。 / p>
问候
答案 0 :(得分: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();
}
}
希望有所帮助!!