配置hibernate jpa和spring mvc(entityManager始终为null)

时间:2016-02-29 14:27:33

标签: java spring hibernate spring-mvc jpa

早上好,我仍然是hibernate jpa和spring的新手,这是我制作的第一个项目,每当我尝试执行它时,我都会得到它。这是我的代码

的applicationContext.xml

   http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/tx      http://www.springframework.org/schema/tx/spring-tx.xsd">

<bean id="dao" class="com.talan.springmvc.dao.AdminDaoImpl">
</bean>


<bean id="metier" class="com.talan.springmvc.metier.AdminMetier">
    <property name="dao" ref="dao" />
</bean>
<bean id="datasource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
    <property name="url" value="jdbc:oracle:thin:@localhost:1521/XE"></property>
    <property name="username" value="system"></property>
    <property name="password" value="Islem1992"></property>

</bean>
<bean id="persistenceUnitManager"
    class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="persistenceXmlLocations">
        <list>
            <value>classpath*:META-INF/persistence.xml</value>
        </list>
    </property>
    <property name="defaultDataSource" ref="datasource"></property>
</bean>
<bean id="entityManagerFactory
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="persistenceUnitManager"></property>
    <property name="dataSource" ref="datasource" />
    <property name="persistenceUnitName" value="myapp"></property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">none</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
        </props>
    </property>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        </bean>
    </property>
</bean>
<!-- <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> 
    <property name="persistenceUnitName" value="myapp"></property> </bean> -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

的persistence.xml

<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="myapp"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
    </persistence-unit>
</persistence>

Test.java

包裹测试;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.talan.springmvc.entities.Agence;
import com.talan.springmvc.entities.User;
import com.talan.springmvc.metier.IAdminMetier;

public class Test {
    public static void main(String[] args){

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
        IAdminMetier admin = (IAdminMetier) context.getBean("metier");
        User u = new User(1,"islem", "yeddes", "salesAgent");
        admin.addUser(u);
    }

}

2 个答案:

答案 0 :(得分:0)

我忘记发布我的DAO

package com.talan.springmvc.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.talan.springmvc.entities.User;

public class AdminDaoImpl implements IAdminDao {
    @PersistenceContext
    private EntityManager em;
    @Override
    public User addUser(User  u) {
        em.persist(u);
        return u;
    }   



}

答案 1 :(得分:0)

首先,您的DataSource存在问题,无法为数据库连接处理数据库池。 org.springframework.jdbc.datasource.DriverManagerDataSource正在为每个HttpRequest创建一个新的Connection,它仅适用于测试目的...... 使用Tomcat中的dbcp:

<dependency>
   <groupId>org.apache.tomcat</groupId>
   <artifactId>tomcat-dbcp</artifactId>
   <version>8.0.32</version>
</dependency>

或来自c3p0vibur的其他提供商,可以大大处理这项工作。

其次,您需要添加@Service(&#34; serviceName&#34;)和一些@Autowired注释,以便为Spring IoC机制提供代码依赖性。也许在你的服务中添加一些@ComponentScan(&#34; com.talan.springmvc.dao&#34;)。

在我的一个项目中,我有一个服务,其定义为:

@Service("utilisateurService")
public class UtilisateurService implements UserDetailsService {

   public static final Logger logger = LoggerFactory.getLogger(UtilisateurService.class);

   private EntityManager entityManager;

   @PersistenceContext
   public void setEntityManager(EntityManager newEm){
      this.entityManager = newEm;
   }


   @Override
   @Transactional
   public UserSpringSecurity loadUserByUsername(final String username) throws UsernameNotFoundException {

   }

   // etc.

} 

当然,有一些bean可以定义我的&#34; utitisateurService&#34;。在XML中:

<context:annotation-config />

<context:property-placeholder location="classpath:jdbc.properties" />

<bean id="dsn1" class="org.vibur.dbcp.ViburDBCPDataSource" 
                init-method="start" destroy-method="terminate">
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="poolInitialSize" value="10" />
    <property name="poolMaxSize" value="50" />
    <property name="connectionIdleLimitInSeconds" value="30" />
    <property name="testConnectionQuery" value="SELECT 1" />
    <property name="logQueryExecutionLongerThanMs" value="500" />
    <property name="logStackTraceForLongQueryExecution" value="true" />
    <property name="statementCacheMaxSize" value="200" />
</bean>


<bean id="crmEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" autowire="byName">
    <property name="persistenceUnitName" value="crmPersistenceUnit" />
    <property name="dataSource" ref="dsn1" />
    <property name="packagesToScan" value="crm.db.model" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="crmEmf"></property>
</bean>

<tx:annotation-driven proxy-target-class="true" mode="proxy" />

<bean id="persistenceExceptionTranslationPostProcessor" 
    class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<!-- Logging -->
<bean id="loggerListener"
    class="org.springframework.security.authentication.event.LoggerListener" />


<bean id="customAuthenticationProvider" class="crm.security.CustomAuthenticationProvider" />
<bean id="utilisateurService" class="crm.service.UtilisateurService"/>

尝试这种方式并告诉我们它是否有效!