1 dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2 实体类
@RedisHash(value = "persons")
public class Person {
@Id
private String id;
@Indexed
private String firstname;
@Indexed
private String lastname;
private Address address;
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", address=" + address +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
import org.springframework.data.redis.core.index.Indexed;
public class Address {
@Indexed
private String city;
@Indexed
private String country;
@Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", country='" + country + '\'' +
'}';
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
3 repository
public interface PersonRepository extends CrudRepository<Person,String> {
List<Person> findByAddress_City(String name);
}
4 redis配置
#配置redis的连接配置
#redis服务器地址
spring.redis.host=127.0.0.1
#redis服务器连接端口
spring.redis.port=6379
#redis服务器连接密码
spring.redis.password=
5 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootDemoApplicationTests {
@Test
public void savePerson(){
Person person = new Person();
person.setFirstname("张");
person.setLastname("三");
Address address = new Address();
address.setCity("北京");
address.setCountry("中国");
person.setAddress(address);
personRepository.save(person);
}
@Test
public void selectPerson(){
List<Person> list = personRepository.findByAddress_City("北京");
for (Person person : list) {
System.out.println(person);
}
}