MyBatis && ssm integrated project

                MyBatis && ssm integrated project

A mapping .mapper
    1. Preparation interfaces EmployeeMapper
    2. Preparation xml EmployeeMapper.xml
    complete 3. tested
two high-level query.
Three configuration relationship (heavy and difficult).
    1. Many-
       1.1 domain prepare
        1.2 relational mapping - Nested Results
        1.3 Relationship mapping - nested query
    2. many configurations
        2.1 to prepare the corresponding domain
        2.2 nested results
        2.3 - nested query
four .SSM three frame integration
   4.1 leader packet
    4.2 the jdbc.properties
    4.3 applicatinContext.xml
expansion:
    many- methods of wild
    -many paging pit

a .mapper mapping

we just need to write an interface, implemented by MyBatis yourself
fully qualified name of the namespace is consistent with the xml interface in
a consistent id sql the interface method name of the xml

1. ready interfaces EmployeeMapper

Package Penalty for cn.itsource._01_mapper.mapper;
...
{interface EmployeeMapper public
    the Employee findOne (Long the above mentioned id);
    // @ the Select ( "the SELECT * from the Employee"): too complicated to solve the
    List <the Employee> findAll ();
}

2. EmployeeMapper.xml ready xml

<xml Version =? ? "1.0" encoding = "UTF-8">
! <DOCTYPE Mapper the PUBLIC "- // mybatis.org//DTD Mapper 3.0 // EN"
    "http://mybatis.org/dtd/mybatis-3-mapper. DTD ">

<-! ID corresponding to the required and where the method name ->
<SELECT ID =" the findOne "the parameterType =" Long "the resultType =" cn.itsource._01_mapper.domain.Employee ">
    SELECT * wHERE from Employee ID {ID} # =
</ SELECT>

<-! Search ->
<SELECT ID = "the findAll" the resultType = "cn.itsource._01_mapper.domain.Employee ">
    SELECT * from Employee
</ SELECT>


3. completion of the test

@Test
public void testMapper () throws Exception {
    . // get the session object. 1
    the SqlSession MyBatisUtils.openSession session = ();
    . 2 // get achieve the mapper (MyBatis automatically help us to achieve the function)
    EmployeeMapper = mapper session. getMapper (EmployeeMapper.class);
    .. 3 // direct execution method of
    the Employee Employee = mapper.findOne (1L);
    System.out.println (Employee);

    Session.close ();
}

structure as shown

two advanced query

fuzzy query using concat concat ( "%", # {name}, "%")
special characters or escape CDATA sections using
    & lt; representatives of less than
    <[CDATA [...]]! >
each condition is determined if required (this condition has before filtration)
    `<= IF Test" a condition and / or condition II ">
together prior to filtration where, the first and replace where
if encountering repeated sQL, you can use it to sql tag out to

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--准备一个代码块-->
<sql id="whereSql">
    <where>
        <if test="name!=null and name!=''">
            and name like concat("%",#{name},"%")
        </if>
        <if test="minAge!=null">
            and age >= #{minAge}
        </if>
        <if test="maxAge!=null">
            <![CDATA[
               and age <= #{maxAge}
             ]]><-! query total number of data -></ SQL>    </ the WHERE>
        </ IF>




<the SELECT the above mentioned id = "getCount" resultType = "Long" parameterType = "cn.itsource._01_mapper.query.EmployeeQuery">
  the SELECT COUNT (*) from the Employee
  <refid the include = "whereSql" />
</ the SELECT>
<! -
    query phrase condition
        CDATA: data area is not recognized as a syntax
 ->
<SELECT ID = "queryAll" the parameterType = "cn.itsource._01_mapper.query.EmployeeQuery"
        the resultType = "cn.itsource._01_mapper.domain. the Employee ">
    SELECT * from Employee
    <= the include the refid" whereSql "/>
</ SELECT>

<-! id required here and the corresponding method name ->
<SELECT id =" the findOne "the parameterType =" Long "= the resultType" cn.itsource._01_mapper.domain.Employee">
    select * from employee where id= #{id}
</select>

<!--查询所有-->
<SELECT ID = "the findAll" the resultType = "cn.itsource._01_mapper.domain.Employee">
    SELECT * from Employee
</ SELECT>

Relationship of the configuration (heavy and difficult)
1. Many-
1.1 domain preparation

Product

public class Product {

Long ID Private;
Private String name;
// many to one (corresponding to a plurality of product classification)
Private ProductDir the dir;

// gettersetter with toString omitted

ProductDir

public class ProductDir {

Private Long ID;
Private String name;
// gettersetter omitted and toString

}

1.2 relational mapping - the nested results

of a SQL query all data (prone to the same column name, so we try to take the time to develop the appropriate aliases for these columns), mybatis again to help us sort out the data.

ResultMap mapping necessary to use manual
shut association object is connected for
    automatically disabling the use of the mapped
    object attributes individually configured

<! -
    Write your own code completion manually map
    resultMap: the results of the mapping id: Name type: mapping object types
        result: Mapping property certain attributes: type attribute column: columns in a table
    association: association (if you are connected to an object to use it) -> automatic mapping on the failure
            property: property name column: column name javaType: type attribute of
            property, column: these two things can make the name correspond
            javaType plus inside the label: the type corresponds to the type of data inside
        understanding: in Product ProductDir object has a property of type: dir, dir that there are two attributes, one id (query results corresponding to DID), is a name, ...
->
<the resultMap ID = "productMap" type = "cn.itsource._02_many2one_result.Product">
    <Property ID = "ID" column = "ID" />
    <Property Result = "name" column = "name" />
    <Property = Association "the dir" the javaType = "CN. itsource._02_many2one_result.ProductDir ">
        <id property="id" column="did" />
        <Property Result = "name" column = "DNAME" />
    </ Association>
</ The resultMap>

<-!
    The resultMap: find the corresponding manual mapping
->
<SELECT ID = "the findAll" The resultMap = "productMap">
   SELECT p.id, p.name, dir.id DID, from t_product P dir.name DNAME
        the LEFT the JOIN t_productdir the dir
        the ON dir.id p.dir_id =
</ SELECT>

1.3 relational mapping - nested queries

to prepare a SQL query to the data , and then to find the foreign key data corresponding to the query object

<XML Version = "1.0" encoding = "UTF-. 8"??>
<DOCTYPE Mapper the PUBLIC "-! // 3.0 // EN mybatis.org//DTD Mapper "
    " http://mybatis.org/dtd/mybatis-3-mapper.dtd ">

<-! manual map ->
<The resultMap ID ="productMap" type="cn.itsource._03_many2one_search.Product">
    <id property="id" column="id" />
    <the Result Property = "name" column = "name" />
    ! <- setting related mapping
        select = "findDirById": find the corresponding query
            if the call is another xml query: select = "namespace .id value "
    ->
    <Property = Association" the dir "column =" dir_id "SELECT =" findDirById "
                 the javaType =" cn.itsource._03_many2one_search.ProductDir "> </ Association>
</ the resultMap>

<-! id obtained according to to the corresponding type parameterType = "long" is a value obtained in the column ->
<SELECT ID = "findDirById" parameterType = "long" the resultType = "cn.itsource._03_many2one_search.ProductDir">
    SELECT * WHERE ID from t_productdir {ID} # =
</ SELECT>

<SELECT ID = "the findAll "The resultMap =" productMap ">
  SELECT * from t_product
</ SELECT>

2. many configurations
2.1 to prepare the corresponding domain

Product

public class Product {

Private Long ID;
Private String name;
// gettersetter with toString omitted

ProductDir

public class ProductDir {

Private Long ID;
Private String name;
 // many: a plurality of product types corresponding to the
private List <Product> products the ArrayList new new = <> ();
// with toString omitted gettersetter

}

2.2 nested results

<?? XML Version = "1.0" encoding = "UTF-. 8">
! <DOCTYPE Mapper the PUBLIC "- // mybatis.org// Mapper 3.0 // EN the DTD "
    " http://mybatis.org/dtd/mybatis-3-mapper.dtd ">

<-!
    manual mapping association: representative of an object is related to
        collection: set (get multi): after use automatic mapping failure
            property: property name
            ofType:This attribute representative of each object type
->
<resultMap id="productDirMap" type="cn.itsource._04_one2many_result.ProductDir">
    <id property="id" column="id" />
    <result property="name" column="name" />
    <collection property="products" ofType="cn.itsource._04_one2many_result.Product">
        <id property="id" column="pid" />
        <result property="name" column="pname" />
    </collection>
</resultMap>

<select id="findAll" resultMap="productDirMap">
    select dir.id,dir.name,p.id pid,p.name pname from t_productdir dir LEFT JOIN t_product p
      ON p.dir_id = dir.id
</ the SELECT> <DOCTYPE Mapper the PUBLIC! "- // mybatis.org//DTD Mapper 3.0 // EN"<xml Version = "1.0" encoding = "UTF-8">??

2.3 - nested query



    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<-!
    manual mapping association: representative of an object is related to
        collection: set (get multi): after failure using automatic mapping
            property: attribute name
            ofType: this attribute representative of each object type
            select: to obtain the corresponding the SQL
->
<the resultMap ID = "productDirMap" type = "cn.itsource._05_one2many_search.ProductDir">
    <property ID = "ID" column = "ID" />
    <Property Result = "name" column = "name" />
    <= Collection Property "Products" column = "ID" SELECT = "getProductByDirId"
                ofType = "cn.itsource._05_one2many_search.Product">
    < / Collection>
</resultMap>

<select id="getProductByDirId" parameterType="long" resultType="cn.itsource._05_one2many_search.Product">
    * WHERE dir_id from t_product SELECT = # {ID}
</ SELECT>

<SELECT ID = "the findAll" The resultMap = "productDirMap">
    SELECT * from t_productdir
</ SELECT>

four .SSM three integrated frame

①. pack guide
②. Basic building structure
③. integration step

the db.properties
the dataSource
a SqlSessionFactory
mapper mapper
mapper,-Service
the TX transaction
the controller
4.1 leader packet

Spring package, Spring dependencies, SpringMVC packet (JSON support package), mybatis packet, mybatis integration with Spring package Image

4.2 jdbc.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc: MySQL: /// the mybatis
jdbc.username = root
jdbc.password = 123456

4.3 applicatinContext.xml

<xml Version = "1.0? "encoding ="UTF-8"?>

<!--扫描service-->
<context:component-scan base-package="cn.itsource.ssm.service" />

<!--
    ①.jdbc.properties -> ②.DataSource -> ③.SqlSessionFactory -> ④.Mapper实现
        -> ⑤.Service/TX事务 -> ⑥.集成SpringMVC
-->
<!--引入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--创建dataSource-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<!--
    Configuring a SqlSessionFactory -> the SqlSessionFactoryBean
->
<the bean ID = "SqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
    <-! Connection pool ->
    <Property name = "the dataSource" REF = "the dataSource" />
    <Property name = "the mapperLocations" value = "CLASSPATH: CN / itsource / SSM / Mapper / Mapper.xml *" />
    <- typeAliasesPackage:! value of this packet will take the appropriate alias ->
    <Property name = "typeAliasesPackage">
        <value>
            cn.itsource.ssm.domain
            cn.itsource.ssm.query
        </ value>
    </ Property>
</ the bean>

<!-
    Let us help generate Spring Mapper
    mapperInterface: represents the type of interface you want to map
<bean id = "employeeMapper" class = "org.mybatis.spring.mapper.MapperFactoryBean">
    <Property name = "SqlSessionFactory" REF = "SqlSessionFactory" />
    <Property name = "mapperInterface" value = "cn.itsource.ssm.mapper.EmployeeMapper" />
</ the bean>
->

<-! once
    Mapper ( mapping) Scanner (scan) Configurer (configuration)
    basePackage: scanning packages (object classes will be used to create an implementation)
->
<the bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
    <Property name = "basePackage "value =" cn.itsource.ssm.mapper "/>
</ bean>


<! - transaction configuration ->
<! - configure transaction Manager ->
<bean the above mentioned id =" transactionManager "class =" ORG. springframework.jdbc.datasource.DataSourceTransactionManager ">
    <Property name ="dataSource "ref =" dataSource "/>
</ bean>
<-! open transaction annotation support, will go a default name is called transactionManager Transaction Manager ->
<tx:annotation-driven transaction-manager="transactionManager" />

扩展
多对一映射的野方法

<?xml version="1.0" encoding="UTF-8" ?>
<resultMap id="productMap" type="cn.itsource._06_many2one_haha.Product">
    <result property="dir.id" column="did" />
    <result property="dir.name" column="dname" />
</resultMap>

<!--
    resultMap:找到对应的手动映射
-->
<select id="findAll" resultMap="productMap">
   select p.id,p.name,dir.id did,dir.name dname from t_product p
        LEFT JOIN t_productdir dir
        ON dir.id = p.dir_id
</select>


Guess you like

Origin www.cnblogs.com/1999wang/p/11392071.html