0

I am facing issues while implemeting @Reference in Spring Boot + Spring Data Redis. Address is a List in Employee and when I saved the office and home address and I was expecting the data to be saved with the Employee. But data did not get saved and hence unable to search the Address using street.

Employee.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;
} 

Address.java

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

Test class

@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() {

    }
}

Spring Doc:

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.

?

PAA
  • 1
  • 46
  • 174
  • 282

1 Answers1

0

Spring Data Redis requires you to save the objects stored in home and office separately from the referencing object employee1.

This is (now) stated in the official documentation at the very end of chapter 8.8: https://docs.spring.io/spring-data-redis/docs/current/reference/html/#redis.repositories.references

So if you save home and office to the database before saving employee1 you should be fine.

The same btw holds valid for updates you make to referenced objects later on. Just saving the referencing object alone does not save the updates on the referenced objects.