美文网首页
结合实际研发经验讲解spring核心模块orm

结合实际研发经验讲解spring核心模块orm

作者: 欢乐时光欢乐你我 | 来源:发表于2019-03-15 16:46 被阅读0次
image.png

主题:spring orm

ORM:提供了常用的ORM框架,比如提供了:hibernate,mybatis等。
spring没有提供orm框架但是我们可以和流行的orm框架进行整合;

MapperScannerConfigurer

Mybatis-Spring为我们提供了一个叫做MapperScannerConfigurer的类,通过这个类Mybatis-Spring会自动为我们注册Mapper对应的MapperFactoryBean对象。

如果我们需要使用MapperScannerConfigurer来帮我们自动扫描和注册Mapper接口的话,我们需要在Spring的applicationContext配置文件中定义一个MapperScannerConfigurer对应的bean。

对于MapperScannerConfigurer而言有一个属性是我们必须指定的,那就是basePackage。
basePackage是用来指定Mapper接口文件所在的基包的,在这个基包或其所有子包下面的Mapper接口都将被搜索到。多个基包之间可以使用逗号或者分号进行分隔。

最简单的MapperScannerConfigurer定义就是只指定一个basePackage属性,如:
MapperScannerConfiguer 要扫描并注册的接口

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zxz.zxzx.ddx.mapper,com.xzx.zxzx.marketing.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

sqlsessionFactoryBean

在使用MyBatis-Spring jar :
用sqlsessionFactoryBean 来管理mybatis的sqlsessionFactory;

mybatis中, sessionFactory可由SqlSessionFactoryBuilder来创建。
但是 在 MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。如图:


image.png
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

SqlSessionFactoryBean有一个必须属性dataSource,
另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName">
            <value>${jdbc.connection.driver_class}</value>
        </property>
        <property name="url">
            <value>${jdbc.connection.url} </value>
        </property>
        <property name="username">
            <value>${jdbc.connection.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.connection.password}</value>
        </property>
        <property name="maxActive">
            <value>${jdbc.max.pool.size}</value>
        </property>
        <property name="initialSize">
            <value>${jdbc.min.pool.size}</value>
        </property>
        <property name="minIdle">
            <value>${jdbc.min.pool.size}</value>
        </property>
        <property name="testWhileIdle" value="true" />
        <property name="validationQuery" value="select 1" />
        <property name="filters" value="config" />
        <property name="connectionProperties" value="config.decrypt=true;config.decrypt.key=${xyydb.xyy.key}" />
        <property name="filters" value="stat,log4j,wall" />   
        <property name="removeAbandoned" value="true" />
        <property name="removeAbandonedTimeout" value="120" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
    </bean>
  • 通用属性configLocation(用来指定mybatis的xml配置文件路径)

  • configLocation:用于指定Mybatis的配置文件位置。如果指定了该属性,那么会以该配置文件的内容作为配置信息构建对应的SqlSessionFactoryBuilder,但是后续属性指定的内容会覆盖该配置文件里面指定的对应内容。

  • typeAliasesPackage:它一般对应我们的实体类所在的包,这个时候会自动取对应包中不包括包名的简单类名作为包括包名的别名。多个package之间可以用逗号或者分号等来进行分隔。(value的值一定要是包的全名)

    <!-- SqlSessionFactoryBean  spring整合ibatis的入口 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis.xml" />
        <property name="typeAliasesPackage" value="com.xaxs.xax.ddx.bo,com.xas.yhyc.ddx.dto,com.xasxa.xa.marketing.bo,com.yyw.yhyc.ddx.entity"  />
        <property name="mapperLocations" value="classpath*:ibatis/mapper/**/*.xml" />
        <property name="dataSource" ref="dataSource" />
        <property name="plugins">
            <list>
                <bean id="paginationPlugin" class="com.yyw.yhyc.plugin.PaginationPlugin"/>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                            reasonable=false
                        </value>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.asa.asaxx.ddx.mapper,com.yyw.yhyc.marketing.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL MAP Config 3.1//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- settings 一定要配置在plugins标签前面,有顺序讲究 -->
    <settings>
        <!-- 配置全局性 cache 的 ( 开 / 关) default:true -->
        <setting name="cacheEnabled" value="false" />

        <!-- 是否使用 懒加载 关联对象  同 hibernate中的延迟加载 一样  default:true  -->
        <setting name="lazyLoadingEnabled" value="false" />

        <!--当对象使用延迟加载时 属性的加载取决于能被引用到的那些延迟属性,否则,按需加载(需要的是时候才去加载)-->
        <setting name="aggressiveLazyLoading" value="true" />

        <!--SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>

事务

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
        <property name="rollbackOnCommitFailure" value="true" />
    </bean>

    <!-- 配置事务 -->
    <aop:config proxy-target-class="true">
        <aop:advisor pointcut="execution(* com.sss.sssaa.*.service..*Service*.*(..))" advice-ref="txAdvice" />
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="retrieve*" rollback-for="Exception" read-only="true" />
            <tx:method name="list*" rollback-for="Exception" read-only="true" />
            <tx:method name="get*" rollback-for="Exception" read-only="true" /> -->
            <tx:method name="view*" rollback-for="Exception" read-only="true" />
            <tx:method name="query*" rollback-for="Exception" read-only="true" /> -->
        </tx:attributes>
    </tx:advice>

开发中使用:

public interface CustomerInfoService {

    /**
     * 更新库存信息
     * @param supplierId
     * @param supplyName
     * @param syncAll
     * @param customers
     * @return
     */
    void updateCustomerInfo(String supplierId, String supplyName, Boolean syncAll, List<Customer> customers);
}

image.png image.png

ErpCustomerInfoMapper.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.xxs.sss.ddx.mapper.ErpCustomerInfoMapper" >
  <resultMap id="BaseResultMap" type="com.yyw.yhyc.ddx.entity.customer.ErpCustomerInfo" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="enterprise_id" property="enterpriseId" jdbcType="INTEGER" />
    <result column="enterprise_name" property="enterpriseName" jdbcType="VARCHAR" />
    <result column="syn_count" property="synCount" jdbcType="INTEGER" />
    <result column="cust_code_erp" property="custCodeErp" jdbcType="VARCHAR" />
    <result column="cust_name_erp" property="custNameErp" jdbcType="VARCHAR" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="created_user" property="createdUser" jdbcType="VARCHAR" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
    <result column="updated_user" property="updatedUser" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, enterprise_id, enterprise_name, cust_code_erp, cust_name_erp,
    create_time, created_user, update_time, updated_user,
  </sql>
  <select id="findCustomerInfoByEnterpriseIdAndName" resultType="map">
    select cust_name_erp,cust_code_erp from erp_customer_info
    where enterprise_id=#{enterpriseId} and cust_name_erp IN
    <foreach collection="custNames" open="(" close=")" separator="," item="custName">
      #{custName}
    </foreach>
  </select>
  <insert id="insertCustomerInfo" parameterType="list">
    insert into erp_customer_info(enterprise_id,enterprise_name,cust_code_erp,cust_name_erp,
    created_user,updated_user) VALUES
    <foreach collection="list" separator="," item="customer">
      (#{customer.seller_code},#{customer.create_user},#{customer.cust_code_erp},
      #{customer.cust_name_erp},'system','system')
    </foreach>
  </insert>
  <update id="updateCustomerInfo">
    update erp_customer_info set cust_code_erp=#{custCode},updated_user='system',update_time=now()
    where enterprise_id=#{enterpriseId} and cust_name_erp=#{custName}
  </update>
  <select id="findCustomerCount" resultType="integer">
    select count(0) from erp_customer_info
    where enterprise_id=#{enterpriseId}
  </select>
  <insert id="insertOrUpdate">
    insert into erp_customer_info(enterprise_id,enterprise_name,cust_code_erp,cust_name_erp,
    created_user, create_time) VALUES
    <foreach collection="list" separator="," item="customer">
      (#{customer.enterpriseId},#{customer.enterpriseName},#{customer.custCodeErp},
      #{customer.custNameErp}, #{customer.createdUser}, #{customer.createTime})
    </foreach>
      ON DUPLICATE KEY UPDATE
      cust_code_erp = VALUES(cust_code_erp),
      update_time = VALUES(create_time),
      updated_user = VALUES(created_user)
  </insert>
</mapper>

相关文章

网友评论

      本文标题:结合实际研发经验讲解spring核心模块orm

      本文链接:https://www.haomeiwen.com/subject/igqrmqtx.html