복붙노트

[SPRING] Spring JPA와 persistence.xml

SPRING

Spring JPA와 persistence.xml

글래스 피시 배포를 위해 Spring JPA Hibernate 간단한 예제 WAR을 설정하려고합니다. persistence.xml 파일을 사용하는 예제가 있으며 다른 예제에서는 그렇지 않습니다. 일부 예제에서는 dataSource를 사용하고 일부는 사용하지 않습니다. 지금까지 내 이해는 내가 가지고있는 경우 dataSource 필요하지 않습니다 :

<persistence-unit name="educationPU"
    transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.coe.jpa.StudentProfile</class>
    <properties>
        <property name="hibernate.connection.driver_class"
            value="com.mysql.jdbc.Driver" />
        <property name="hibernate.connection.url"
            value="jdbc:mysql://localhost:3306/COE" />
        <property name="hibernate.connection.username" value="root" />
        <property name="show_sql" value="true" />
        <property name="dialect" value="org.hibernate.dialect.MySQLDialect" />
    </properties>
</persistence-unit>

나는 잘 배치 할 수 있지만 EntityManager는 Spring에 의해 주입되지 않는다.

내 applicationContext.xml :

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="educationPU" />
</bean>

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

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

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="StudentProfileDAO" class="com.coe.jpa.StudentProfileDAO">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="studentService" class="com.coe.services.StudentService">
</bean>

EntityManager를 사용한 나의 수업 :

public class StudentService {
private String  saveMessage;
private String  showModal;
private String modalHeader;
private StudentProfile studentProfile;
private String lastName;
private String firstName;

@PersistenceContext(unitName="educationPU")
private EntityManager em;

@Transactional
public String save()
{
    System.out.println("*** em: " + this.em); //em is null
    this.studentProfile= new StudentProfile();
    this.saveMessage = "saved";
    this.showModal = "true";
    this.modalHeader= "Information Saved";
    return "successs";
}

내 web.xml :

  <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

Spring에서 StudentService에 "em"을 삽입하도록 설정하지 않은 부분이 있습니까?

해결법

  1. ==============================

    1.네가 아마했을지라도 확인 만하면 ...

    네가 아마했을지라도 확인 만하면 ...

    당신은

    <!--  tell spring to use annotation based congfigurations -->
    <context:annotation-config />
    <!--  tell spring where to find the beans -->
    <context:component-scan base-package="zz.yy.abcd" />
    

    귀하의 응용 프로그램 context.xml 비트?

    또한 이런 종류의 설정으로 jta 트랜잭션 유형을 사용할 수 있을지 잘 모르겠습니다. 데이터 소스에서 관리하는 연결 풀이 필요하지 않습니까? RESOURCE_LOCAL을 대신 사용해보십시오.

  2. ==============================

    2.나는 혼란스러워. PU를 지속 레이어가 아닌 서비스 레이어에 삽입하고 있습니까? 나는 그것을 얻지 못한다.

    나는 혼란스러워. PU를 지속 레이어가 아닌 서비스 레이어에 삽입하고 있습니까? 나는 그것을 얻지 못한다.

    나는 서비스 레이어에 지속 레이어를 삽입한다. 서비스 계층은 비즈니스 로직을 포함하고 트랜잭션 경계를 구분합니다. 트랜잭션에 둘 이상의 DAO를 포함 할 수 있습니다.

    나는 당신의 save () 메소드에서 마법을 얻지 못한다. 데이터는 어떻게 저장됩니까?

    프로덕션에서는 다음과 같이 스프링을 구성합니다.

    <jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/ThePUname" />
    

    web.xml의 참조와 함께

    단위 테스트를 위해서 나는 이것을한다 :

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        p:dataSource-ref="dataSource" p:persistence-xml-location="classpath*:META-INF/test-persistence.xml"
        p:persistence-unit-name="RealPUName" p:jpaDialect-ref="jpaDialect"
        p:jpaVendorAdapter-ref="jpaVendorAdapter" p:loadTimeWeaver-ref="weaver">
    </bean>
    
  3. ==============================

    3.누구나 xml 구성에서 hibernate 대신 순수하게 Java 구성을 사용하려면 다음을 사용하십시오.

    누구나 xml 구성에서 hibernate 대신 순수하게 Java 구성을 사용하려면 다음을 사용하십시오.

    다음과 같이 Spring 내에서 persistence.xml을 전혀 사용하지 않고 Hibernate를 설정할 수있다.

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
    {
    Map<String, Object> properties = new Hashtable<>();
    properties.put("javax.persistence.schema-generation.database.action",
    "none");
    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); //you can change this if you have a different DB
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(adapter);
    factory.setDataSource(this.springJpaDataSource());
    factory.setPackagesToScan("package name");
    factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
    factory.setValidationMode(ValidationMode.NONE);
    factory.setJpaPropertyMap(properties);
    return factory;
    }
    

    persistence.xml을 사용하지 않으므로 데이터 소스를 설정하는 위의 메소드에서 지정한 DataSource를 리턴하는 bean을 작성해야한다.

    @Bean
    public DataSource springJpaDataSource()
    {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUrl("jdbc:mysql://localhost/SpringJpa");
    dataSource.setUsername("tomcatUser");
    dataSource.setPassword("password1234");
    return dataSource;
    }
    

    그런 다음이 구성 파일에 대해 @EnableTransactionManagement 주석을 사용합니다. 이제 그 주석을 넣으면 마지막 빈 하나를 만들어야합니다.

    @Bean
    public PlatformTransactionManager jpaTransactionManager()
    {
    return new JpaTransactionManager(
    this.entityManagerFactoryBean().getObject());
    }
    

    DB를 다루는 메소드에 @Transactional Annotation을 사용하는 것을 잊지 마십시오.

    마지막으로 저장소에 EntityManager를 삽입하는 것을 잊지 마십시오 (이 저장소 클래스에는 @Repository 주석이 있어야 함).

  4. ==============================

    4.JPA / Hibernate & Spring을 사용하여 테스트 응용 프로그램을 설정하고 데이터 소스를 만들고이를 EntityManagerFactory에 삽입하고 persistenceUnit에서 데이터 소스로 데이터 소스 특정 속성을 이동하는 구성을 미러링합니다. 이 두 가지 작은 변화로 내 EM이 제대로 주입됩니다.

    JPA / Hibernate & Spring을 사용하여 테스트 응용 프로그램을 설정하고 데이터 소스를 만들고이를 EntityManagerFactory에 삽입하고 persistenceUnit에서 데이터 소스로 데이터 소스 특정 속성을 이동하는 구성을 미러링합니다. 이 두 가지 작은 변화로 내 EM이 제대로 주입됩니다.

  5. ==============================

    5.이것은 오래된 것일지도 모르지만 누구나 똑같은 문제가 있다면 PersistenceContext 어노테이션에서 unitname을 단지 이름으로 변경해보십시오 :

    이것은 오래된 것일지도 모르지만 누구나 똑같은 문제가 있다면 PersistenceContext 어노테이션에서 unitname을 단지 이름으로 변경해보십시오 :

    에서

    @PersistenceContext(unitName="educationPU")
    

    @PersistenceContext(name="educationPU")
    
  6. from https://stackoverflow.com/questions/1132565/spring-jpa-and-persistence-xml by cc-by-sa and MIT license