1. 程式人生 > >Spring SpringMVC配置Mybatis及Redis

Spring SpringMVC配置Mybatis及Redis

 作者:譚東

這裡是基於上個文章的配置繼續增加的Mybatis配置。

檔案目錄結構如圖:

 

pom.xml增加如下庫(mybatis和redis),一起配置了:

<!-- mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatisSpring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

        <!--mysql驅動包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!--c3p0 連線池 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
         <!--Redis -->
         <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>${redisSpring.version}</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${redis.version}</version>
        </dependency>
<mybatis.version>3.2.8</mybatis.version>
        <mybatisSpring.version>1.3.1</mybatisSpring.version>
        <mysql.version>5.1.40</mysql.version>
        <c3p0.version>0.9.1.2</c3p0.version>
        <redisSpring.version>1.6.2.RELEASE</redisSpring.version>
        <redis.version>2.9.0</redis.version>

接下來,將mybatis和redis配置到Spring中去,在applicationContext.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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!--classpath*:db.properties-->
    <!--1 引入屬性檔案,在配置中佔位使用 -->
    <context:property-placeholder location="classpath:/properties/db.properties,
    classpath:/properties/redis.properties"/>

    <!--2 配置C3P0資料來源 -->
    <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <!--驅動類名 -->
        <property name="driverClass" value="${jdbc.driver}"/>
        <!-- url -->
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <!-- 使用者名稱 -->
        <property name="user" value="${jdbc.username}"/>
        <!-- 密碼 -->
        <property name="password" value="${jdbc.password}"/>
        <!-- 當連線池中的連線耗盡的時候c3p0一次同時獲取的連線數 -->
        <!--<property name="acquireIncrement" value="${mysql.acquireIncrement}"></property>-->
        <!--&lt;!&ndash; 初始連線池大小 &ndash;&gt;-->
        <!--<property name="initialPoolSize" value="${mysql.initialPoolSize}"></property>-->
        <!--&lt;!&ndash; 連線池中連線最小個數 &ndash;&gt;-->
        <!--<property name="minPoolSize" value="${mysql.minPoolSize}"></property>-->
        <!--&lt;!&ndash; 連線池中連線最大個數 &ndash;&gt;-->
        <!--<property name="maxPoolSize" value="${mysql.maxPoolSize}"></property>-->
    </bean>

    <!--3 會話工廠bean sqlSessionFactoryBean  classpath:SqlMapConfig.xml"-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置檔案路徑 -->
        <property name="configLocation" value="classpath:/mybatis/SqlMapConfig.xml"></property>
        <!-- 資料來源 -->
        <property name="dataSource" ref="datasource"></property>
        <!-- sql對映檔案路徑 -->
        <!--<property name="mapperLocations" value="classpath*:com/web/mvc/mapper/*Mapper.xml"></property>-->
    </bean>

    <!--4 自動掃描物件關係對映 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定會話工廠,如果當前上下文中只定義了一個則該屬性可省去 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 指定要自動掃描介面的基礎包,實現介面 -->
        <property name="basePackage" value="com.web.mvc.mapper"/>
    </bean>

    <!--5 宣告式事務管理 -->
    <!--定義事物管理器,由spring管理事務 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"/>
    </bean>
    <!--支援註解驅動的事務管理,指定事務管理器 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    <!-- 定義JdbcTemplate的Bean -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="datasource"/>
    <!--6 容器自動掃描IOC元件 -->
    <context:component-scan base-package="com.web.mvc"/>

    <!--7 aspectj支援自動代理實現AOP功能 -->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

    <!-- 匯入redis的配置檔案 -->
    <import resource="classpath:/redis/redisConfig.xml"/>
</beans>

分別建立紅框的幾個配置檔案,目錄結構如圖:

先編寫db.properties:

# mysql資料庫
jdbc.driver=com.mysql.jdbc.Driver
# 本地mysql資料庫
# 資料庫地址,此處預設本地地址,hotel表示資料庫名
jdbc.url=jdbc:mysql://localhost:3306/mysql?serverTimezone=GMT&characterEncoding=utf-8
# 資料庫使用者名稱稱
jdbc.username=root
# 資料庫密碼
jdbc.password=Mysql123456
#定義初始連線數
initialSize=0
#定義最大連線數
maxActive=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWait=60000

編寫SqlMapConfig.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>
    <!-- 載入資料庫檔案db.properties -->
    <!--<properties resource="/properties/db.properties"/>-->
    <!--<properties resource="org/mybatis/example/config.properties">-->
    <!--<property name="username" value="dev_user"/>-->
    <!--<property name="password" value="F2Fa3!33TYyg"/>-->
    <!--</properties>-->
    <settings>
        <setting name="defaultExecutorType" value="REUSE"/>
    </settings>
    <typeAliases>
        <typeAlias type="com.web.mvc.model.Entity" alias="Entity"/>
        <!-- 批量別名定義(推薦) -->
        <!-- package:指定包名稱來為該包下的po類宣告別名,預設的別名就是類名(首字母大小寫都可) -->
        <!--<package name="com.web.mvc.model"/>-->
    </typeAliases>
    <!--<environments default="development">-->
        <!--<environment id="development">-->
            <!--<transactionManager type="JDBC"/>-->
            <!--<dataSource type="POOLED">-->
                <!--<property name="driver" value="${jdbc.driver}"/>-->
                <!--<property name="url" value="${jdbc.url}"/>-->
                <!--<property name="username" value="${jdbc.username}"/>-->
                <!--<property name="password" value="${jdbc.password}"/>-->
            <!--</dataSource>-->
        <!--</environment>-->
    <!--</environments>-->
    <mappers>
        <!--<mapper resource="com/web/mvc/EntityMapper.xml"/>-->
        <!-- 批量載入對映檔案 -->
        <package name="com.web.mvc.mapper"/>
    </mappers>

</configuration>

編寫redis.properties:

#redis setting
redis.host=127.0.0.1
redis.port=6379
redis.password=
redis.maxIdle=100
redis.maxActive=300
redis.maxWait=1000
redis.testOnBorrow=true
redis.timeout=100000
fep.local.cache.capacity=10000

編寫redisConfig.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
     http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd"
       default-autowire="byName" default-lazy-init="true">

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    </bean>
    <!-- redis伺服器中心 -->
    <bean id="connectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="poolConfig"/>
        <property name="port" value="${redis.port}"/>
        <property name="hostName" value="${redis.host}"/>
        <property name="password" value="${redis.password}"/>
        <property name="timeout" value="${redis.timeout}"></property>
    </bean>
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="keySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
    </bean>

    <bean id="redisUtil" class="com.web.mvc.utils.RedisUtils">
        <property name="redisTemplate" ref="redisTemplate"/>
    </bean>

</beans>

建立mapper類和xml:

EntityMapper.java:

package com.web.mvc.mapper;

import com.web.mvc.model.Entity;
import org.apache.ibatis.annotations.Param;

import java.sql.SQLException;
import java.util.List;

public interface EntityMapper {
    int insert(Entity record);

    int insertSelective(Entity record);

    Entity findById(@Param("id") int id) throws SQLException;

    List<Entity> findAll() throws SQLException;

    void delete(int id);

    void update(int id,Entity s);
}

EntityMapper.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.web.mvc.mapper.EntityMapper">
    <resultMap id="BaseResultMap" type="com.web.mvc.model.Entity">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="age" jdbcType="INTEGER" property="age"/>
        <result column="name" jdbcType="VARCHAR" property="name"/>
        <result column="sex" jdbcType="VARCHAR" property="sex"/>
        <result column="tel" jdbcType="VARCHAR" property="tel"/>
    </resultMap>
    <insert id="insert" parameterType="com.web.mvc.model.Entity">
        insert into students (id, age, name,
        sex, tel)
        values (#{id,jdbcType=INTEGER}, #{age,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
        #{sex,jdbcType=VARCHAR}, #{tel,jdbcType=VARCHAR})
    </insert>
    <insert id="insertSelective" parameterType="com.web.mvc.model.Entity">
        insert into students
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="age != null">
                age,
            </if>
            <if test="name != null">
                name,
            </if>
            <if test="sex != null">
                sex,
            </if>
            <if test="tel != null">
                tel,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="sex != null">
                #{sex,jdbcType=VARCHAR},
            </if>
            <if test="tel != null">
                #{tel,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    <select id="findById" parameterType="int" resultMap="BaseResultMap">
        select * from students where id=#{id,jdbcType=INTEGER}
    </select>
    <select id="findAll" resultMap="BaseResultMap">
        select * from students
    </select>

    <delete id="delete" parameterType="int">
        DELETE FROM students WHERE id=#{id}
    </delete>

    <update id="update" parameterType="Entity">
        UPDATE students SET name=#{name},sex=#{sex},age=#{age},tel=#{tel} WHERE id=#{id}
    </update>
</mapper>

其實這兩個檔案我們可以通過mybatis逆向工程進行自動生成,再來新增方法會更方便快速些,後續給大家講解使用mybatis逆向工程進行生成。

建立Redis操作工具類,RedisUtils:

package com.web.mvc.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

public class RedisUtils {
    private RedisTemplate<Serializable, Object> template;

    /**
     * 寫入快取
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = template.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            System.out.println("set cache error" + e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * 寫入快取
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = template.opsForValue();
            operations.set(key, value);
            template.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            System.out.println("set cache error" + e.getLocalizedMessage());
        }
        return result;
    }

    public Object get(String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = template.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 刪除對應的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            template.delete(key);
        }
    }

    /**
     * 判斷快取中是否有對應的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return template.hasKey(key);
    }

    public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
        this.template = redisTemplate;
    }

}

上面的mapper類相當於dao層的類了。

完善這兩個類:

EntityService.java:

package com.web.mvc.service;

import com.web.mvc.mapper.EntityMapper;
import com.web.mvc.model.Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class EntityService implements IEntityService {

    @Autowired
    private EntityMapper entityMapper;

    @Override
    public void add(Entity s) throws SQLException {
        entityMapper.insert(s);
    }

    @Override
    public void update(int id,Entity s) throws SQLException {
        entityMapper.update(id,s);
    }

    @Override
    public void delete(int id) throws SQLException {
        entityMapper.delete(id);
    }

    @Override
    public Entity findById(int id) throws SQLException {
        return entityMapper.findById(id);
    }

    @Override
    public List<Entity> findAll() throws SQLException {
        return entityMapper.findAll();
    }
}

IEntityService.java:

package com.web.mvc.service;

import com.web.mvc.model.Entity;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

public interface IEntityService {
    //新增方法
    void add(Entity s) throws SQLException;

    //更新方法
    void update(int id, Entity s) throws SQLException;

    //刪除方法
    void delete(int id) throws SQLException;

    //查詢方法
    Entity findById(int id) throws SQLException;

    //查詢所有
    List<Entity> findAll() throws SQLException;
}

完善Controller進行測試:

package com.web.mvc.controller;

import com.web.mvc.model.Entity;
import com.web.mvc.service.EntityService;
import com.web.mvc.service.IEntityService;
import com.web.mvc.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.sql.SQLException;
import java.util.List;

@Controller
@RequestMapping("/entity")
public class EntityController {

    @Autowired
    private IEntityService entityService;
    @Autowired
    private RedisUtils redisUtils;
    private static Logger logger = LoggerFactory.getLogger(EntityController.class);

    @RequestMapping("/{id}")
    public String getDetail(@PathVariable Integer id, Model model) {
        Entity entity = null;
        try {
            entity = entityService.findById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        redisUtils.set("entity", entity);
        model.addAttribute("text", entity.getName() + "");
        model.addAttribute("entity", entity);
        return "page";
    }

    @RequestMapping("/add/{id}")
    public String addEntity(@PathVariable Integer id, Model model) {
        Entity entity = new Entity();
        entity.setId(id);
        entity.setName("Entity");
        entity.setAge(18);
        entity.setSex("boy");
        entity.setTel("133");
        try {
            entityService.add(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        model.addAttribute("text", id + "");
        model.addAttribute("entity", entity);
        return "page";
    }

    @RequestMapping("/all")
    public String getAll(Model model) {
        List<Entity> list = null;
        try {
            list = entityService.findAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        model.addAttribute("text", list.get(0).getName() + "");
        return "page";
    }

    @RequestMapping("/cache/{id}")
    public String getCacheDetail(@PathVariable Integer id, Model model) {
        Entity entity = (Entity) redisUtils.get("entity");
        model.addAttribute("text", entity.getName() + "");
        model.addAttribute("entity", entity);
        return "page";
    }

    @RequestMapping("/del/{id}")
    public String delete(@PathVariable Integer id, Model model) {
        try {
            entityService.delete(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        model.addAttribute("text", "del");
        return "page";
    }

    @RequestMapping("/update/{id}")
    public String update(@PathVariable Integer id, Model model) {
        Entity entity = new Entity();
        entity.setName("Update");
        entity.setAge(18);
        try {
            entityService.update(id, entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        model.addAttribute("text", "del");
        return "page";
    }
}

ok,這樣就可以了。

專案Github地址為:https://github.com/jaychou2012/SpringMVC