Creating database queries and access the information from database is a tedious and aged one. JPA repository makes the database queries easier . you don't need to worry about the syntax of relational databases and it is a portable one.
Adding JPA repository into pom.xml,
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data}</version>
</dependency>
Persisting an entity
Saving an entity can be performed using the
CrudRepository.save()
-Method using JPA EntityManager
. If the entity has not been persisted yet Spring Data JPA will save the entity via a call to the entityManager.persist()
-Method, otherwise theentityManager.merge()
-Method will be called.
Spring Data JPA uses the following strategy to detect whether an entity is new or old one.
By default Spring Data JPA inspects the Id-Property of the specified Entity. If the Id-Property is null, then the entity will be assumed as new one, otherwise as old one.
Query Creation
Generally the query creation mechanism for JPA works . Here's a short example of what a JPA query method translates into:
Query creation from method names
Query creation from method names
public interface ProfileRepository extends Repository<Profile, Long> {
List<Profile> findByEmailAddressAndFirstname(String emailAddress, String firstname);
}
@QUERY
You can create custom Jpa Queries with in @Query annotation ,
@Transactional
@Query(value = "UPDATE user SET otp=:otp, last_modified_date=now() WHERE user_id=:userId", nativeQuery = true)
public int updateOtp(@Param("userId") String userId, @Param("otp") String otp);
@Modifying - we need to use this annotation for any update to table (it will use safe update zero)
@Transactional - for a query to execute as a single seperate transaction
@Query - put your query here.
@Param - parameters used in this query (name with in double quotes should be the same one as mentioned in the query with colon at front).
nativeQuery = true -for native queries like mysql queries.
for writing hibernate based hql queries ,
@Modifying
@Transactional
@Query("UPDATE User SET otp=:otp, lastModifiedDate=now() WHERE userId=:userId")
public int updateOtp(@Param("userId") String userId, @Param("otp") String otp);
To know more about Hibernate click here.
Named Queries
Within @NamedQuery annotation , specify the method name you need to call in your service in name property.
and specify hql query in query property.
@Entity
@NamedQuery(name = "Profile.findByEmailAddress",
query = "select p from Profile p where p.emailAddress = ?1")
public class Profile{
}
Jpa repository inherited from CrudRepository, we can use many methods from CrudRepository without the need to implement them ourself. Some of these methods are:
save - used to save an entity
findOne - find the specified row with primary key.
exists - to check the specified row exists in table
findAll - to get all the rows from the specified table.
count - to get the number of rows in the table
delete - to delete the specified row with id.
deleteAll - to delete all data from table.
eg:
userRepository.save(user);
here user is the entity to be persisted and userrepository is the jpa repository.
We can also define our own methods. These method names should use special keywords such as “find”, “order” with the name of the variables. Available Jpa methods have listed below,
Jpa Repository methods and meaning
1) And
findByLastnameAndFirstname
means
where x.lastname = ?1 and x.firstname = ?2
------------------------------------------------------
2) Or
findByLastnameOrFirstname
means
where x.lastname = ?1 or x.firstname = ?2
------------------------------------------------------
3) Is,Equals
findByFirstname,findByFirstnameIs,findByFirstnameEquals
means
where x.firstname = 1?
------------------------------------------------------
4) Between
findByStartDateBetween
means
where x.startDate between 1? and ?2
------------------------------------------------------
5) LessThan
findByAgeLessThan
means
where x.age < ?1
------------------------------------------------------
6) LessThanEqual
findByAgeLessThanEqual
means
where x.age <= ?1
------------------------------------------------------
7) GreaterThan
findByAgeGreaterThan
means
where x.age > ?1
------------------------------------------------------
8) GreaterThanEqual
findByAgeGreaterThanEqual
means
where x.age >= ?1
------------------------------------------------------
9) After
findByStartDateAfter
means
where x.startDate > ?1
------------------------------------------------------
10) Before
findByStartDateBefore
means
where x.startDate < ?1
------------------------------------------------------
11) IsNull
findByAgeIsNull
means
where x.age is null
------------------------------------------------------
12) IsNotNull,NotNull
findByAge(Is)NotNull
means
where x.age not null
------------------------------------------------------
14) Like
findByFirstnameLike
means
where x.firstname like ?1
------------------------------------------------------
15) NotLike
findByFirstnameNotLike
means
where x.firstname not like ?1
------------------------------------------------------
16) StartingWith
findByFirstnameStartingWith
means
where x.firstname like ?1 (parameter bound with appended %)
------------------------------------------------------
17) EndingWith
findByFirstnameEndingWith
means
where x.firstname like ?1 (parameter bound with prepended %)
------------------------------------------------------
18) Containing
findByFirstnameContaining
means
where x.firstname like ?1 (parameter bound wrapped in %)
------------------------------------------------------
19) OrderBy
findByAgeOrderByLastnameDesc
means
where x.age = ?1 order by x.lastname desc
------------------------------------------------------
20) Not
findByLastnameNot
means
where x.lastname <> ?1
------------------------------------------------------
21) In
findByAgeIn(Collection<Age> ages)
means
where x.age in ?1
------------------------------------------------------
22) NotIn
findByAgeNotIn(Collection<Age> age)
means
where x.age not in ?1
------------------------------------------------------
23) True
findByActiveTrue()
means
where x.active = true
------------------------------------------------------
24) False
findByActiveFalse()
means
where x.active = false
------------------------------------------------------
25) IgnoreCase
findByFirstnameIgnoreCase
means
where UPPER(x.firstame) = UPPER(?1)
No comments:
Post a Comment