When use getOne and findOne methods Spring Data JPA

TL;DR T findOne(ID id) (name in the old API) / Optional<T> findById(ID id) (name in the new API) relies on EntityManager.find() that performs an entity eager loading. T getOne(ID id) relies on EntityManager.getReference() that performs an entity lazy loading. So to ensure the effective loading of the entity, invoking a method on it is required. … Read more

How to add custom method to Spring Data JPA

You need to create a separate interface for your custom methods: public interface AccountRepository extends JpaRepository<Account, Long>, AccountRepositoryCustom { … } public interface AccountRepositoryCustom { public void customMethod(); } and provide an implementation class for that interface: public class AccountRepositoryImpl implements AccountRepositoryCustom { @Autowired @Lazy AccountRepository accountRepository; /* Optional – if you need it */ … Read more

What is this spring.jpa.open-in-view=true property in Spring Boot?

The OSIV Anti-Pattern Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram. The OpenSessionInViewFilter … Read more

Spring CrudRepository findByInventoryIds(List inventoryIdList) – equivalent to IN clause

findByInventoryIdIn(List<Long> inventoryIdList) should do the trick. The HTTP request parameter format would be like so: Yes ?id=1,2,3 No ?id=1&id=2&id=3 The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn … Read more

Spring Boot – Loading Initial Data

You can create a data.sql file in your src/main/resources folder and it will be automatically executed on startup. In this file you can add some insert statements, eg.: INSERT INTO users (username, firstname, lastname) VALUES (‘lala’, ‘lala’, ‘lala’), (‘lolo’, ‘lolo’, ‘lolo’); Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your … Read more

How to use OrderBy with findAll in Spring Data

public interface StudentDAO extends JpaRepository<StudentEntity, Integer> { public List<StudentEntity> findAllByOrderByIdAsc(); } The code above should work. I’m using something similar: public List<Pilot> findTop10ByOrderByLevelDesc(); It returns 10 rows with the highest level. IMPORTANT: Since I’ve been told that it’s easy to miss the key point of this answer, here’s a little clarification: findAllByOrderByIdAsc(); // don’t miss … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)