MyBatis Entry 2nd day--mybatis and Spring integration and reverse engineering

Source: Internet
Author: User

Document Version Development Tools Test Platform Project Name Date author Notes
V1.0 2016.06.28 Lutianfei None
Spring and MyBatis integration
    • Integration Ideas

      • Spring is required to manage sqlsessionfactory in a single case.
      • Spring and MyBatis Consolidate build proxy objects and use Sqlsessionfactory to create sqlsession. (Spring and MyBatis Integration Auto-complete)
      • The mapper of the persistence layer needs to be managed by spring.
    • Integrated environment

    • Create a new Java project (close to the actual development of the engineering structure)
    • Jar Package:

      • MYBATIS3.2.7 's jar Package
      • SPRING3.2.0 's jar Package
      • MyBatis and Spring Integration packages: Early Ibatis and spring consolidation are provided by spring, and now mybatis and spring integration are provided by MyBatis.
      • All jar packages (including SPRINGMVC)
    • Engineering structure

First step: Consolidate configuration sqlsessionfactory
    • Configuring Sqlsessionfactory and data sources in Applicationcontext.xml
      • Sqlsessionfactory is under the integration package for MyBatis and spring.
<!--load configuration files --    <context:property-placeholder location ="Classpath:db.properties" />    <!--data source, using DBCP--    <bean id= "dataSource" class=" Org.apache.commons.dbcp.BasicDataSource "destroy-method=" Close ">                < property name="Driverclassname" value="${jdbc.driver}" />        < property name="url" value="${jdbc.url}" />        < property name="username" value="${jdbc.username}" />         < property name="password" value="${jdbc.password}" />        < property name="maxactive" value="Ten" />        < property name="Maxidle" value="5" />    </Bean>    <!--sqlsessinfactory --    <bean id= "sqlsessionfactory" class=" Org.mybatis.spring.SqlSessionFactoryBean ">        <!--load MyBatis configuration file--        < property name="Configlocation" value="Mybatis/sqlmapconfig.xml" />        <!--data source -        < property name="DataSource" ref="DataSource" />     </Bean>


Original DAO Development (and spring integration)
    • Sqlmap/user.xml

    • Load in Sqlmapconfig.xml user.xml

    • Dao ( Implement class inheritance Sqlsessiondaosupport)

    • Before the DAO interface implementation class needs to be injected sqlsessoinfactory, injected through spring.

    • Here's how to configure DAO's bean using Spring declaration configuration:

      • let Userdaoimpl implement class inheritance Sqlsessiondaosupport
      /li>
    • Configuring DAO

      • Configuring the DAO interface in Applicationcontext.xml
    <!-- 原始dao接口 -->    <bean id="userDao" class="cn.itcast.ssm.dao.UserDaoImpl">        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>    </bean


    • Test program
      • Source_folder/userdaoimpltest.java
 Public  class userdaoimpltest {    PrivateApplicationContext ApplicationContext;//In Setup This method gets the spring container    @Before     Public void setUp()throwsException {ApplicationContext =NewClasspathxmlapplicationcontext ("Classpath:spring/applicationcontext.xml"); }@Test     Public void Testfinduserbyid()throwsException {Userdao Userdao = (Userdao) Applicationcontext.getbean ("Userdao");//method of calling UserdaoUser user = Userdao.finduserbyid (1);    SYSTEM.OUT.PRINTLN (user); }}


Mapper Agent Development
    • Usermapper.xml and Usermapper.java

      • Copy the previous project to remove the package path.
    • Creating a proxy object from Mapperfactorybean

      • Because Usermapper is not an interface type, you use Mapperfactorybean to generate the interface type
    • This method problem:

      • Need to be configured for each mapper, please.
mapper scanning via Mapperscannerconfigurer(recommended)


* basePackage After configuring the Mapper scan path through the properties, the scan path is not configured in Sqlmapperconfig.xml.

    • The sqlSessionFactoryBeanName attribute is used here because the sqlSessionFactory database configuration file and the data source configuration (db.properties) will not be loaded first if the property is configured

    • Test code



Reverse Engineering
    • Mybaits requires programmers to write their own SQL statements, MyBatis official reverse engineering can be automatically generated for a single table MyBatis execute the required code (mapper.java,mapper.xml, PO. )

    • In the enterprise actual development, the commonly used reverse engineering way: Because the database table generates the Java code.

    • Download Reverse Engineering

How to use(Will be used)
    • Run Reverse engineering
    • It is recommended that you use Java programming methods without relying on development tools.

    • Generate a code configuration file (4 places to modify)

      • Where to build the PO class: Cn.itcast.ssm.po
      • Mapper Map File generation location: Cn.itcast.ssm.mapper
      • Location of Mapper interface generation: Cn.itcast.ssm.mapper
      • Specify Database tables:
      <table tableName="items"></table>      <table tableName="orders"></table>      <table tableName="orderdetail"></table>      <table tableName="user"></table>
<?xml version= "1.0" encoding= "UTF-8"?><! DOCTYPE generatorconfiguration Public "-//mybatis.org//dtd mybatis Generator Configuration 1.0//en" "/http Mybatis.org/dtd/mybatis-generator-config_1_0.dtd "><generatorconfiguration>    <context id="Testtables" targetruntime="MyBatis3">        <commentgenerator>            <!--whether to remove automatically generated comments true: Yes: false: No --            < property name="suppressallcomments" value="true" />        </commentgenerator>        <!--database connection information: Driver class, connection address, user name, password- -        <jdbcconnection driverclass="Com.mysql.jdbc.Driver"Connectionurl ="Jdbc:mysql://localhost:3306/mybatis" userId="root"password= "MySQL">                                </jdbcconnection>        <!--<jdbcconnection driverclass= "Oracle.jdbc.OracleDriver" Connectionurl= "jdbc:oracle:thin:@127.0.0. 1:1521:YYCG "userid=" YYCG "password=" YYCG "> </jdbcConnection> --        <!--default False to parse the JDBC decimal and NUMERIC types to Integer, and to resolve the JDBC decimal and NUMERIC types to Java.math.BigDec when True iMAL --        <javatyperesolver>            < property name="Forcebigdecimals" value="false" />         </javatyperesolver>        <!--targetproject: Generate POS Class Location--        <javamodelgenerator targetpackage="Cn.itcast.ssm.po"targetproject= ". \src">                        <!--enablesubpackages: Do you want the schema to be a suffix of the package--            < property name="Enablesubpackages" value="false" / >            <!--The value returned from the database is cleared before and after the space-            < property name="trimstrings" value="true" />        </javamodelgenerator>        <!--targetproject:mapper Map file generated location--        <sqlmapgenerator targetpackage="Cn.itcast.ssm.mapper"targetproject =". \src">                         <!--enablesubpackages: Do you want the schema to be a suffix of the package--            < property name="Enablesubpackages" value="false" />        </sqlmapgenerator>        <!--Targetpackage:mapper interface generated location--        <javaclientgenerator type= "xmlmapper"targetpackage=" Cn.itcast.ssm.mapper "targetproject=". \src ">                                     <!--enablesubpackages: Do you want the schema to be a suffix of the package--            < property name="Enablesubpackages" value="false" />        </javaclientgenerator>        <!--specifying database tables --        <table tableName="items"></table>        <table tableName="Orders"></table>        <table tableName="OrderDetail"></table>        <table tableName="user"></table>    </Context></generatorconfiguration>


    • Executing the Build Program

    • Post-generated code

using the generated code
    • The code generated in the build project needs to be copied to your project.

    • Testing the methods in Itemsmapper

//Custom condition Query    @Test     Public void Testselectbyexample() {Itemsexample itemsexample =NewItemsexample ();//Construct query criteria through criteriaItemsexample.criteria Criteria = Itemsexample.createcriteria (); Criteria.andnameequalto ("Notebook 3");//May return more than one recordlist<items> list = Itemsmapper.selectbyexample (itemsexample);    SYSTEM.OUT.PRINTLN (list); }//Search by primary key    @Test     Public void Testselectbyprimarykey() {Items items = Itemsmapper.selectbyprimarykey (1);    SYSTEM.OUT.PRINTLN (items); }//Insert    @Test     Public void Testinsert() {//Construct Items ObjectItems items =NewItems (); Items.setname ("mobile"); Items.setprice (999f);    Itemsmapper.insert (items); }//Update data    @Test     Public void Testupdatebyprimarykey() {//Update all fields, need to be queried before updatingItems items = Itemsmapper.selectbyprimarykey (1); Items.setname ("Water Cup"); Itemsmapper.updatebyprimarykey (items);//If the incoming field is not empty to update, use this method in a bulk update and do not need to query and update first        //itemsmapper.updatebyprimarykeyselective (record);}

MyBatis Entry 2nd day--mybatis and Spring integration and reverse engineering

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.