Spring与Mybatis基于注解整合Redis的方法

基于这段时间折腾redis遇到了各种问题,想着整理一下。本文主要介绍基于Spring+Mybatis以注解的形式整合Redis。废话少说,进入正题。

  首先准备Redis,我下的是Windows版,下载后直接启动redis-server就行了,见下图:

一,先上jar包

二,创建实体类

package com.sl.user.vo;
import java.io.Serializable;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize
@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
public class UserVO implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String username;
private String password;
private int age;
public UserVO(){
super();
}
public UserVO(int id, String username, String password, int age) {
super();
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserVO [id=" + id + ", username=" + username + ", password="
+ password + ", age=" + age + "]";
}
}

三,dao接口

package com.sl.user.dao;
import com.sl.user.vo.UserVO;
public interface UserDao {
public void addUser(UserVO user);
public void deleteUser(UserVO user);
public void updateUser(UserVO user);
public UserVO getUserById(int id);
public UserVO getUser(int id);
}

四,UserMapper

<?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.sl.user.dao.UserDao" >
<resultMap id="userResult" type="User">
<result column="id" property="id"/>
<result column="userame" property="userame"/>
<result column="password" property="password"/>
<result column="age" property="age"/>
</resultMap>
<insert id="addUser" parameterType="User">
insert into t_user(username,password,age) values(#{username},#{password},#{age})
</insert>
<update id="deleteUser" parameterType="User">
delete * from t_user where id = #{id}
</update>
<update id="updateUser" parameterType="User">
update t_user set
<if test="username != null and username != ''"> username = #{username},</if>
<if test="password != null and password != ''"> password = #{password},</if>
<if test="age != null and age != ''"> age = #{age}</if>
where 1=1
<if test="id != null and id != ''">and id = #{id}</if>
</update>
<select id="getUser" parameterType="int" resultType="User" >
select * from t_user where id = #{id}
</select>
<select id="getUserById" parameterType="int" resultType="java.lang.String" >
select username from t_user where id = #{id}
</select>
</mapper>

五,Service接口

package com.sl.user.service;
import com.sl.user.vo.UserVO;
public interface UserService {
public void addUser(UserVO user);
public void deleteUser(UserVO user);
public void updateUser(UserVO user);
public UserVO getUserById(int id);
public UserVO getUser(int id);
}

六,Service实现

package com.sl.user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.sl.user.dao.UserDao;
import com.sl.user.service.UserService;
import com.sl.user.vo.UserVO;
@Service("userService")
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
@CacheEvict(value="User",key="addUser",allEntries=true)
public void addUser(UserVO user) {
userDao.addUser(user);
}
@Override
@CacheEvict(value = {"getUser", "getUserById"}, allEntries = true)
public void deleteUser(UserVO user) {
userDao.deleteUser(user);
}
@Override
@CacheEvict(value = {"getUser", "getUserById"}, allEntries = true)
public void updateUser(UserVO user) {
userDao.updateUser(user);
}
@Override
@Cacheable(value="User",key="getUserById")
public UserVO getUserById(int id) {
return userDao.getUserById(id);
}
@Override
@Cacheable(value="User",key="'getUser'")
public UserVO getUser(int id) {
return userDao.getUser(id);
}
}

七,Ctrl层

package com.sl.user.web;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sl.user.service.UserService;
import com.sl.user.vo.UserVO;
@Controller
@RequestMapping("/userCtrl")
public class UserCtrl {
@Autowired
private UserService userService;
@RequestMapping("/addUser")
public void addUser(UserVO user){
userService.addUser(user);
}
@RequestMapping("/deleteUser")
public void deleteUser(UserVO user){
userService.deleteUser(user);
}
@RequestMapping("/updateUser")
public void updateUser(UserVO user){
userService.updateUser(user);
}
@ResponseBody
@RequestMapping("/getUserById")
public Map<String,Object> getUserById(UserVO user){
Map<String,Object> map = new HashMap<String,Object>();
map.put("msg",userService.getUserById(4));
return map;
}
@ResponseBody
@RequestMapping("/getUser")
public Map<String,Object> getUser(UserVO vo){
Map<String,Object> map = new HashMap<String,Object>();
Object user = userService.getUser(4);
map.put("msg",user.toString());
return map;
}
}

八,Redis关键类,用于CRUD操作

package com.sl.user.redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
public class RedisUtil implements Cache{
private RedisTemplate<String, Object> redisTemplate;
private String name;
public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
@Override
public Object getNativeCache() {
return this.redisTemplate;
}
/**
* 从缓存中获取key
*/
@Override
public ValueWrapper get(Object key) {
System.out.println("get key");
final String keyf = key.toString();
Object object = null;
object = redisTemplate.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] key = keyf.getBytes();
byte[] value = connection.get(key);
if (value == null) {
return null;
}
return toObject(value);
}
});
return (object != null ? new SimpleValueWrapper(object) : null);
}
/**
* 将一个新的key保存到缓存中
* 先拿到需要缓存key名称和对象,然后将其转成ByteArray
*/
@Override
public void put(Object key, Object value) {
System.out.println("put key");
final String keyf = key.toString();
final Object valuef = value;
final long liveTime = 86400;
redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] keyb = keyf.getBytes();
byte[] valueb = toByteArray(valuef);
connection.set(keyb, valueb);
if (liveTime > 0) {
connection.expire(keyb, liveTime);
}
return 1L;
}
});
}
private byte[] toByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
}catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
}
private Object toObject(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}
/**
* 删除key
*/
@Override
public void evict(Object key) {
System.out.println("del key");
final String keyf = key.toString();
redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
return connection.del(keyf.getBytes());
}
});
}
/**
* 清空key
*/
@Override
public void clear() {
System.out.println("clear key");
redisTemplate.execute(new RedisCallback<String>() {
public String doInRedis(RedisConnection connection)
throws DataAccessException {
connection.flushDb();
return "ok";
}
});
}
@Override
public <T> T get(Object key, Class<T> type) {
return null;
}
@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
return null;
}
}

九,Spring整合mybatis和redis配置文件

<?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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 扫描dao,service -->
<context:component-scan base-package="com.sl.user.service" />
<context:component-scan base-package="com.sl.user.service.*" />
<context:component-scan base-package="com.sl.user.redis" />
<!-- 启用注解 -->
<context:annotation-config/>
<!-- 启动缓存注解 -->
<cache:annotation-driven/>
<!-- MyBatis start -->
<!-- 配置dataSource DriverManagerDataSource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- MyBatis配置 SqlSessionFactoryBean -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:config/mybatis.xml"></property>
<property name="mapperLocations" value="classpath:mapper/UserMapper.xml"></property>
</bean>
<!-- mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer
sqlSessionFactory
basePackage:指定sql映射文件/接口所在的包(自动扫描) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sessionFactory"></property>
<property name="basePackage" value="com.sl.user.dao"></property>
</bean>
<!-- 事务管理 DataSourceTransactionManager-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 使用声明式事务 transaction-manager:引用上面定义的事务管理器-->
<tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
<!-- MyBatis end -->
<!-- 配置redis部分 start -->
<!-- 配置redis连接池 JedisPoolConfig-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="300" />
<property name="maxTotal" value="600" />
</bean>
<!-- 配置CoonnectionFactory JedisConnectionFactory-->
<bean id="connFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="127.0.0.1"></property>
<property name="port" value="6379"></property>
<property name="poolConfig" ref="poolConfig"></property>
</bean>
<!-- 配置redisTemplate StringRedisTemplate-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connFactory"/>
</bean>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="com.sl.user.redis.RedisUtil">
<property name="redisTemplate" ref="redisTemplate" />
<property name="name" value="User"/>
<!-- User名称要在类或方法的注解中使用 -->
</bean>
</set>
</property>
</bean>
</beans>

十,SpringMVC配置文件

<?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:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven/>
<!-- 启用spring mvc 注解 -->
<context:annotation-config/>
<!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="com.sl.user.*"></context:component-scan>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<!-- JSON转换器 -->
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=utf-8</value>
<value>text/json;charset=utf-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
</beans>

十一,mybatis配置文件

<?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>
<!-- 实体类,简称 -设置别名 -->
<typeAliases>
<typeAlias alias="User" type="com.sl.user.vo.UserVO" />
</typeAliases>
</configuration>

十二,log4j

# Set root category priority to INFO and its only appender to CONSOLE.
log4j.rootCategory=DEBUG, CONSOLE
#log4j.rootCategory=INFO, CONSOLE, LOGFILE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} %p - %m%n
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG

十三,web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>TestRedis</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:config/applicationContext.xml
</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:config/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 日志 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/SpringMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 解决中文乱码问题 -->
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

十四,测试,已查询为例(getUser()方法),jsp测试页面整的比较丑就不贴出来了,自己写一个吧。。。

查询前:

执行第一次查询:

执行第二次查询操作:

上图可见,没有再执行sql,直接从redis中获取数据。

以上所述是小编给大家介绍的Spring与Mybatis基于注解整合Redis的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • Mybatis基于注解形式的sql语句生成实例代码

    对其做了些优化,但此种sql生成方式仅适用于复杂程度不高的sql,所以实用性不是很高,仅仅是写着玩的,知道点mybatis的注解形式的使用方式,可能以后会逐渐完善起来.第一次写博客,写的简单点. package com.bob.config.mvc.mybatis; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retenti

  • mybatis执行批量更新batch update 的方法(oracle,mysql两种)

    Oracle和MySQL数据库的批量update在mybatis中配置不太一样: oracle数据库: <code class="hljs tcl" style=""><<span class="hljs-keyword" style="">update</span> id=<span class="hljs-string" style=""

  • mybatis中注解映射SQL示例代码

    前言 本文主要给大家介绍了关于mybatis注解映射SQL的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍: 结果集分页 有时我们需要处理海量数据,由于数据量太大,所以不能一次取出所有的数据,这时我们就需要使用分页功能.mybatis通过RowBounds对象提供对分页的支持,如下所示: <select id="findAllStudents" resultMap="StudentResult"> select * from st

  • MyBatis Generator去掉生成的注解

    是不是很讨厌mybatis Generator帮我们生成代码的时候在Mapper和mapper.xml文件中生成的一大堆注解?今天在看MyBatis Generator代码的时候发现,原来mybatis generator是提供了配置注解的能力,配置如下,在generatorConfig.xml中加上配置: <commentGenerator> <property name="suppressDate" value="true"/> <

  • Mybatis中注解@MapKey的使用详解

    mybatis的原身是ibatis,现在已经脱离了apache基金会,新官网是http://www.mybatis.org/. 在研究Mybatis源码之前并不知道这个注解的妙用的,但是当我看到参数解析的时候 有这个一个注解,所以我了解了一下,当我们返回像Map<String, Map<String, Object>>这种类型的时候,我们往往很难做到,因为这里面可能是多个表的数据,所以我们不可能再建一个模型. 这时候我们就可以使用这个注解了 @Retention(Retention

  • Mybatis 开发注解快速入门

    快速普及 1.mybatis是什么 mybatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架. MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录. Mybatis实现了接口绑定,使用更加方便. 对象关系映射的改进,效率更高 MyBatis采用功能强大的基于OGNL的表达式来

  • Spring与Mybatis基于注解整合Redis的方法

    基于这段时间折腾redis遇到了各种问题,想着整理一下.本文主要介绍基于Spring+Mybatis以注解的形式整合Redis.废话少说,进入正题. 首先准备Redis,我下的是Windows版,下载后直接启动redis-server就行了,见下图: 一,先上jar包 二,创建实体类 package com.sl.user.vo; import java.io.Serializable; import com.fasterxml.jackson.databind.PropertyNamingSt

  • Spring基于注解整合Redis完整实例

    在<Redis之--Spring整合Redis>一文中,向大家介绍了如何将spring与Redis整合起来,但不是基于注解的形式,很多同学都希望能够通过注解的形式来简单的将Spring与Redis整合起来,这样,在使用的时候,只需要在相应的方法上加上注解,便可以使方法轻松的调用Redis的缓存.那么今天就来向大家介绍如何用基于注解的形式来整合Spring与Redis. 一.项目搭建 今天,我们不使用hibernate来操作数据库了,我们今天选择的框架是: Spring4(包括mvc.conte

  • spring与mybatis三种整合方法

    1.采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean. spring-mybatis.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3

  • 详解spring boot mybatis全注解化

    本文重点给大家介绍spring boot mybatis 注解化的实例代码,具体内容大家参考下本文: pom.xml <!-- 引入mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version

  • Mybatis基于注解实现多表查询功能

    对应的四种数据库表关系中存在四种关系:一对多,多对应,一对一,多对多.在前文中已经实现了xml配置方式实现表关系的查询,本文记录一下Mybatis怎么通过注解实现多表的查询,算是一个知识的补充. 同样的先介绍一下Demo的情况:存在两个实体类用户类和账户类,用户类可能存在多个账户,即一对多的表关系.每个账户只能属于一个用户,即一对一或者多对一关系.我们最后实现两个方法,第一个实现查询所有用户信息并同时查询出每个用户的账户信息,第二个实现查询所有的账户信息并且同时查询出其所属的用户信息. 1.项目

  • SpringBoot详解整合Redis缓存方法

    目录 1.Spring Boot支持的缓存组件 2.基于注解的Redis缓存实现 3.基于API的Redis缓存实现 1.Spring Boot支持的缓存组件 在Spring Boot中,数据的缓存管理存储依赖于Spring框架中cache相关的org.springframework.cache.Cache和org.springframework.cache.CacheManager缓存管理器接口. 如果程序中没有定义类型为CacheManager的Bean组件或者是名为cacheResolve

  • Spring Boot + Mybatis多数据源和动态数据源配置方法

    网上的文章基本上都是只有多数据源或只有动态数据源,而最近的项目需要同时使用两种方式,记录一下配置方法供大家参考. 应用场景 项目需要同时连接两个不同的数据库A, B,并且它们都为主从架构,一台写库,多台读库. 多数据源 首先要将spring boot自带的DataSourceAutoConfiguration禁掉,因为它会读取application.properties文件的spring.datasource.*属性并自动配置单数据源.在@SpringBootApplication注解中添加ex

  • Spring + Spring Boot + MyBatis + MongoDB的整合教程

    前言 我之前是学Spring MVC的,后面听同学说Spring Boot挺好用,极力推荐我学这个鬼.一开始,在网上找Spring Boot的学习资料,他们博文写得不是说不好,而是不太详细. 我就在想我要自己写一篇尽可能详细的文章出来,下面话不多说了,来一看看详细的介绍吧. 技术栈 Spring Spring Boot MyBatis MongoDB MySQL 设计模式 MVC 功能 注册(用户完成注册后是默认未激活的,程序有个定时器在检测没有激活的用户,然后发一次邮件提醒用户激活) 登录 发

  • Spring Cache整合Redis实现方法详解

    导入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>

随机推荐