使用Spring JPA注入EntityManager

时间:2018-09-14 15:34:33

标签: java spring jpa

我有一个使用Spring和Jpa使用Eclipse训练的小型应用程序。当我注入Entitymanager时,它给出一个错误,它为NULL。 我在Google上搜索了很多东西,试图了解我是否错过了一些东西并阅读了官方文档,但我找不到问题的根源。任何帮助表示赞赏。运行主类后,我加入了控制台。

spring-context.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-3.2.xsd   
                       http://www.springframework.org/schema/tx
                       http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
                       http://www.springframework.org/schema/context
                      http://www.springframework.org/schema/context/spring-context-3.2.xsd
                       ">
       <context:component-scan base-package="src/ben" />
       <tx:annotation-driven /> 

       <bean id="hello" class="ben.Hello">
             <property name="message" value="Bonjour"> </property>
       </bean>

 <bean id="myEmf"
     class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
       <property name="dataSource" ref="dataSource" />
       <property name="packagesToScan" value="ben" />
       <property name="persistenceUnitName" value="BenJpaProject"></property>
       <property name="jpaVendorAdapter">
           <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
       </property>
       <property name="jpaProperties">
          <props>
              <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
             <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
          </props>
       </property>
   </bean>

   <bean id="dataSource"
     class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
          <property name="url" value="jdbc:oracle:thin:@10.56.4.101:1552/dev1002" />      
          <property name="username" value="ISPOWNRE6" />
          <property name="password" value="ISPOWNRE6" />

   </bean>

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


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

 <bean  id="personDao"  class="ben.AbstractBaseDao" />

 <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 
   xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
  http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

    <persistence-unit name="BenJpaProject" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>ben.Person</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
            <property name="javax.persistence.jdbc.user" value="ISPOWNRE6" />
            <property name="javax.persistence.jdbc.password" value="ISPOWNRE6" />
            <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@10.56.4.101:1552:dev1002" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.jdbc.lob.non_contextual_creation"
                value="true" />
            <property name="hibernate.jdbc.use_get_generated_keys"
                value="true" />
            <property name="hibernate.archive.autodetection" value="class " />
         </properties>
     </persistence-unit>
</persistence>

使用EntityManager的类:

package ben;

@Repository
public class AbstractBaseDao
{
private EntityManager em;

  @PersistenceContext
  public void setEm(EntityManager em)
  {
    this.em = em;
  }


  public <T> T findById (Class <T> clazz,Serializable code)
  {
     return em.find(clazz, code);
  }

}

主类:

public class MainJpa
{

  public static void main(String[] args)
  {
    ApplicationContext context= new ClassPathXmlApplicationContext("spring/spring-context.xml");

    PersonDaoImpl personDaoImpl=new PersonDaoImpl();
    Person person=personDaoImpl.findPersonById((long) 10);
    System.out.println("person Found "+person);
  }

}

PersonDaoImpl类:

public class PersonDaoImpl extends AbstractBaseDao implements  PersonDao
{

  @Override
  public Person findPersonById(Long id)
  {
    Class <Person> clazz=Person.class;
    return findById(clazz, id);

  }

运行主类后控制台:

Sep 14, 2018 11:29:22 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1698c449: startup date [Fri Sep 14 11:29:22 EDT 2018]; root of context hierarchy
Sep 14, 2018 11:29:22 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/spring-context.xml]
Sep 14, 2018 11:29:23 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: oracle.jdbc.driver.OracleDriver
Sep 14, 2018 11:29:23 AM org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager readPersistenceUnitInfos
INFO: Found explicit default unit with name 'BenJpaProject' in persistence.xml - overriding local default unit settings ('packagesToScan'/'mappingResources')
Sep 14, 2018 11:29:23 AM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'BenJpaProject'
Sep 14, 2018 11:29:23 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: BenJpaProject
    ...]
Sep 14, 2018 11:29:23 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.10.Final}
Sep 14, 2018 11:29:23 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 14, 2018 11:29:23 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Sep 14, 2018 11:29:24 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Sep 14, 2018 11:29:25 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Sep 14, 2018 11:29:25 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
Sep 14, 2018 11:29:26 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Sep 14, 2018 11:29:26 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table Person cascade constraints
Hibernate: create table Person (id number(19,0) not null, numero number(19,0), primary key (id))
Sep 14, 2018 11:29:27 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Sep 14, 2018 11:29:27 AM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean buildNativeEntityManagerFactory
INFO: Initialized JPA EntityManagerFactory for persistence unit 'BenJpaProject'
Exception in thread "main" java.lang.NullPointerException
    at ben.AbstractBaseDao.findById(AbstractBaseDao.java:38)
    at ben.PersonDaoImpl.findPersonById(PersonDaoImpl.java:12)
    at ben.MainJpa.main(MainJpa.java:14)

0 个答案:

没有答案