0

I am new to Spring Boot and I see that the CrudRepository interface is used by the Application-class. I see that the .save()-method from CrudRepository interface is called, but I don't understand where this method is implemented. Does this happen somewhere in the backend in Spring?

Here is the Application-class:

@SpringBootApplication
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    @Bean
    public CommandLineRunner demo(CustomerRepository repository) {
        return (args) -> {
            // save a couple of customers
            repository.save(new Customer("Jack", "Bauer"));
            repository.save(new Customer("Chloe", "O'Brian"));
            repository.save(new Customer("Kim", "Bauer"));
            repository.save(new Customer("David", "Palmer"));
            repository.save(new Customer("Michelle", "Dessler"));

            // fetch all customers
            log.info("Customers found with findAll():");
            log.info("-------------------------------");
            for (Customer customer : repository.findAll()) {
                log.info(customer.toString());
            }
            log.info("");

            // fetch an individual customer by ID
            repository.findById(1L)
                .ifPresent(customer -> {
                    log.info("Customer found with findById(1L):");
                    log.info("--------------------------------");
                    log.info(customer.toString());
                    log.info("");
                });

            // fetch customers by last name
            log.info("Customer found with findByLastName('Bauer'):");
            log.info("--------------------------------------------");
            repository.findByLastName("Bauer").forEach(bauer -> {
                log.info(bauer.toString());
            });
            // for (Customer bauer : repository.findByLastName("Bauer")) {
            //  log.info(bauer.toString());
            // }
            log.info("");
        };
    }

}

CustomerRepository extends CrudRepository:

public interface CustomerRepository extends CrudRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);
}
Draken
  • 3,134
  • 13
  • 34
  • 54
Nora
  • 1,825
  • 8
  • 31
  • 47
  • https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java – JB Nizet Aug 23 '19 at 10:37

3 Answers3

0

The following code can be found in the SimpleJpaRepository class:

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

I am sure there are more implementations available depending on what sort of database/persistence provider you have, but as you can see, it is a simple wrapper over the standard JPA implementation.

cameron1024
  • 9,083
  • 2
  • 16
  • 36
0

Yes, the CRUD repository would be based on the implementation that you are using. It should be Hibernate if you are using Hibernate as the implementation.

For every CRUD repository method specification, corresponding implementations such as Hibernate have different dialects written for different databases, that would convert these method invocations into SQL queries in the background.

0

According to where this has been answered Chan Chan:

JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.

Their main functions are:

CrudRepository mainly provides CRUD functions.

PagingAndSortingRepository provides methods to do pagination and sorting records.

JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.

Here is an example from my current project where I implemented CrudRepository, PagingAndSortingRepository and JpaRepository. So when you just need CRUD functions, you implement it. When you need pagination alongside CRUD. You go for PagingAndSortingRepository. Then when you need more functionalities, then JpaRepository suits you,

public interface CartRepository extends CrudRepository<ShoppingCart, Integer> {

    @Query("select max(s.itemId) FROM ShoppingCart s")
    public Integer findMaxItemId();

    public List<ShoppingCart> findByCartId(String cartId);

    public ShoppingCart findByItemId(int itemId);
}


public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {

    @Query(value = "select p from Product p where p.description = SUBSTRING(p.description, 1,:description_length)")
    List<Product> getAll(@Param("description_length")Integer description_length, Pageable pageable);
}


@RepositoryRestResource
public interface AttributesRepository extends JpaRepository<Attribute, Integer> {

    @Query("select new com.turing.ecommerce.DTO.AttributeDTO(a.attributeId, a.name)"
        + " from Attribute a ")
    List<AttributeDTO> findAllAttributes();
} 
Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
tksilicon
  • 3,276
  • 3
  • 24
  • 36