MyBatis-Spring project

  Spring IoC can use to effectively manage all types of Java resources, to achieve plug-and-pull functionality; by AOP framework, database transactions can be delegated to Spring, eliminating a large part of the transaction code, with MyBatis is highly flexible, configurable, optimized SQL and other characteristics, can build high-performance large sites.
  Two MyBatis and Spring Framework Java Internet technology has become the mainstream of the frame assembly, they withstood the test of large amounts of data and high-volume requests, it has been widely used in the Internet system. Using MyBatis-Spring makes the service layer and model layer to get a better separation, at the same time, the use of MyBatis in a Spring environment is much easier, saving a lot of code, even without SqlSessionFactory, SqlSession and other objects. Because MyBatis-Spring package them for us.

  Configure MyBatis-Spring projects require such steps:
  • Configure the data source.
  • Configure SqlSessionFactory.
  • You can select SqlSessionTemplate arranged, in the case of SqlSessionTemplate and configure SqlSessionFactory of precedence SqlSessionTemplate.
  • Mapper configuration, you can configure a single Mapper, Mapper may be generated by a scanning method, and more flexible. Spring IoC case generates a corresponding interface instance, so that the resources can be obtained by way of injection.

Configuration SqlSessionFactoryBean

  From the introduction of MyBatis, you can know that is the basis for generating SqlSessionFactory SqlSession, configuring SqlSessionFactory crucial. Provided in MyBatis-Spring project in the SqlSessionFactoryBean to support SqlSessionFactory configuration
  almost you can configure all about the components of MyBatis, and it also provides a corresponding setter methods let Spring set them, so can go to configure them by the rules of the Spring IoC container. Due to the use of third-party packages, in general, we prefer XML configuration.

  Listing: Configuring SqlSessionFactoryBean

<!--配置SqlSessionFactoryBean-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:ssm/chapter12/sqlMapConfig.xml"/>
</bean>

 


  Here configured SqlSesionFactoryBean, but only configure the data source, and then introducing a MyBatis configuration file, of course, if what you configure is simple, can be completely without introducing MyBatis configuration file, you only need to inject by Spring IoC container, but in general, the more complex configurations, I still recommend that you use the MyBatis configuration file, so the advantage will not make SqlSessionFactoryBean all depends on the configuration of Spring provides rules, leading to the complexity of the configuration.

  Listing: MyBatis configuration file --sqlMapConfig.xml

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE the Configuration the PUBLIC "- // mybatis.org//DTD Config 3.0 // EN" "http://mybatis.org/dtd/mybatis config.dtd--3 " > 
< configuration > 
    < Settings > 
        <-! this configuration enables the global map enables or disables caching -> 
        < Setting name =" cacheEnabled " value =" to true " /> 
        <! - allows JDBC support generated keys. You need to drive appropriate. If set to true, then this setting forces generated keys are used, some drivers deny compatibility but still valid (for example the Derby) -> 
        < Setting name = "useGeneratedKeys" value = "to true"
        The default configuration of the actuator. SIMPLE actuator nothing special. REUSE actuator reuse prepared statements. BATCH actuator reusing statements and batch updates   -> 
        < Setting name = "defaultExecutorType" value = "REUSE" /> 
        <-! Globally enable or disable lazy loading. When disabled, all associations will be eagerly loaded -> 
        < Setting name = "lazyLoadingEnabled" value = "to true" /> 
        <-! Set the timeout, it decided to wait for a database driver response time   -> 
        < Setting name = "defaultStatementTimeout" value = "25000" /> 
    </ Settings > 
    <-! alias configuration -> 
    <
        typeAlias alias="role" type="com.ssm.chapter12.pojo.Role"/>
    </typeAliases>
    <!-- 指定映射器路径 -->
    <mappers>
        <mapper resource="ssm/chapter12/mapper/RoleMapper.xml"/>
    </mappers>
</configuration>

 


  Listing: RoleMapper.xml

<?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">
<mapper namespace="com.ssm.chapter12.mapper.RoleMapper">

    <insert id="insertRole" useGeneratedKeys="true" keyProperty="id">
        insert into t_role (role_name, note)
        values (#{roleName}, #{note})
    </insert>

    <delete id="deleteRole" parameterType="long">
        delete
        from t_role
        where id = #{id}
    </delete>

    <select id="getRole" parameterType="long" resultType="role">
        select id, role_name as roleName, note
        from t_role
        where id = #{id}
    </select>

    <update id="updateRole" parameterType="role">
        update t_role
        set role_name = #{roleName},
            note      = #{note}
        where id = #{id}
    </update>

</ >Folders

 


  It defines a namespace (namespace) - com.ssm.chapter12.mapper.RoleMapper, and provides a role for growth, delete, search, change method. According to MyBatis rules need to define an interface RoleMapper.java, to be able to call it

  Listing: RoleMapper.java

package com.ssm.chapter12.mapper;

import com.ssm.chapter12.pojo.Role;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface RoleMapper {
    public int insertRole(Role role);

    public Role getRole(@Param("id") Long id);

    public int updateRole(Role role);

    public int deleteRole(@Param("id") Long id);
}

 

  Here is complete on the main code MyBatis framework, since RoleMapper is an interface, not a class, it is no way to produce an example, then it should be how to configure it

SqlSessionTemplate components

  Strictly speaking, SqlSessionTemplate not have to configure a component, but it also has a certain value. First, it is thread-safe class, that is, to ensure that SqlSession unique and not conflict with each other for each thread. Second, it offers a range of functions, such as increasing common functions, delete, search, change, etc.
  Listing: Configuring SqlSessionTemplate

<!--配置SqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="SqlSessionFactory"/>
    <!-- <constructor-arg value="BATCH"/>  -->
</bean>

 

  SqlSessionTemplate to go through to create the object constructor with parameters, commonly used parameters are SqlSessionFactory and MyBatis actuator (Ex-ecutor) type, which ranges SIMPLE, REUSE, BATCH, which we've discussed before actuator 3 types.

  Listing: SqlSessionTemplate applications

ApplicationContext ctx = new ClassPathXmlApplicationContext("ssm/chapter12/spring-cfg.xml");//ctx为Spring IoC容器

SqlSessionTemplate sqlSessionTemplate = ctx.getBean(SqlSessionTemplate.class);
Role role = new Role();
role.setRoleName("role_name_sqlSessionTemplate");
role.setNote("note_sqlSessionTemplate");
sqlSessionTemplate.insert("com.ssm.chapter12.mapper.RoleMapper.insertRole", role);
Long id = role.getId();
sqlSessionTemplate.selectOne("com.ssm.chapter12.mapper.RoleMapper.getRole", id);
role.setNote("update_sqlSessionTemplate");
sqlSessionTemplate.update("com.ssm.chapter12.mapper.RoleMapper.updateRole", role);
sqlSessionTemplate.delete("com.ssm.chapter12.mapper.RoleMapper.deleteRole", id);

 

  When running a SqlSessionTemplate, it will re-acquire a new SqlSession, that is to say each time SqlSessionTemplate run will produce a new SqlSession, so every method is independent SqlSession, which means it is safe thread.
  About SqlSessionTemplate, currently use is running, as shown in Listing as it requires the use of string which indicates that runs SQL, string does not contain business meaning, but functional code does not comply with the object-oriented specification. At the same time, the use of strings, IDE can not check the correctness of the code logic, so this usage gradually been abandoned. Note that, SqlSessionTemplate type configuration allowing the actuator, and when configure SqlSessionFactory SqlSessionTemplate time, priority higher than SqlSessionTemplate SqlSessionFactory.

Configuration MapperFactoryBean

  MyBatis run only need to provide similar RoleMapper.java interface, without having to provide an implementation class. By learning the principles of MyBatis running, you can know that it is a dynamic proxy object created by MyBatis system running, so there is no way for Spring generates implementation classes. To solve this problem, MyBatis-Spring team provides a MapperFactoryBean class as an intermediary, we can achieve what we want Mapper configure it. Mapper manner using the programming interface can be effectively erased SqlSessionTemplate your logic code, such code be written in accordance with the object-oriented specification, which is employed in the form of people willing.
  Listing: Object Configuration RoleMapper

<! - Configuration RoleMapper Object -> 
< the bean ID = "the RoleMapper" class = "org.mybatis.spring.mapper.MapperFactoryBean" > 
    <! - RoleMapper interface to be scanned Mapper -> 
    < Property name = " mapperInterface " value =" com.ssm.chapter12.mapper.RoleMapper " /> 
    < Property name =" SqlSessionFactory " ref =" SqlSessionFactory " /> 
    <-! If simultaneous injection sqlSessionTemplate and SqlSessionFactory, will only enable sqlSessionTemplate -> 
    <-! <Property name = "sqlSessionTemplate"  ref="sqlSessionTemplate"/> -->
</bean>

 

  Here it can be seen that there are three attributes MapperFactoryBean can be configured, namely mapperInterface, sqlSessionTemplate and SqlSessionFac-tory, wherein:
  • mapperInterface is mapper interface.
  • If the configuration sqlSessionTemplate and SqlSessionFactory the same time, it will enable sqlSessionTemplate, and SqlSessionFactory void. When we configure such a Bean, then we can use the following code to get a mapper.
  

RoleMapper roleMapper = ctx.getBean(RoleMapper.class);

 

Configuration MapperScannerConfigurer

  This is a form configured by scanning Mapper class, if one by one to configure Mapper, obviously heavy workload, and lead to the proliferation of configuration, with only need to give some simple configuration, it can generate a lot of Mapper, so reduce workload. First of all we need to know which properties can be configured for MapperScannerConfigurer its main configuration items are as follows:
  • basePackage, specify that the Spring automatically scan any package, it will drill down to scan, if you encounter multiple packages can use a comma separated.
  • annotationClass, said that if the class when they were identified by this comment, it is scanned. For developers, the author recommends using this mode register corresponding Mapper. Often using annotations @Repository represents the data access layer (DAO, Data Access Object) in the Spring, so the examples in this book is mainly introduced in this way.
  • SqlSessionFactoryBeanName, specify definitions SqlSessionFactory name of Bean in Spring. If sqlSessionTemplateBeanName is defined, then it will be useless.
  • markerInterface, specify the interface to achieve what it is considered Mapper. We need to provide a common interface to the mark.

  Listing: Configuring RoleMapper by scanning the way

<!--通过扫描的方式配置RoleMapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.ssm.chapter12.mapper"/>
    <property name="SqlSessionFactoryBeanName" value="SqlSessionFactory"/>
    <!--使用sqlSessionTemplateBeanName将覆盖SqlSessionFactoryBeanName的配置-->
    <!--<property name="sqlSessionTemplateBeanName" value="SqlSessionFactory"/>-->
    <!- nameProperty<->Specify dimension scanning only become Mapper
    ="annotationClass" value="org.springframework.stereotype.Repository"/>
</bean>

 

Guess you like

Origin www.cnblogs.com/ooo0/p/11027064.html