基於註解方式配置springMVC 並整合mybatis(二)

基於註解方式配置springMVC 並整合mybatis(一)java

接上篇文章,以下是整合數據層。mysql

spring-mybatis.xmlspring

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 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/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:annotation-config/>
    <aop:aspectj-autoproxy />
    <!-- 自動掃描 -->
    <context:component-scan base-package="com.tao.demo" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化鏈接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 鏈接池最大數量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 鏈接池最大空閒 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 鏈接池最小空閒 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 獲取鏈接最大等待時間 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mapping/*.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.tao.demo.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 使用annotation定義事務 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

jdbc.propertiessql

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=123qwe
#定義初始鏈接數
initialSize=0
#定義最大鏈接數
maxActive=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWait=60000

UserTMapper.xmlapache

<?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.tao.demo.mapper.UserTMapper" >
  <resultMap id="BaseResultMap" type="com.tao.demo.po.UserT" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Oct 27 15:37:49 CST 2017.
    -->
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Oct 27 15:37:49 CST 2017.
    -->
    id, user_name, password, age
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Oct 27 15:37:49 CST 2017.
    -->
    select 
    <include refid="Base_Column_List" />
    from user_t
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Oct 27 15:37:49 CST 2017.
    -->
    delete from user_t
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.tao.demo.po.UserT" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Oct 27 15:37:49 CST 2017.
    -->
    insert into user_t (id, user_name, password, 
      age)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.tao.demo.po.UserT" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Oct 27 15:37:49 CST 2017.
    -->
    insert into user_t
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="age != null" >
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.tao.demo.po.UserT" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Oct 27 15:37:49 CST 2017.
    -->
    update user_t
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.tao.demo.po.UserT" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Oct 27 15:37:49 CST 2017.
    -->
    update user_t
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
  <sql id="sql_where" >
    <where >
      <if test="userName != null" >
         and user_name = #{userName,jdbcType=VARCHAR}
      </if>
      <if test="password != null" >
         and password = #{password,jdbcType=VARCHAR}
      </if>
      <if test="age != null" >
         and age = #{age,jdbcType=INTEGER}
      </if>
    </where>
  </sql>
  <select id="getList" resultMap="BaseResultMap" parameterType="com.tao.demo.po.UserT" >
     select * from user_t
    <include refid="sql_where" />
  </select>
</mapper>

UserTMappersegmentfault

public interface UserTMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_t
     *
     * @mbggenerated Fri Oct 27 15:37:49 CST 2017
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_t
     *
     * @mbggenerated Fri Oct 27 15:37:49 CST 2017
     */
    int insert(UserT record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_t
     *
     * @mbggenerated Fri Oct 27 15:37:49 CST 2017
     */
    int insertSelective(UserT record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_t
     *
     * @mbggenerated Fri Oct 27 15:37:49 CST 2017
     */
    UserT selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_t
     *
     * @mbggenerated Fri Oct 27 15:37:49 CST 2017
     */
    int updateByPrimaryKeySelective(UserT record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user_t
     *
     * @mbggenerated Fri Oct 27 15:37:49 CST 2017
     */
    int updateByPrimaryKey(UserT record);

    List<UserT> getList(UserT UserT);
}

UserServicespring-mvc

@Service
public class UserService {
    @Resource
    private UserTMapper userTMapper;

    public UserT getUserById(int userId) {
        return userTMapper.selectByPrimaryKey(userId);
    }

}

HelloControllermybatis

@Controller
public class HelloController {

    @Resource
    private UserService userService;

    @RequestMapping("index")
    public String hello(){
        System.out.println("hello world");
        return "index";
    }

    @RequestMapping(value = "/user")
    @ResponseBody
    public String Random(){
        UserT userById = userService.getUserById(1);
        return "data:"+ JSON.toJSONString(userById);
    }

}

在WebInitializer中需加入監聽器mvc

public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MyMvcConfig.class);
        context.setServletContext(servletContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        servlet.setAsyncSupported(true);
        servletContext.setInitParameter("contextConfigLocation","classpath:spring-mybatis.xml");
        servletContext.addListener(ContextLoaderListener.class);
    }
}

最後目錄結構爲app

clipboard.png

總結:
基於java類配置,是spring4中推薦的方式,類和註解組合能夠減小不少配置文件。整合mybatis時,若是不加上servletContext.addListener(ContextLoaderListener.class);就沒法啓動容器。

相關文章
相關標籤/搜索