Spring Data JPA introduction and dao layer (persistence layer) standard interface rules or custom methods

JPA Introduction

Introduced earlier, JPA JPA ORM specification is incorporated in JDK5 sun, it is an object ORM integration technology, standardized and standards. More mature JPA framework including Jboss of HibernateEntityManager, Oracle donated to the community EclipseLink Eclipse, Apache's OpenJPA and so on. Hibernate will use the following example to describe the JPA.

Use Hibernate EntityManager

Hibernate is independent of the spring itself, and without the use of spring framework, the Dao layer of code shown below, a standard time required persistence.xmlprofile

public class UserDaoImpl implements UserDao { 
	public AccountInfo save(AccountInfo accountInfo) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("SimplePU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(accountInfo); em.getTransaction().commit(); emf.close(); return accountInfo; } }

Use spring + Hibernate

If introduced in the project of the spring, spring for JPA provides a very friendly support can be used to automatically rather than manually inject new implementation class, the configuration is more flexible, the most important is the EntityManager Spring of creation and destruction, transaction management, etc. code is extracted by its unified management. Transaction management and EntityManager create, destroy all the code developers no longer need to care about.

Persistence Code:

@Repository("userDao") 
public class UserDaoImpl implements UserDao { @PersistenceContext private EntityManager em; @Transactional public Long save(AccountInfo accountInfo) { em.persist(accountInfo); return accountInfo.getAccountId(); } }

Profiles:

<?xml version="1.0" encoding="UTF-8"?> <beans...> <context:component-scan base-package="footmark.springdata.jpa"/> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <bean id="entityManagerFactory" class= "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> </bean> </beans>

Test code:

public class SimpleSpringJpaDemo{ 
	public static void main(String[] args){ ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring-demo-cfg.xml"); UserDao userDao = ctx.getBean("userDao", UserDao.class); userDao.createNewAccount("ZhangJianPing", "123456", 1); } }

Using Spring Data JPA

From the top you can see Spring JPA support has been very strong, developers only need to be concerned about core business logic implementation code, without too much concern related to the JPA EntityManager process of creation, transaction processing. But you will find dao persistence layer implementation logic or manually writing. Thereby giving rise Spring Data JPA, Spring Data JPA persistence layer can be automatically generated according to the method name to achieve the desired logic specification or standard interfaces provided by inheriting Repository, PagingAndSortingRepository, CrudRepositoryand JpaRepositoryother various methods substantially crud obtained automatically, or by annotation @QueryCustom Some complex implementations.

Notably Spring-data-jpa dependent on Hibernate.

Spring Data JPA in the background is the persistence layer interface to create a proxy object, there are three ways to achieve lasting functional layers:

  1. Access to basic crud methods by inheriting the standard interface
  2. The method of custom formats comply with the specified name, Spring Data JPA automatically named according to its function.
  3. Using the method above statement @Queryas an argument, Spring Data JPA when you create a proxy object, then the query provide to fulfill its function annotations, and provides a query. Or increasing the @Modifyingannotation to modify the query identifies the query (update operation)

Standard or custom interfaces inherit methods

For the Repository, PagingAndSortingRepository, CrudRepositoryand JpaRepositoryother interfaces developed by the persistence layer should be how to choose the time, the direct successor CrudRepositoryor PagingAndSortingRepositorythese interfaces are of course very easy to automatically have achieved a lot, but this presents a problem, it may expose you do not want to expose to the business method layer. For example, you only want certain interfaces provide increased operating without desirable to provide methods to delete. In view of this situation, developers can only return to the Repository interface, and then to copy the method declaration in CrudRepository want to keep the interface can be customized, of course, not so particular about the general simple system (erp), the how how come easy.

Spring Data JPA provides some keyword query expression conditions for custom queries, as follows:

  • And --- equivalent to the SQL and keywords, such as findByUsernameAndPassword (String user, Striang pwd);
  • Or --- equivalent to or keyword in SQL, such as findByUsernameOrAddress (String user, String addr);
  • BETWEEN --- equivalent to between keywords in SQL, such findBySalaryBetween (int max, int min);
  • LessThan --- SQL equivalent of "<", such findBySalaryLessThan (int max);
  • GreaterThan --- SQL equivalent of the ">", such findBySalaryGreaterThan (int min);
  • IsNull --- equivalent to the SQL "is null", such findByUsernameIsNull ();
  • IsNotNull --- SQL equivalent of "is not null", such findByUsernameIsNotNull ();
  • NotNull --- and IsNotNull equivalent;
  • Like --- SQL equivalent of "like", such findByUsernameLike (String user);
  • NotLike --- equivalent to the SQL in the "not like", such as findByUsernameNotLike (String user);
  • OrderBy --- equivalent to the SQL in "order by", such as findByUsernameOrderBySalaryAsc (String user);
  • Not --- equivalent to the SQL, such as findByUsernameNot (String user) "=!";
  • --- the In SQL equivalent to the "in", such findByUsernameIn (Collection userList), the parameter type Collection method may be, or may be an array variable length parameter;
  • Notin --- SQL equivalent of "not in", such findByUsernameNotIn (Collection userList), the parameter type Collection method may be, or may be an array variable length parameter;

Create a query using @Query

@Query notes very simple to use, simply mark the comment above the method declaration, while providing a JP QL queries can

public interface UserDao extends Repository<AccountInfo, Long> { @Query("select a from AccountInfo a where a.accountId = ?1") AccountInfo findByAccountId(Long accountId); @Query("select a from AccountInfo a where a.balance > ?1") Page<AccountInfo> findByBalanceGreaterThan( Integer balance,Pageable pageable); }

Developers can also perform an update operation by using @Query, to this end, we need to use the @Query with @Modifying to identify the operation to modify the query

@Modifying 
@Query("update AccountInfo a set a.salary = ?1 where a.salary < ?2") 
int increaseSalary(int after, int before);

Delete the wording slightly special:

@Transactional
int deleteByCountrycode(@Param("countrycode") String countrycode); 

springboot integrationSpring Data JPA

springboot official integration of Spring Data JPA Starter:  spring-boot-starter-data-jpa, which rely on integrated Hibernate, Spring Data JPAas well as Spring ORMs(Core ORM support from the Spring Framework ). Very simple to use.

First, add dependencies

<dependency
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Two, application.properties configuration

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop

Third, create entity

@Entity
public class User {
    @Id
    @GeneratedValue private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private Integer age; // 省略构造函数 // 省略getter和setter }

Fourth, create a data access interface

public interface UserRepository extends JpaRepository<User, Long> { User findByName(String name); User findByNameAndAge(String name, Integer age); @Query("from User u where u.name=:name") User findUser(@Param("name") String name); }

github have specific demo project implementation can reference, note the demo using H2-memory database.

Spring Data JPA support for transactions

By default, the method Spring Data JPA implementation are using transactions. A method for the query type, which is equivalent to @Transactional (readOnly = true); CRUD type method, is equivalent to @Transactional. As can be seen, in addition to the method of the query is set to read-only transactions, other transaction attributes are default values.

Of course, in addition to using the transaction annotation persistence layer outside, developers can also use @Transactional specify the transaction attributes in the business layer method, which is mainly a business layer method calls for the case of persistence method multiple times. The transaction will be determined persistence layer is a layer of pending business transaction or business affairs added layer according to the propagation of the transaction set.

 

When using Baidu search, there is no related articles found, only to see a Google search, it is reproduced once.

This article is reproduced to: https://github.com/jiwenxing/spring-boot-demo/wiki/Spring-Data-JPA

Guess you like

Origin www.cnblogs.com/timeout/p/11084382.html