Spring Integrated MyBatis (Hibernate) configuration

Source: Internet
Author: User

First, spring integrated configuration MyBatis

Spring consolidation MyBatis can be used without the need for a mybatis-config.xml profile, directly through the spring configuration file. A few basic configurations are generally required.

  1. Configure the data source (the most basic configuration of the connection database, such as database URL, account number, password, and database driver, etc.)

1 <!--Import Properties Profile--2     <context:property-placeholder location= "Classpath*:/jdbc.properties"/ > 3  4     <!--data source basic configuration--5     <bean id= "DataSource" class= " Org.springframework.jdbc.datasource.DriverManagerDataSource "> 6          <property name=" username "value=" ${ Jdbc.username} "/> 7          <property name=" password "value=" ${jdbc.password} "/> 8          <property name=" url " Value= "${jdbc.url}"/> 9          <property name= "Driverclassname" value= "${jdbc.driverclassname}"/>10     </bean>

We write the parameter configuration uniformly to the Jdbc.properties file:

1 jdbc.url=jdbc:mysql://localhost:3306/mydb2 jdbc.driverclassname=com.mysql.jdbc.driver3 Jdbc.username=root4 Jdbc.password=root

  2. Configuring Sessionfactory (for managing and initializing the Mapper mapping files for data sources and MyBatis)

1 <!--Create sessionfactory-->2     <bean id= "sqlsessionfactory" class= " Org.mybatis.spring.SqlSessionFactoryBean ">3         <property name=" DataSource "         ref=" DataSource "/>4 <!--scanning mapper mapping file-->5         <property name= "mapperlocations" value= "classpath*:d ao/mapping/*.xml"/>6     </bean>

  3. Scan the mapper mapping file for the DAO Interface class (actually DAO interface is the implementation class is the Mapper.xml mapping file, this configuration is to initialize the interface and the mapping file)

1 <!--scan the DAO interface class corresponding to the mapper mapping file-->2     <bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" >3         <property name= "basepackage" value= "Dao.daointerface"/>4         <property name= " Sqlsessionfactorybeanname "value=" sqlsessionfactory "/>5     </bean>

  4. Create transactions (transactions are configured in two ways: annotation and AOP cut-in)

1 <!--Create transaction management-->2     <bean id= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager ">3         <property name=" DataSource "ref=" DataSource "/>4     </bean>

Once the transaction management has been created, we have the option of using annotations to implement management, or AOP weaving management

    4.1 Annotation Methods

1 <!--Annotated transaction configuration, starting transaction annotations driver-->2 <tx:annotation-driven/>

Annotation configuration You start the transaction note driver through the configuration file, and then add the transaction annotations on the method that you want to add the transaction to:@Transactional (propagation = Propagation.required,isolation = isolation.read_committed) transaction-related knowledge can be consulted: http://www.cnblogs.com/caijh/p/7724964.html

1 @Transactional (propagation = Propagation.required,isolation = isolation.read_committed)2     @Override3 Public     void Insertuser (Userentity userentity) {4 for         (int i=0;i<10;i++) {5             Userentity.setid (111+i); 6             userentity.setusername ("MyBatis" +i), 7             userdao.insertuser (userentity); 8         }9     }

    4.2 AOP weave in style

1 <!--AOP Plunge transaction Configuration-2     <tx:advice id= "Tradvice" transaction-manager= "TransactionManager" > 3         < Tx:attributes> 4             <tx:method name= "*" propagation= "REQUIRED" isolation= "read_committed"/> 5         </tx :attributes> 6     </tx:advice> 7  8     <aop:config> 9         <aop:pointcut id= "Serviceadvice" expression= "Execution (* service.serviceimpl.*.* (..))" />10         <aop:advisor advice-ref= "Tradvice" pointcut-ref= "Serviceadvice"/>11     </aop:config>

AOP related knowledge can be consulted: http://www.cnblogs.com/caijh/p/7710725.html

The final configuration is as follows:

<?xml version= "1.0" encoding= "UTF-8"?><!--~@ (#) Applicationcontext.xml~ <br> Copyright:copyright (c) ~ <br>@author cjh~ <br> 2017-10-29 15:45:16--><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:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://Www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.3.xsdhttp//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.3.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-4.3.xsd"><!--Import Properties profile--<context:property-placeholder location= "classpath*:/jdbc.properties"/> <!- -Scan Note Pack--<context:component-scan base- Package= "Dao.daointerface"/> <context:component-scan base- Package= "Service.serviceimpl"/> <!--data source basic configuration--<bean id= "DataSource"class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name= "username" value= "${jdbc.use Rname} "/> <property name=" password "value=" ${jdbc.password} "/> <property name=" url "value=" ${j Dbc.url} "/> <property name=" driverclassname "value=" ${jdbc.driverclassname} "/> </bean> <!- -Create Sessionfactory--<bean id= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property name= "dataSource" ref= "DataSource"/> <!-- Scan Mapper Mapping file--<property name= "mapperlocations" value= "classpath*:d ao/mapping/*.xml"/> </bean&gt    ; <!--scan the DAO interface class that corresponds to the mapper mapping file--<beanclass= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "basepackage" value= "Dao.daointerface" /> <property name= "sqlsessionfactorybeanname" value= "Sqlsessionfactory"/> </bean> <!--create transaction Manage-<bean id= "TransactionManager"class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name= "DataSource" ref= " DataSource "/> </bean> <!--Annotated transaction configuration, start transaction annotations driven-<!--<tx:annotation-driven/>--> < !--AOP Plunge Transaction Configuration--<tx:advice id= "Tradvice" transaction-manager= "TransactionManager" > <tx:attributes > <tx:method name= "*" propagation= "REQUIRED" isolation= "read_committed"/> </tx:attributes&gt    ; </tx:advice> <aop:config> <aop:pointcut id= "Serviceadvice" expression= "Execution (* Service.servic Eimpl.*.* (..)) " /> <aop:advisor advice-ref= "Tradvice" pointcut-ref= "Serviceadvice"/> </aop:config></beans>

Ssmdemo Integration Configuration Source location: Https://gitee.com/codecaijh/SSMDemo

Two, spring integration configuration Hibernate

Spring integration configuration Hibernate and MyBatis configuration is similar, the main difference in the management configuration with sessionfactory and mapping files, but the purpose is the same.

  1. Configure the data source (the most basic configuration of the connection database, such as database URL, account number, password, and database driver) "with MyBatis Configuration"

2. Configure Sessionfactory (because hibernate encapsulates database operations, so some additional property configuration is required)

 1 <!--created Sessionfactory--2 <bean id= "sessionfactory" class= "Org.springframework.orm.hibernate5.LocalSessi Onfactorybean "> 3 <property name=" DataSource "ref=" DataSource "/> 4 <property name=" Hibernatepr                 Operties "> 5 <props> 6 <prop key=" Hibernate.show_sql ">true</prop> 7 <prop key= "Hibernate.format_sql" >true</prop> 8 <prop key= "Hibernate.dialect" > Org.hibernate.dialect.mysql5dialect</prop> 9 <!--<prop key= "Hibernate.current_session_context_         Class ">org.springframework.orm.hibernate5.springsessioncontext</prop>-->10 </props>11 </property>12 <!--entity class mapping file-->13 <property name= "Mappinglocations" >14 < List>15 <value>classpath*:/domain/*.hbm.xml</value>16 </list>17 &      Lt;/property>18   <!--scan entity class package-->19 <property name= "Packagestoscan" >20 <value>domain</value>2             1 </property>22 <!--entity class-->23 <property name= "annotatedclasses" >24 <list>25 <value>domain. userentity</value>26 </list>27 </property>28 </bean>

Hibernate configuration, the mapping file and entity class mappings are all configured in Sessionfactory, which is similar to MyBatis 2nd and 3rd steps,

  3. Create transactions (transactions are configured in two ways: annotation mode and AOP cut-in) "with MyBatis Configuration"

The final configuration is as follows:

<?xml version= "1.0" encoding= "UTF-8"?><!--~@ (#) Applicationcontext.xml~ <br> Copyright:copyright (c) ~ <br>@author cjh~ <br> 2017-10-29 15:45:16--><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:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:context= "Http://www.springframework.org/schema/context"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://Www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.3.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.3.xsd"><!--Import Properties profile--<context:property-placeholder location= "classpath*:/jdbc.properties"/> <!- -Scan Note Pack--<context:component-scan base- Package= "Dao.daoimpl"/> <context:component-scan base- Package= "Service.serviceimpl"/> <!--data source basic configuration--<bean id= "DataSource"class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name= "username" value= "${jdbc.use Rname} "/> <property name=" password "value=" ${jdbc.password} "/> <property name=" url "value=" ${j Dbc.url} "/> <property name=" driverclassname "value=" ${jdbc.driverclassname} "/> </bean> <!- -Create Sessionfactory--<bean id= "Sessionfactory"class= "Org.springframework.orm.hibernate5.LocalSessionFactoryBean" > <property name= "dataSource" ref= "DataSource" /> <property name= "hibernateproperties" > <props> <prop key= "hibernate.s How_sql ">true</prop> <prop key= "Hibernate.format_sql" >true</prop> <prop key= "Hibernate.dialect" >org.hibernate.dialect.MySQL5Dialect</prop> <!--<prop key= "Hibernate.current_session_context_class" > Org.springframework.orm.hibernate5.springsessioncontext</prop>--> </props> </property&        Gt <!--entity class mapping file--<property name= "mappinglocations" > <list> <value&gt ; classpath*:/domain/*.hbm.xml</value> </list> </property> <!--scanning entity class Pack--<property        Name= "Packagestoscan" > <value>domain</value> </property> <!--entity class-- <property name= "annotatedclasses" > <list> <value>domain.    userentity</value> </list> </property> </bean> <!--Create declarative transaction Management- <bean id= "TransactionManager" class= "Org.springframework.orm.hibernate5.HibernateTransactionManager" > <p Roperty name= "Sessionfactory" ref= "Sessionfactory"/> </bean> <!--transaction notification (annotated)--<tx:annotation -driven transaction-manager= "TransactionManager"/> <!--transaction notification (AOP mode)-<!--<tx:advice id= "Txadvice" Transaction-manager= "TransactionManager" > <tx:attributes> &lt;! &ndash;   Propagation configuring propagation behavior, Isolation configuring isolation mode &ndash;&gt;         <tx:method name= "*" propagation= "REQUIRED" isolation= "read_committed"/> </tx:attributes> & Lt;/tx:advice> &lt;! &ndash;    AOP Weaving Notifications &ndash;&gt; <aop:config> <aop:pointcut id= "serviceoption" expression= "(Execution (* service.serviceimpl.*.* (..)) and (E Xecution (* dao.daoimpl.*.* (..)))) " /> <aop:advisor advice-ref= "Txadvice" pointcut-ref= "serviceoption"/> </aop:config>--></bean S>

Sshdemo Integration Configuration Source location: Https://gitee.com/codecaijh/SSHDemo

Iii. problems that may be encountered

You may encounter Bindingexception:invalid bound statement (not found) when consolidating MyBatis: Dao.daoInterface.UserDao.getUserInfo The DAO interface class and the mapper file binding failed to find an exception for the implementation method.

  

When I look at the classes file under the target directory, we find that there is no XML file, and it may not be included in the project compilation.

  Workaround:

Add the following to the Pom.xml file: (indicates that MAVEN will load files that are suffixed with XML and properties to the target path from the resource path at build time)

1 <build> 2      3       <resources> 4           <resource> 5               <directory>src/main/java</ Directory> 6               <includes> 7                   <include>**/*.properties</include> 8                   <include>** /*.xml</include> 9               </includes>10               <filtering>false</filtering>11           </ resource>12       </resources>13   </build>

Resources are often not code, not compiled, but some properties or XML configuration files, which tend to copy resource files from the source path to the specified destination path during the build process.

Configuration Description :

    • Resource files involved in the Resources,build process
      • TargetPath, the target path of the resource file
      • filtering, whether the resource is filtered during the build process, false by default
      • directory, the path to the resource file, by default in the ${basedir}/src/main/resources/directory
      • Includes, a set of file name matching patterns, the matching resource file will be processed by the build process
      • Excludes, a set of file name matching patterns, the matching resource file will be ignored by the build process. Resource files that are also matched by includes and excludes will be ignored.
    • Filters, the path to the properties file that filters the resource file, is located in the ${basedir}/src/main/filters/directory by default. Several key-value pairs are defined in the properties file. During the build process, the variable (key) that appears in the resource file is replaced with the value corresponding to the key in the property file.
    • The resource files involved in the testresources,test process are located by default in the ${basedir}/src/test/resources/directory. The resource files are not built into the target artifacts.

Reference source link : https://www.cnblogs.com/caijh/p/7755479.html

Blog is to remember that they are easy to forget things, but also a summary of their work, the article can be reproduced, without copyright. Hope to do their own efforts to do better, we work together to improve!

If there is any problem, welcome to discuss together, code if there is a problem, you are welcome to the great God!

Spring Integrated MyBatis (Hibernate) configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.