当前位置:Gxlcms > 数据库问题 > Spring集成myBatis操作数据库

Spring集成myBatis操作数据库

时间:2021-07-01 10:21:17 帮助过:12人阅读

这是一个半自动化的框架,何谓半自动,因为它需要手工编写POJO、SQL和映射关系。虽然要多花点时间编写SQL语句,但至少在优化方面可以省心不少。

2. Spring与myBatis的结合

2.1 基础配置文件  mybatis_config.xml

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

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <properties>
  <!-- 配置数据库方言 目前只有mysql和oracle两种--> 
  <property name="dialect" value="mysql" />
  </properties>

  <settings>
    <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
    <setting name="useGeneratedKeys" value="true" />

    <!-- 使用列别名替换列名 默认:true -->
    <setting name="useColumnLabel" value="true" />

    <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>

    <!-- 启用或禁用 缓存 -->
    <setting name="cacheEnabled" value="true" />

    <!-- 启用或禁用延迟加载。当禁用时, 所有关联对象都会即时加载 -->
    <!-- <setting name="lazyLoadingEnabled" value="true" /> -->
  </settings>

  <!-- 
    设置别名
    通过一个简单的别名来表示一个冗长的类型,这样可以降低复杂度。类型别名标签typeAliases中可以包含多个typeAlias 
  -->
  <typeAliases>
    <typeAlias alias="user" type="com.lhw.test.user.entity.User" />
  </typeAliases>

  <!-- 引入映射文件 --> 
  <mappers>
    <!-- start base config -->
    <mapper resource="user/user.mapper.xml" />
  </mappers>
</configuration>

2.2 Spring的配置文件   applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
  <!-- 开启注解扫描 -->
  <context:annotation-config />
  <context:component-scan base-package="com.lhw.*" /> 
  <!-- jdbc.properties文件路径 -->
  <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" />

  <!-- 系统日志初始化配置类 -->
  <bean id="log4jInitialization" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
    <property name="targetMethod" value="initLogging" />
    <property name="arguments">
      <list>
        <value>classpath:log4j.xml</value>
      </list>
    </property>
  </bean>

  <!-- 数据库日志初始化配置类 -->
  <bean id="log4jdbcInterceptor" class="net.sf.log4jdbc.DataSourceSpyInterceptor" />
  <bean id="dataSourceLog4jdbcAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="interceptorNames">
      <list>
        <value>log4jdbcInterceptor</value>
      </list>
    </property>
    <property name="beanNames">
      <list>
        <value>dataSource</value>
      </list>
    </property>
  </bean>

  <!-- 数据源的配置 -->
  <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}" />
    <!-- 设置连接池初始值 -->
    <property name="initialSize" value="1" />
    <!-- 设置连接池最大值 -->
    <property name="maxActive" value="2" />
    <!-- 设置连接池最大空闲值 -->
    <property name="maxIdle" value="2" />
    <!-- 设置连接池最小空闲值 -->
    <property name="minIdle" value="1" />

    <!--removeAbandoned: 是否自动回收超时连接-->
    <property name="removeAbandoned" value="true"/>
    <!--removeAbandonedTimeout: 超时时间(以秒数为单位)--> 
    <property name="removeAbandonedTimeout" value="180"/>
    <!--maxWait: 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒-->
    <property name="maxWait" value="3000"/>
    <!-- SQL查询,用来验证从连接池取出的连接 -->
    <property name="validationQuery" value="SELECT 1" />
    <property name="testOnBorrow" value="true" />
    <!-- 指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除 -->
    <property name="testWhileIdle" value="true" />
    <!-- 在每次空闲连接回收器线程(如果有)运行时检查的连接数量,最好和maxActive一致 -->
    <property name="numTestsPerEvictionRun" value="2"/>
    <!-- 在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小 -->
    <property name="timeBetweenEvictionRunsMillis" value="60000" />
    <!-- 连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位 -->
    <property name="minEvictableIdleTimeMillis" value="300000" />
  </bean>

  <!-- MyBatis sqlSessionFactory 配置 mybatis -->
  <bean name="sqlSessionFactory" id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="configLocation" value="classpath:config/mybatis_config.xml" />
    <property name="dataSource" ref="dataSource" />
  </bean>
  <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory" />
  </bean>

  <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="sqlSessionFactory"/>
  </bean>
  <!-- 基于接口方式 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    <property name="basePackage" value="com.lhw.test.service"></property>
    <property name="annotationClass" value="org.springframework.stereotype.Repository"></property>
  </bean>
  <!-- 事务控制 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="globalRollbackOnParticipationFailure" value="false"></property>
    <property name="dataSource" ref="dataSource" />
  </bean>

  <tx:annotation-driven transaction-manager="transactionManager"/>
  <aop:aspectj-autoproxy proxy-target-class="true" />   

  <tx:advice id="txAdvice" transaction-manager="transactionManager">   

    <tx:attributes>

      <tx:method name="get*" read-only="true" />
      <tx:method name="query*" read-only="true" />
      <tx:method name="save*" read-only="true" />

      <tx:method name="update*" read-only="true" />

      <tx:method name="del*" read-only="false" rollback-for="Exception" propagation="REQUIRED" />

      <tx:method name="remove*" read-only="false" rollback-for="Exception" propagation="REQUIRED" />
      <tx:method name="update*" read-only="false" rollback-for="Exception" propagation="REQUIRED" />
      <tx:method name="modfiy*" read-only="false" rollback-for="Exception" propagation="REQUIRED" />
      <tx:method name="add*" read-only="false" rollback-for="Exception" propagation="REQUIRED" />
      <tx:method name="create*" read-only="false" rollback-for="Exception" propagation="REQUIRED" />
      <tx:method name="insert*" read-only="false" rollback-for="Exception" propagation="REQUIRED" />
      <tx:method name="*" read-only="false" rollback-for="Exception" propagation="REQUIRED" />
     </tx:attributes>
   </tx:advice>
  <aop:config>
    <aop:pointcut id="serviceOperation" expression="execution(* com.lhw.test..service..*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
  </aop:config> 
</beans>

 

2.3 JDBC的配置文件   jdbc.properties

#jdbc settings
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&noAccessToProcedureBodies=true
jdbc.username=root
jdbc.password=root

 

2.4 映射文件   user.mapper.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="userMapper" >
   <!--

    如果POJO的属性名与数据库中表中列名映射一致,也可不写,或是通过在POJO中通过@Column(name = "")将数据库字段注解到POJO属性或方法上保持一致性也可

    -->
  <resultMap id="userMap" type="user" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="INTEGER" />
    <result column="email" property="email" jdbcType="VARCHAR" />
    <result column="tel" property="tel" jdbcType="VARCHAR" />
  </resultMap>

  <sql id="Base_Column_List" >
    id,username,password,name,sex,email.tel
  </sql>

  <!-- 根据id查询 -->
  <select id="queryById" resultMap="userMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from b_user where id = #{id,jdbcType=BIGINT}
  </select>

  <!-- 查询所有 -->
  <select id="queryAll" resultMap="userMap">
    select 
    <include refid="Base_Column_List" /> 
    from tb_user where 1 = 1
  </select>
</mapper>

 

2.5 DAO,BaseMybatisDao.java

/**
*
* @description:获取sqlSessionTemplate
* 
* @author: liuhongwei
*/
public class BaseMybatisDao {    
  @Resource
  public SqlSession sqlSessionTemplate;
}

sqlSessionTemplate是Spring提供的操作模板。

 

2.6 CRUD测试,继承DAO,userDAO.java

/**
*
* @description: 用户类数据库操作
* 
* @author: liuhongwei
*/
@Repository("userDao")
public class UserDao extends BaseMybatisDao {

  /**
  * 根据id查询用户信息
  * @param id
  * @return
  */
  @Override
  public Email queryById(Integer id) {
    return sqlSessionTemplate.selectOne("userMapper.queryById",id);
  }

  /**
  * 查询所有
  * @return
  */
  @Override
  public List<User> queryAll() {
    return sqlSessionTemplate.selectList("userMapper.queryAll");
  }

 

Spring集成myBatis操作数据库

标签:map   end   where   dial   简单的   复杂度   失败   自动化   cto   

人气教程排行