本系列前面的文章
使用redisTemplate操作数据
将对象一次性hash入库的方法
方法一:使用Jackson2HashMapper
@Resource(name="redisTemplate")
private HashOperations<String, String, Object> jacksonHashOperations;
private HashMapper<Object, String, Object> jackson2HashMapper = new Jackson2HashMapper(false);
@Test
public void testHashPutAll(){
PictureVO p = new PictureVO(Long.valueOf(17),"byrant","a");
//将对象以hash的形式放入数据库
Map<String,Object> mappedHash = jackson2HashMapper.toHash(p);
jacksonHashOperations.putAll("picture" + p.getId(), mappedHash);
//将对象从数据库取出来
Map<String,Object> loadedHash = jacksonHashOperations.entries("picture" + p.getId());
Object map = jackson2HashMapper.fromHash(loadedHash);
PictureVO getback = new ObjectMapper().convertValue(map,PictureVO.class);
Assert.assertEquals(p.getAuthor(),getback.getAuthor());
}
方法二:使用redis repository
1.在要序列化的类上加上注解@RedisHash(“xxx”)
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@RedisHash("pictures")
public class PictureVO implements Serializable {
private static final long serialVersionUID = -8985545025228238754L;
@Id
private Long id;
private String author;
private String type;
}
2.继承CrudRepository接口,获取基本的CRUD操作
ackage com.example.mytoken.dao;
import com.example.mytoken.model.PictureVO;
import org.springframework.data.repository.CrudRepository;
public interface PictureRepository2 extends CrudRepository<PictureVO, Long> {
// 继承CrudRepository,获取基本的CRUD操作
}
3.在项目入口方法上加上注解@EnableRedisRepositories
@SpringBootApplication
@EnableRedisRepositories
public class MytokenApplication {
public static void main(String[] args) {
SpringApplication.run(MytokenApplication.class, args);
}
}
4.测试
package com.example.mytoken;
import com.example.mytoken.dao.PictureRepository2;
import com.example.mytoken.jpa.Picture;
import com.example.mytoken.jpa.PictureRepository;
import com.example.mytoken.model.PictureVO;
import javafx.application.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisRepositoryTest {
@Autowired
PictureRepository2 pictureRepository2;
@Test
public void test(){
PictureVO rand = new PictureVO(Long.valueOf(19),"LJR","NB");
pictureRepository2.save(rand);
Optional<PictureVO> op = pictureRepository2.findById(rand.getId());
PictureVO p2 = op.get();
pictureRepository2.count();
//pictureRepository2.delete(rand);
}
@Test
public void testDelete(){
pictureRepository2.deleteById(Long.valueOf(19));
}
}