Spring集成JPA的配置

时间:2021-03-19 20:33:37

1.在src类路径下配置一个META-INF文件,再在文件下建一个persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- example of a default 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="itcast" transaction-type="RESOURCE_LOCAL">
           <provider>org.hibernate.ejb.HibernatePersistence</provider>
       
        <properties>
//这里就不要再写url,username,password,driver了,应为在beans.xml 配置了数据源dataSource,如果这里在配了就会发生异常

org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.UnsupportedOperationException: Not supported by BasicDataSource
 
Caused by: java.lang.UnsupportedOperationException: Not supported by BasicDataSource

  

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.max_fetch_depth" value="3"/>
            <property name="hibernate.jdbc.fetch_size" value="18"/>
            <property name="hibernate.jdbc.batch_size" value="10"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="false"/>
            
        </properties>
    </persistence-unit>

</persistence>

2.在src下建一个beans.xml和jdbc.properties

beans.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:aop="http://www.springframework.org/schema/aop"  
       xmlns:tx="http://www.springframework.org/schema/tx"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-2.5.xsd  
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
  //这里需要注意的是你要使用spring的注解的包的位置,如果这里不是saleLong那么saleLong下使用spring注解的bean将不会注入到spring容器内
    <context:component-scan base-package="saleLong"/>     
      
  
<context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
        <property name="driverClassName" value="${driverClassName}"/>  
        <property name="url" value="${url}"/>  
        <property name="username" value="${username}"/>  
        <property name="password" value="${password}"/>  
        <property name="initialSize" value="${initialSize}"/>  
        <property name="maxActive" value="${maxActive}"/>  
        <property name="maxIdle" value="${maxIdle}"/>  
        <property name="minIdle" value="${minIdle}"/>  
    
    </bean>  
          
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />  
        <property name="persistenceUnitName" value="itcast"/>  
            <property name="loadTimeWeaver">  
              <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>  
           </property>  
    </bean>  
 <!--   
   <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">  
        <property name="persistenceUnitName" value="itcast"/>  
   </bean>  
-->  
   <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">  
        <property name="entityManagerFactory" ref="entityManagerFactory"/>  
   </bean>  
     
    <!-- Activates @Transactional for DefaultImageDatabase -->  
   <tx:annotation-driven transaction-manager="transactionManager"/>  
      
</beans>  

jdbc.properties

driverClassName=org.gjt.mm.mysql.Driver
url=jdbc:mysql://127.0.0.1:3306/itcast 

//要注意这里的写法,最好去copy

Cannot create JDBC driver of class 'org.gjt.mm.mysql.Driver' for connect URL 'jdbc:mysql//127.0.0.1:3306/itcast'

先检查url是否写对,在检查是否导入了数据库的驱动包
username=root
password=root
initialSize=1
maxActive=100
maxIdle=8
minIdle=1

3.测试

建一个SaveService类

package saleLong.service;

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


import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import saleLong.bean.product.product;



@Service()
@Transactional
public class SaveService {
    @PersistenceContext EntityManager em;
    public void save(){
        em.persist(new product("小黄"));
        System.out.println("保存成功");
    }
    
}


在建一个Spring_jpa_test

package junit.test;

import static org.junit.Assert.*;

import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.jpa.JpaTransactionManager;

import saleLong.service.SaveService;


public class Spring_JPA_Test {

    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        System.out.println(ctx.getBean("transactionManager"));
        SaveService s=(SaveService)ctx.getBean("saveService");
        s.save();
        
        
    }

}


测试save成功