Michael
Michael

Reputation: 189

How to use Spring Data Neo4j Repository save method with specific id?

I'm using Neo4j to create graphs. The below codes is an example for spring data Neo4j. I can save a node entity when no id property value is provided.

But how to save a node entiry with a specific id property value?

Model Class:

@Data
@NodeEntity
public class Person {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private String title;

    @Relationship(type = "ACTED_IN")
    private List<Movie> movies = new ArrayList<>();
}

Repository Class

public interface PersonRepository extends Neo4jRepository<Person, Long> {

    @Query("MATCH (n:Person {name:{name}}) RETURN n")
    List<Person> findByName(@Param("name") String name);
}

Controller Class

@RestController
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private PersonRepository personRepository;

    @PostMapping("/save")
    public Map save(@RequestBody Person person) {
        Map resultMap = new HashMap();
        String code = "200";
        String msg = "success";
        // It can save success when no id property value is provided
        Person savedPerson = personRepository.save(person);
        resultMap.put("code", code);
        resultMap.put("msg", msg);
        resultMap.put("data", savedPerson);
        return resultMap;
    }
}

Upvotes: 2

Views: 1260

Answers (1)

Jatish
Jatish

Reputation: 392

I have tried it successfully and can be easily done provide the "id" should be

String not Long

Domain/DAO class:

 @Id
 @GeneratedValue(strategy = Neo4JCustomIdStrategy.class)
 String id;

Repository Class:

@Repository

public interface PersonRepository extends Neo4jRepository<Person, String>{
}

And lastly, custom implementation of Strategy:

public class Neo4JCustomIdStrategy implements IdStrategy {

  @Override
  public Object generateId(Object entity) {
    return String.valueOf(entity.hashCode());
  }
}

The library I am using is spring-data-neo4j

Upvotes: 1

Related Questions