Redis @Reference не работает в Spring Data Redis

Я сталкиваюсь с проблемами при реализации @Reference в Spring Boot + Spring Data Redis. Address — это список в Employee, и когда я сохранил адреса office и home, я ожидал, что данные будут сохранены с Employee. Но данные не были сохранены и, следовательно, невозможно выполнить поиск Address с помощью street.

Сотрудник.java

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("employees")
public class Employee {
    @Id @Indexed
    private String id;
    private String firstName;
    private String lastName;

    @Reference
    private List<Address> addresses;
} 

Адрес.java

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("address")
public class Address {
    @Id
    private String id;
    @Indexed
    private String street;
    private String city;
}

Тестовый класс

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class EmployeeAdressTest extends RepositoryTestSupport{
    @Autowired private EmployeeRepository employeeRepository;


    @Before
    public void setUp() throws JsonProcessingException {
        Address home = Address.builder().street("ABC Street").city("Pune").build();
        Address offc = Address.builder().street("XYZ Street").city("Pune").build();

        Employee employee1 = Employee.builder().firstName("Raj").lastName("Kumar").addresses(Arrays.asList(home, offc)).build();
        employeeRepository.save(employee1);


        List<Employee> employees = employeeRepository.findByAddresses_Street("XYZ Street");
        System.out.println("EMPLOYEE = "+employees);
    }

    @Test
    public void test() {

    }
}

Весенний документ:

8.8. Persisting References
Marking properties with @Reference allows storing a simple key reference instead of copying values into the hash itself. On loading from Redis, references are resolved automatically and mapped back into the object, as shown in the following example:

Example 30. Sample Property Reference
_class = org.example.Person
id = e2c7dcee-b8cd-4424-883e-736ce564363e
firstname = rand
lastname = al’thor
mother = people:a9d4b3a0-50d3-4538-a2fc-f7fc2581ee56      
Reference stores the whole key (keyspace:id) of the referenced object.

?


person Pra_A    schedule 20.11.2018    source источник


Ответы (1)


Spring Data Redis требует, чтобы вы сохраняли объекты, хранящиеся в home и office, отдельно от ссылающегося объекта employee1.

Это (теперь) указано в официальной документации в самом конце главы 8.8: https://docs.spring.io/spring-data-redis/docs/current/reference/html/#redis.repositories.references

Поэтому, если вы сохраните home и office в базу данных перед сохранением employee1, все будет в порядке.

То же самое, кстати, справедливо для обновлений, которые вы сделаете для объектов, на которые ссылаетесь, позже. Простое сохранение ссылочного объекта не сохраняет обновления ссылочных объектов.

person Christian Rühl    schedule 07.03.2019