Spring Boot JpaRepository knowledge learning (Spring Data JPA)

1. Problems solved by
Spring Data Spring Data: Provides a complete set of data access layer (DAO) solutions and is committed to reducing the amount of data access layer (DAO) development. It is based on an interface class called Repository, which is defined as a super interface for accessing the underlying data model. For a specific data access operation, it is defined in its sub-interface.
public interface Repository<T, ID extends Serializable> {
}

All interfaces that inherit this interface are managed by spring. This interface is used as an identification interface, and its function is to control the domain model.
Spring Data allows us to define only interfaces, as long as we follow the specifications of spring data, there is no need to write implementation classes.

Configuration file:
spring:
  application:
    name: service-client
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@ip:port:xx
    username: xxx
    password: xxxxx
  jpa:
    database: oracle



import com.springcloud.eurekaclient.jpa.dao.DemoUserRepository;
import com.springcloud.eurekaclient.jpa.entity.DemoUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.bind.annotation.*;

@SpringBootApplication
@EnableEurekaClient
@RestController
@EnableJpaRepositories(basePackages = "com.springcloud.eurekaclient.jpa")
@ComponentScan(basePackages = {"com.springcloud.eurekaclient"})
@EntityScan(basePackages="com.springcloud.eurekaclient.jpa")
public class EurekaclientApplication {

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



Note:
To use JpaRepository to implement additions, deletions, and changes, the following operations are required:

1. Add the JPA dependency package (jdbc database related) in pom.xml 2. The
User.java class needs to add the @Entity annotation, which needs to be added to the properties of the class @Id or @Column annotation
3. The UserRepository.java interface needs to implement the JpaRepository interface. By default, there are add and delete methods, and the modification method can be defined by yourself
. 4. The startup class needs to add two annotations, namely: @EnableJpaRepositories(basePackages="com.etc .*") and @EntityScan(basePackages="com.etc.*")

entity classes (note the ID generation strategy):
@Entity
@Table(name="DEMO_USER")
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class DemoUser{

    @Id
    @GeneratedValue(generator="system_uuid")
    @GenericGenerator(name="system_uuid",strategy="uuid")
    private String id;

    @Column(name = "USER_NAME")
    private String userName ;

    private String sex;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "DemoUser{" +
                "id='" + id + '\'' +
                ", userName='" + userName + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}


2. What is Repository

2.1 Repository (repository): Coordinates between the domain and the data mapping layer through a collection-like interface used to access domain objects. This name is similar to what we usually call DAO. Here, we call the data access layer Repository according to this habit.
Spring Data provides us with several Repositories. The basic Repository provides the most basic data access functions, and several of its sub-interfaces extend some functions. Their inheritance relationship is as follows:
a.Repository: It is just an identifier, indicating that any inheriting it is a warehouse interface class, which is convenient for Spring to automatically scan and identify
b.CrudRepository: Inheriting Repository, it implements a set of CRUD-related methods
c.PagingAndSortingRepository:
Inherit CrudRepository ,
implement a set of methods related to page sorting

The defined XxxxRepository needs to inherit JpaRepository, so that our XxxxRepository interface has the capability of a general data access control layer.

2.2 Basic functions provided by
JpaRepository 2.2.1 CrudRepository<T, ID extends Serializable>:
This interface provides the most basic operations of adding, deleting, modifying and checking entity classes

T save(T entity);//Save a single entity
        Iterable<T> save(Iterable<? extends T> entities);//保存集合
        T findOne(ID id);//Find entity according to id
        boolean exists(ID id);//Determine whether the entity exists according to the id
        Iterable<T> findAll();//Query all entities, do not use or use with caution!
        long count();//Query the number of entities
        void delete(ID id);//Delete entity according to ID
        void delete(T entity);//Delete an entity
void delete(Iterable<? extends T> entities);//Delete a collection of entities
        void deleteAll();//Delete all entities, do not use or use with caution!


2.2.2 PagingAndSortingRepository<T, ID extends Serializable>
This interface provides paging and sorting functions
Iterable<T> findAll(Sort sort);//排序
        Page<T> findAll(Pageable pageable);//Paging query (including sorting function)


2.2.3 JpaRepository<T, ID extends Serializable>
This interface provides JPA related functions
List<T> findAll();//Find all entities
        List<T> findAll(Sort sort);//sort to find all entities
        List<T> save(Iterable<? extends T> entities);//保存集合
        void flush();//Execute cache synchronization with database
        T saveAndFlush(T entity);//Force persistence
        void deleteInBatch(Iterable<T> entities);//Delete an entity collection


3. Spring data query

3.1 Simple conditional query: query a certain entity class or collection
According to
the rules defined by Spring data, the query method starts with find|read|get . When conditional query is involved, the attributes of the condition are connected with the conditional keyword. It should be noted that Yes: Condition attributes are specified with the first letter uppercase and the rest lowercase.



For example: define an Entity entity class
class User{
private String firstname;
private String lastname;


When using the And conditional connection, it should be written like this:
findByLastnameAndFirstname(String lastname,String firstname);
The attribute name and number of the condition should be in one-to-one correspondence with the position and number of parameters

3.2 Using JPA NamedQueries (standard specification implementation)
This query is Defined by the standard JPA specification, it is directly declared on the Entity entity class. When calling, the method corresponding to the named query is defined in the interface, and Spring Data automatically completes the search for the named query according to the method name.
(1) Use the @NamedQuery annotation on the Entity entity class to directly declare a named query.
@Entity
@NamedQuery(name = "User.findByEmailAddress",
  query = "select u from User u where u.emailAddress = ?1")
public class User {

}

Note: Use the following annotations when defining multiple
@NamedQueries(value = {
                @NamedQuery(name = User.QUERY_FIND_BY_LOGIN,
                                        query = "select u from User u where u." + User.PROP_LOGIN
                                                + " = :username"),
        @NamedQuery(name = "getUsernamePasswordToken",
                        query = "select new com.aceona.weibo.vo.TokenBO(u.username,u.password) from User u where u." + User.PROP_LOGIN
                            + " = :username")})

(2) Define the method corresponding to (1) in the interface
public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByLastname(String lastname);

  User findByEmailAddress(String emailAddress);
}


3.3 Use @Query to customize the query (provided by Spring Data) (?1 form or @Param)
This query can be declared in the Repository method, get rid of constraints like named queries, and declare the query directly in the corresponding interface method, The structure is clearer, which is a specific implementation of Spring data.
E.g:
public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.emailAddress = ?1")
  User findByEmailAddress(String emailAddress);
}


3.4 The two annotations @Query and @Modifying perform update operations
are declared together to define personalized update operations. For example, it is most commonly used when only certain fields are updated. Examples are as follows:
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);


3.5 Index parameters and named parameters
(1) The index parameters are as follows, the index value starts from 1, the number of "?X" in the query needs to be the same as the number of parameters defined by the method, and the order must be consistent
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);


(2) Named parameters (this method is recommended)
can define the parameter name, and use @Param("parameter name") when assigning, regardless of the order. As follows:
public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
  User findByLastnameOrFirstname(@Param("lastname") String lastname,
                                 @Param("firstname") String firstname);
}


4. Transactionality (transaction)

4.1 Transactions that operate a single object
Spring Data provides a default transaction processing method, that is, all queries are declared as read-only transactions, and for persistence, update and delete objects are declared as transactional.
See org.springframework.data.jpa.repository.support.SimpleJpaRepository<T, ID>
@org.springframework.stereotype.Repository
@Transactional(readOnly = true)
public class SimpleJpaRepository<T, ID extends Serializable> implements JpaRepository<T, ID>,
                JpaSpecificationExecutor<T> {
……
@Transactional
        public void delete(ID id) {

                delete(findOne(id));
        }
……
}

For custom methods, if you need to change the default transaction mode provided by spring data, you can annotate the method with @Transactional

declaration
, according to the idea of ​​layered architecture, this part belongs to the business logic layer. Therefore, it is necessary to implement calls to multiple Repositories in the Service layer, and declare transactions on the corresponding methods.
E.g:
@Service(“userManagement”)
class UserManagementImpl implements UserManagement {

  private final UserRepository userRepository;
  private final RoleRepository roleRepository;

  @Autowired
  public UserManagementImpl(UserRepository userRepository,
    RoleRepository roleRepository) {
    this.userRepository = userRepository;
    this.roleRepository = roleRepository;
  }

  @Transactional
  public void addRoleToAllUsers(String roleName) {

    Role role = roleRepository.findByName(roleName);

    for (User user : userRepository.readAll()) {
      user.addRole(role);
      userRepository.save(user);
    }
}


5. Specifications about the DAO layer
5.1. For the case where you do not need to write an implementation class: define the XxxxRepository interface and inherit the JpaRepository interface. If the default interface methods provided by Spring data are not enough, you can use @Query to define personalized interface methods in it .

5.2. For the case where you need to write an implementation class: define the XxxxDao interface and inherit com.aceona.xxx.persistent.data.GenericDao
, write the XxxxDaoImpl implementation class and inherit com.aceona.xxxx.persistent.data.GenericJpaDao, and implement the XxxxDao interface Method Call the XxxxRepository interface and the XxxxDao interface

at the Service layer to complete the corresponding business logic

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326181865&siteId=291194637