e2

滴滴侠,fai抖

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

spring-boot-starter-data-redis 2.1 以上支持以repository的方式存取对象了。

1,导入依赖包

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2,定义实体

@Data
public class Cat {

    //在需要条件查询的字段上加上@Indexed
    @Indexed
    private String name;

    private String color;
}
@Data
@ToString
@RedisHash(value = "user")
public class TUser {

    @Id
    private String id;
	 //在需要条件查询的字段上加上@Indexed
    @Indexed
    private String name;

    private String password;


    private Cat cat;


}

3,定义repository

支持方法名和example查询,前提查询字段必须是加了@Index注解。

public interface UserDao extends CrudRepository<TUser,String>,QueryByExampleExecutor<TUser> {

    TUser findByName(String name);

}

4,新增,查询测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDemoApplicationTests {

    @Autowired
    private UserDao userDao;
    

    @Test
    public void save() {
        Cat cat = new Cat();
        cat.setColor("hongse");
        cat.setName("小狗");
        TUser user = new TUser();
        user.setId("2");
        user.setName("haha");
        user.setPassword("heiheihei");
        user.setCat(cat);
        userDao.save(user);
    }


    @Test
    public void findOne(){
        TUser user = userDao.findById("2").get();
        System.out.println(user);
    }

    @Test
    public void findByExample(){
        TUser user = new TUser();
        Cat cat = new Cat();
        cat.setName("花花");
        user.setCat(cat);
        System.out.println(userDao.findOne(Example.of(user)));
    }

    @Test
    public void findByName(){
        System.out.println(userDao.findByName("hahaha"));
    }


}

5,Example查询局限

官方文档的一段话。

The following list shows properties not supported by Query by Example:

Case-insensitive matching

Regex, prefix/contains/suffix String-matching

Querying of Associations, Collection, and Map-like properties

Inclusion of null values from the criteria

findAll with sorting

可见对于list,map里包含对象的example查询,是无效的。

posted on 2022-05-03 18:40  纯黑Se丶  阅读(241)  评论(0编辑  收藏  举报