Spring SpringMVC配置Mybatis及Redis

版权声明:本文为博主原创文章,转载需注明出处。 https://blog.csdn.net/jay100500/article/details/84980791

 作者:谭东

这里是基于上个文章的配置继续增加的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

猜你喜欢

转载自blog.csdn.net/jay100500/article/details/84980791