Problem resolution for integration of Spring jpa and mybatis
- 2020-05-10 18:05:25
- OfStack
A while ago, I took over a project developed by SpringBoot and spring-data-jpa. In the later stage, I added a new partner, which indicated that jpa was more difficult to use than mybatis, and it was difficult to write multi-table queries, so I added the support of mybatis
In the beginning
@Configuration
@EnableJpaRepositories("com.xxx.xxx.repository")
class JpaConfig
The configuration of jpa in this way encountered a problem, that is, it can select but cannot save, so it was modified to the configuration file:
Go directly to the configuration file below:
1. Configuration of spring
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<!-- Scan annotation file -->
<context:component-scan base-package="com.xxx"/>
<task:annotation-driven/>
<bean id="springContextHolder" class="com.xxx.common.config.SpringContextHolder"
lazy-init="false"></bean>
<bean id="configProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:jdbc.properties</value>
<value>classpath*:app.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="fileEncoding" value="UTF-8"/>
<property name="properties" ref="configProperties"/>
</bean>
<!-- dataSource configuration -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
destroy-method="close">
<!-- Basic attributes url , user , password -->
<!-- <property name="driverClassName" value="${ds.driverClassName}" /> -->
<property name="url" value="${ds.url}"/>
<property name="username" value="${ds.username}"/>
<property name="password" value="${ds.password}"/>
<!-- Configure the initial size, minimum, and maximum -->
<property name="initialSize" value="${ds.initialSize}"/>
<property name="minIdle" value="${ds.minIdle}"/>
<property name="maxActive" value="${ds.maxActive}"/>
<!-- Configure to get the time for the connection wait timeout -->
<property name="maxWait" value="${ds.maxWait}"/>
<!-- How long is the configuration interval 1 A secondary detection that detects idle connections that need to be closed in milliseconds -->
<property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/>
<!-- configuration 1 The minimum time a connection can live in a pool, in milliseconds -->
<property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/>
<property name="validationQuery" value="${ds.validationQuery}"/>
<property name="testWhileIdle" value="${ds.testWhileIdle}"/>
<property name="testOnBorrow" value="${ds.testOnBorrow}"/>
<property name="testOnReturn" value="${ds.testOnReturn}"/>
<!-- Open the PSCache , and specify each connection PSCache The size of the -->
<property name="poolPreparedStatements" value="${ds.poolPreparedStatements}"/>
<property name="maxPoolPreparedStatementPerConnectionSize"
value="${ds.maxPoolPreparedStatementPerConnectionSize}"/>
<!-- Configure monitoring statistics intercept filters -->
<property name="filters" value="${ds.filters}"/>
<!-- Shut down abanded Output error log while connecting -->
<property name="logAbandoned" value="${ds.logAbandoned}"/>
</bean>
<!-- spring and MyBatis Perfect integration, no need mybatis Configuration mapping file -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="typeAliasesPackage" value="com.xxx.culture.domain"/>
<!-- Automatic scanning mapping.xml file -->
<property name="mapperLocations" value="classpath:mapper/**/*.xml"/>
</bean>
<!-- DAO The package name of the interface, Spring It automatically looks for the class below it -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxx.xxx.dao"/>
</bean>
<!-- ( Transaction management )transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- Transaction management notice -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- right insert,update,delete The first method does transaction management , Roll back whenever there is an exception -->
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="flush*" propagation="REQUIRED"/>
<!-- select,count,get,find Opening method , Open read-only , Improved database access performance -->
<tx:method name="select*" read-only="true"/>
<tx:method name="count*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="search*" read-only="true"/>
<!-- For other methods Use the default transaction management -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- The transaction aop configuration com.xxx.smp.service..*Impl.*(..)) -->
<aop:config>
<aop:pointcut id="serviceMethods"
expression="execution(* com.xxx.xxx.service..*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
</aop:config>
<!-- Configuration to make Spring using CGLIB The agent -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- Transaction annotation support -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<import resource="applicationContext-jpa.xml"/>
</beans>
2. Configuration of jpa
Initially, there was a problem: jpa org.hibernate.LazyInitializationException: could not proxy proxy no Session
Configuration is as follows
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" >
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- Specify data source -->
<property name="dataSource" ref="dataSource"/>
<!-- The specified Entity Entity class package path -->
<property name="packagesToScan">
<list>
<value>com.xxx.xxx.jpadomain</value>
</list>
</property>
<!-- The specified JPA Properties; Such as Hibernate Specifies whether to display SQL Whether to display, dialect, etc -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- Whether to generate ddl file -->
<property name="generateDdl" value="true"/>
<!-- Whether to show sql -->
<property name="showSql" value="false"/>
<!-- Details of the necessary database library usage -->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
<!-- mysql, To choose -->
<property name="database" value="MYSQL"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy
</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
<!-- Spring Data Jpa configuration -->
<!-- configuration Enable the ability to scan and automatically create agents factory-class="com.monk.base.jpa.PeakJpaRepositoryFactory" self-defined bean Annotation method, can not write, directly annotate all packages under -->
<jpa:repositories base-package="com.xxx.xxx.repository"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"/>
<!-- Jpa Transaction configuration -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Open annotation transaction -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
</beans>