Spring + JPA + Hibernate

霸气de小男生 提交于 2019-12-01 20:46:14

I think you're missing the configuration to tell spring to search for the annotations (add the following anywhere between the <beans> element:

<context:annotation-config />

And maybe you also need to add the following specifying the package where you have the DAO. But I don't think this is required.

<context:component-scan base-package="your.package" />

this is working piece of code:

Spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
        <context:annotation-config />
        <context:component-scan base-package="com.package.dao" />
        <tx:annotation-driven transaction-manager="transactionManager" />
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
                <property name="persistenceUnitName" value="fcmsServer" />
        </bean>
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
                <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>        
</beans> 

Dao bean:

@Repository
public class UserDaoBean implements UserDao {
        @PersistenceContext
        protected EntityManager em;         
}

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_1_0.xsd"
             version="1.0">
    <persistence-unit name="fcmsServer" transaction-type="RESOURCE_LOCAL">

        <class>com.package.entity.</class>
        <properties>
            <property name="javax.persistence.jdbc.url"
                 value="jdbc:mysql://localhost:3306/db_name"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.user" value="admin"/>
            <property name="javax.persistence.jdbc.password" value="admin"/>
        </properties>
    </persistence-unit>
</persistence>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!