Spring整合Mybatis、redis的Hello-World程序

Spring+Redis

1.首先redis服务器要处于开启状态
2.redis maven依赖

<!-- redis -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.8.9.RELEASE</version>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

<!-- spring -->
// 省略

3.配置文件:spring-redis.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:redis/redis.properties" ignore-unresolvable="true"/>
    <context:component-scan base-package="com.dadagum.util"/>

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"
          p:maxIdle="${redis.maxIdle}"
          p:maxWaitMillis="${redis.maxWaitMillis}"
          p:maxTotal="${redis.maxTotal}"
          p:numTestsPerEvictionRun="${redis.numTestsPerEvictionRun}"
          p:timeBetweenEvictionRunsMillis="${redis.timeBetweenEvictionRunsMillis}"
          p:testOnBorrow="${redis.testOnBorrow}"
          p:minEvictableIdleTimeMillis="${redis.minEvictableIdleTimeMillis}"
          p:testWhileIdle="${redis.testWhileIdle}"/>

    <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:hostName="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:poolConfig-ref="poolConfig"
          p:timeout="${redis.timeout}"/>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
          p:connectionFactory-ref="jedisConnFactory" >
        <property name="keySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="hashKeySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
        <property name="hashValueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
    </bean>
</beans>

4.redis.properties文件

#redis连接服务端配置
redis.host=127.0.0.1
redis.port=6379
redis.password=test

#客户端超时时间
redis.timeout=2000
#最大空闲数
redis.maxIdle=10
#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
redis.maxTotal=10
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWaitMillis=1000
#连接的最小空闲时间 默认1800000毫秒(30分钟)
redis.minEvictableIdleTimeMillis=300000
#每次释放连接的最大数目,默认3
redis.numTestsPerEvictionRun=1024
#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
redis.timeBetweenEvictionRunsMillis=30000
#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=false
#在空闲时检查有效性, 默认false
redis.testWhileIdle=false

5.redisUtil(作为例子只写有一小部分)

package com.dadagum.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置缓存的失效时间
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time){
        try {
            if (time > 0){
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据key获取过期时间
     * @param key
     * @return
     */
    public long getExpire(String key){
        return  redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除某些缓存
     * @param key
     */
    @SuppressWarnings("unchecked")
    public void deleteK(String ... key){
        if (key == null || "".equals(key)) return;
        if (key.length == 1) {
            redisTemplate.delete(key[0]);
        } else {
            redisTemplate.delete(CollectionUtils.arrayToList(key));
        }
    }

    /**
     * 获取某个缓存
     * @param key
     * @return
     */
    public Object getValue(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入,默认失效时间为无限长
     * @param key
     * @param value
     * @return
     */
    public boolean setValue(String key, Object value){
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置缓存并且设置时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean setValue(String key, Object value, long time){
        try {
            if (time > 0){
                redisTemplate.opsForValue().set(key, value, time);
            } else {
                setValue(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}

6.测试

    @Test
    public void testConnection(){
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-redis.xml");
        RedisUtil redisUtil = (RedisUtil) context.getBean("redisUtil");
        redisUtil.setValue("hello", "world");
        System.out.println(redisUtil.getValue("hello"));
    }

Spring+Mybatis

1.使用Spring就将原本由mybatis配置交由spring管理了,十分方便

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 数据库数据源 -->
    <context:property-placeholder location="classpath:sql/jdbc.properties" ignore-unresolvable="true"/>
    <bean id = "dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"
          p:driverClassName="${jdbc.driver}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}"/>

    <!-- mybatis -->
    <!-- sql session 实例 -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean"
          p:typeAliasesPackage="com.dadagum.bean"
          p:dataSource-ref="dataSource"
          p:mapperLocations="classpath:com/dadagum/mapper/*.xml" />

    <!-- mapper 扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.dadagum.mapper"/>

</beans>

2.创建mapper
①创建mapper接口 (使用xml的方式而不使用注解;如果使用注解直接可以在接口的方法上添加@insert等注解)

package com.dadagum.mapper;

import com.dadagum.bean.UserInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Set;

public interface UserInfoMapper {

    /**
     * 增加一个用户
     * @param userInfo
     * @return
     */
    public int addUser(UserInfo userInfo);

    /**
     * 得到所有的用户信息
     * @return
     */
    public List<UserInfo> getUserInfo();

    /**
     * 根据用户的名称得到用户的密码
     * @return
     */
    public String getPasswordByUserName(String username);

    /**
     * 根据用户的名称得到用户信息中的盐值
     * @param username
     * @return
     */
    public String getSaltByUserName(String username);
}

②编写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.dadagum.mapper.UserInfoMapper">
    <select id="getUserInfo" resultType="UserInfo">
        select * from userinfo
    </select>

    <select id="selectUser" parameterType="_int" resultType="UserInfo">
        select * from userinfo where userId = #{id}
    </select>

    <insert id="addUser" parameterType="UserInfo">
        insert into userInfo values(null, #{userAccount}, #{userPassword}, null, null, #{salt})
    </insert>

    <select id="getPasswordByUserName" parameterType="string" resultType="string">
        select userPassword from userinfo where userAccount = #{username}
    </select>

    <select id="getSaltByUserName" parameterType="string" resultType="string">
        select salt from userinfo where userAccount = #{username}
    </select>
</mapper>

3.配置pom.xml
默认会在resource资源总目录中寻找xml文件,但是我们的mapper的xml文件写在java的目录下,因此要在pom.xml的built标签中加上

<!-- to let mybatis find my mapper -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

这样子就可以正确找到我们编写mapper的xml文件了
4.测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/spring-dao.xml")
public class MybatisSpringTest {

    @Autowired
    private UserInfoMapper mapper;

    @Test
    public void testSelect(){
        System.out.println(mapper.getUserInfo());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值