JPA of Spring Data series (1)

Introduction:

Spring Data is an open source framework under the SpringSource Foundation to simplify database access and support cloud services. Its main goal is to make database access convenient and fast, and to support map-reduce framework and cloud computing data services. For projects with massive data, Spring Data can be used to simplify project development.

However, relative class libraries are used to manipulate the access for different data storage accesses. Spring Data has provided us with some commonly used interfaces and implementation classes in many businesses to help us quickly build projects, such as paging, sorting, and some common operations of DAO.

Today, I mainly explain the JPA module under Spring Data.

Why Spring Data can help us build projects quickly, because Spring Data has already implemented common functions for us in the database access layer, and we only need to write an interface to inherit the interface provided by Spring Data to realize the database access layer. access and operation, similar to Spring-orm's TemplateDAO.

---------------------------------------------- evil dividing line -------------------------------------------------- ----------------------------
Core interface:

Let's take a look at the top-level interface of Repository:
Java code Collection code
public interface Repository<T , ID extends Serializable> { 
 


This interface is just an empty interface, the purpose is to unify all Repository types, the interface type uses generics, T in the generic parameter represents the entity type, and ID is the type of id in the entity.

Let's take a look at the methods in CrudRepository, the direct subinterface of Repository:
Java code Collection code
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> { 
 
    <S extends T> S save(S entity); 
 
    <S extends T> Iterable<S> save(Iterable<S> entities); 
 
    T findOne(ID id); 
 
    boolean exists(ID id); 
 
    Iterable<T> findAll(); 
 
    Iterable<T> findAll(Iterable<ID> ids); 
 
    long count(); 
 
    void delete(ID id); 
 
    void delete(T entity); 
 
    void delete(Iterable<? extends T> entities); 
 
    void deleteAll(); 


Most of the methods in this interface are some of the methods we commonly use in accessing the database. If we want to write our own DAO class, we only need to define an interface to integrate it and then use it.

Let's take a look at the interface PagingAndSortingRepository of the Repository that Spring Data does not provide for paging and sorting:
Java code Collection code
public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> { 
 
    Iterable<T> findAll(Sort sort); 
 
    Page <T> findAll(Pageable pageable); 


These Repositories are the core interfaces provided to us by spring-data-commons, which is the core package of Spring Data. This interface provides us with data paging methods and sorting methods. Look, spring-data saves us a lot of worry, everything is constructed according to this specification, and even some operations commonly used in business systems are taken into account for us, and we only need to pay more attention to the business logic layer . Spring-data divides the granularity of the repository very finely. In fact, I think the granularity of each class is finely divided in the spring framework, which is mainly for the separation of responsibilities.


---------------------------------------------- evil dividing line -------------------------------------------------- ----------------------------
JPA implementation:
A series of repository interfaces are provided for spring-data-jpa, including JpaRepository and JpaSpecificationExecutor. What is the difference between these two interfaces? Let's take a look at the source code of these two interfaces.

JpaRepository.class
Java code Collection code
public interface JpaRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> { 
 
    List<T> findAll(); 
 
    List<T> findAll(Sort sort); 
 
    <S extends T> List< S> save(Iterable<S> entities); 
    void flush(); 
 
    T saveAndFlush(T entity); 
 
    void deleteInBatch(Iterable<T> entities); 
 
    void deleteAllInBatch(); 

This class inherits from PagingAndSortingRepository. Looking at the methods, it can be seen that the methods in it are all simple operations and do not involve complex logic. When you are dealing with some simple data logic, you can inherit this interface and see a small example. The JPA provider selected in this article is Hibernate EntityManager. Of course, readers can also choose other JPA providers, such as EclipseLink and OpenJPA. Anyway, JPA is a standard and can be transplanted without modification.

First define a user entity class User.class:
Java code Collection code
@Entity 
@Table( name = "spring_data_user" ) @PrimaryKeyJoinColumn 
( name = "id" ) 
public class User extends IdGenerator{ 
 
    private static final long serialVersionUID = 1L; 
     
    private String name; 
    private String username; 
    private String password; 
    private String sex; 
    private Date birth; 
    private String address; 
    private String zip; 
         
        //Omit getter and setter 


The Id generation strategy is the table generation strategy used. I won't post the code here, and I won't post the spring configuration file. Anyway, those things are all over the Internet. I will attach the demo later.

The entity class is there. Now we have to write a persistence layer so that we can operate the database. Now let's take a look at the persistence layer. IUserDao.class:
Java code collection code
@Repository("userDao") 
public interface IUserDao extends JpaRepository<User, Long>{} 

and then add the following code to the spring configuration file.
Xml code Collection code
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:jpa="http ://www.springframework.org/schema/data/jpa" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/data/jpa 
    http: https://www.springframework.org/schema/data/jpa/spring-jpa. 
 
    <jpa:repositories base-package="org.tea.springdata.**.dao" /> 
</beans> 

After adding this paragraph, Spring will register the @Repository class in the specified package as a bean, and host the bean to Spring. This definition is finished and OK! Oh, so you can operate the database?
Yes, as I said earlier, Spring data has already written an implementation class for us, and for simple operations, we only need to inherit JpaRepository to do CRUD operations. Write another business class to test it. Since I use Cglib for dynamic proxy, I don't define the interface, and directly define the class UserService.class:
Java code Collection code
@Service("userService") 
public class UserService { 
     
    @Autowired 
    private IUserDao dao; 
     
    public void save(User user ) { 
        dao.save(user); 
    } 
 
    public void delete(Long id) { 
        dao.delete(id); 
    } 
 
    public void update(User user) { 
        dao.saveAndFlush(user); 
    } 
 
    public List<User> findAll() { 
        return dao.findAll(); 
    } 


来写一单元测试。
Java代码  收藏代码
public class UserServiceTest { 
     
    private static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 
     
    private static UserService userService = (UserService) context.getBean("userService"); 
     
    public void saveUser() { 
        StopWatch sw = new StopWatch(getClass().getSimpleName()); 
        sw.start("Add a user information."); 
        User u = new User(); 
        u.setName("John"); 
        u.setSex("Man"); 
        u.setUsername("JohnZhang"); 
        u.setPassword("123456"); 
        u.setBirth(new Date()); 
        userService.save(u); 
        sw.stop(); 
        System.err.println(sw.prettyPrint()); 
    } 
 
     public static void main(String[] args) { 
        UserServiceTest test = new UserServiceTest(); 
        test.saveUser(); 
    } 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326725214&siteId=291194637