简体   繁体   English

使用Spring的Hibernate注释进行ORM

[英]ORM using Hibernate's annotations with Spring

I'm trying integrate spring with hibernate but catch exception on project start. 我正在尝试将spring与hibernate集成在一起,但是在项目启动时捕获了异常。

Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.domain.Worker"/

My config: from spring 我的配置:从春天

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:mysql://localhost/school"/>
        <property name="username" value="root"/>
        <property name="password" value="toor"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="configLocation" value="/WEB-INF/hib.cfg.xml"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

hib.cfg.xml hib.cfg.xml

<hibernate-configuration>


    <session-factory name="java:hibernate/SessionFactory">


        <property name="connection.datasource">java:/comp/env/jdbc/MyDB</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="transaction.factory_class">
            org.hibernate.transaction.JTATransactionFactory
        </property>
        <property name="jta.UserTransaction">java:comp/UserTransaction</property>
        <property name="configClass">org.hibernate.cfg.AnnotationConfiguration</property>

        <mapping class="com.domain.Worker"/>
    </session-factory>
</hibernate-configuration>

domain class 域类

package com.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
@Entity
public class Worker extends DomainObject {
    @Column(nullable = false, length = 20)
    public String getFirstName() {
        return firstName;
    }
//...

如果要对带注释的实体使用Hibernate API,则需要使用AnnotationSessionFactoryBean而不是LocalSessionFactoryBean

If you want to use JPA annotations then you should likely be using a LocalEntityManagerFactoryBean rather than a LocalSessionFactoryBean . 如果要使用JPA批注,则可能应该使用LocalEntityManagerFactoryBean而不是LocalSessionFactoryBean

The former loads your annotations and entities through the regular JPA methods, while your configuration quoted above attempts to use the Hibernate SessionFactory directly. 前者通过常规的JPA方法加载注释和实体,而上面引用的配置尝试直接使用Hibernate SessionFactory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM