Social Media

Category Archives for Spring Data

Spring Data JPA – Custom Repository

Another useful feature of Spring Data is defining custom repositories. These involve defining two additional artifacts for your Spring data repository –

  • Custom Repository interface
  • Custom Repository implementation

Example

1. Define custom repository interface –

public interface CustomExampleRepositoryCustom {
Integer customExampleMethod(String stringIn);
}

2. Define implementation class –

public class CustomExampleRepositoryCustomImpl implements CustomExampleRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public Integer customExampleMethod(String stringIn) {
return new Integer(1);
}
}

3. Extend your Spring Data Repository –

public interface CustomExampleRepository extends CrudRepository<Documents, Long>, CustomExampleRepositoryCustom {
}

4. We can then inject and call the method as we normally would –

@Autowired
private CustomExampleRepository customExampleRepository;
Integer callCustomExampleMethodInteger = customExampleRepository.customExampleMethod("Hello World");
1 12 13 14