Spring Data, Is to provide familiar and consistent be based on Spring Programming model , At the same time, it still retains the special characteristics of the underlying data storage .

It is for data access technology , Relational and non relational databases ,map-reduce Frameworks and cloud based data services become easier .Spring Data It's an umbrella project , among Contains many database specific subprojects .


First , Let's take a look at the general introduction of this article .

How can we know how many dry goods there are in this article without a catalog ?

  • Spring Data What is it?

  • Spring Data Can do

  • Spring Data One of the first HelloWorld Program

  • Determine the method by name

  • Query in the form of annotation

  • Write local SQL Inquire about

  • How to add, delete and change

  • Use the method of adding, deleting, modifying and querying provided in the framework

  • Paging and sorting

  • JpaRepository Use

Is it very clear , Now let's start with the text , one by one :

Spring Data What is it?

In our traditional development , Our whole DAO Layer code is relatively , It's all complicated , under these circumstances ,Spring The team has one problem in mind , Can we develop a framework , This framework can minimize DAO Layer development ?

Spring Data To simplify DAO A framework for layer operations

The traditional addition, deletion and modification are in our Spring Data Has been realized in , That is to say, most of DAO You don't need to write the layer operation part , You just need to write complex business calls

Write this part of the code , You need to write an interface statement , No need to write the implementation , This implementation is automatic

Spring Data Can do

Main uses :

  • The traditional method of adding, deleting, modifying and checking

  • Sort

  • Pagination

  • Sort and paginate

Even if you need to write DAO, Just write a statement , No need to write the implementation

Spring Data One of the first HelloWorld Program (JPA、Hibernate、Spring、SpringMVC、Spring Data)

Guide pack

Writing configuration files

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context" 
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:jpa="http://www.springframework.org/schema/data/jpa"
 xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/data/jpa 
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">
        
        <!-- introduce Properties file -->
        <context:property-placeholder location="classpath:config/db.properties"/>
        
        <!-- To configure c3p0 The connection pool -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${driverClass}"></property>
            <property name="jdbcUrl" value="${url}"></property>
            <property name="user" value="${user}"></property>
            <property name="password" value="${password}"></property>
            <property name="acquireIncrement" value="${acquireIncrement}"></property>
            <property name="maxPoolSize" value="${maxPoolSize}"></property>
            <property name="minPoolSize" value="${minPoolSize}"></property>
            <property name="maxStatements" value="${maxStatements}"></property>
        </bean>
        
        <!-- To configure JPA The adapter that implements the product -->
        <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        </bean>
        
        <!-- To configure EntityManager object -->
        
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
           <!-- Inject data source -->
           <property name="dataSource" ref="dataSource"></property>
           <!-- scanning entity Bag --> 
           <property name="packagesToScan" value="com.qy.helloworld"></property>
           <!-- Inject JPA The adapter that implements the product -->
           <property name="jpaVendorAdapter" ref="jpaVendorAdapter"></property>
           <!-- The configuration is Hibernate Other configurations for    Besides connecting to the database 4 The rest of the configuration beyond the big elements -->
           <property name="jpaProperties">
              <props>
               <!-- Create table automatically  -->
               <prop key="hibernate.hbm2ddl.auto">update</prop>
               <!-- Configure whether to display SQL-->
               <prop key="hibernate.show_sql">true</prop>
               <!-- Is it formatted SQL-->
               <prop key="hibernate.format_sql">true</prop>
               <!-- Dialect connecting to the database -->
               <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            </props>
           </property>
        </bean>
        
        
        <!-- Configure the transaction environment -->
        
        <bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
           <!-- Inject dataSource-->
           <property name="dataSource" ref="dataSource"></property>
           <!-- Inject entityManagerFactory object -->
           <property name="entityManagerFactory" ref="entityManagerFactory"></property>
        </bean>
        
        <!-- With a transaction -->
        <tx:annotation-driven transaction-manager="jpaTransactionManager"/>
        
        <!-- To configure AOP Automatic proxy -->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 
        
        <!-- To configure Spring A bag scan of -->
        <context:component-scan base-package="com.qy.helloworld"></context:component-scan>
        
        <!--Spring data Scanning of the package    The scan here is DAO The location of the layer -->
        <jpa:repositories base-package="com.qy.helloworld" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="jpaTransactionManager"></jpa:repositories>
</beans>

Write entity classes and mappings

@Entity
@Table(name="t_user")
public class User {
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int userId;
 
 private String userName;
 
 private String password;
}

To write Repository class

public interface UserRepository extends Repository<User,Integer>{
 /**
  *  This means by id Find users
  * @Title: getByUserId   
  * @Description: TODO
  * @param: @param userId
  * @param: @return      
  * @return: User      
  * @throws
  */
 public User getByUserId(int userId);
}

test

ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml");
  // obtain DAO The object of
  UserRepository userRepository=applicationContext.getBean(UserRepository.class);
 User users=userRepository.findByUserId(1);
}

Determine the method by name

Code demonstration :

Examples are as follows

public interface UserRepository extends Repository<User,Integer>{
 /**
  *  This means by id Find users
  * @Title: getByUserId   
  * @Description: TODO
  * @param: @param userId
  * @param: @return      
  * @return: User      
  * @throws
  */
 public User getByUserId(int userId);
 
 /**
  *  Remember that the beginning of a query can only be   get  perhaps   find  start    By: Through what inquiry
  * @Title: findByUserId   
  * @Description: TODO
  * @param: @param userId
  * @param: @return      
  * @return: User      
  * @throws
  */
 public User findByUserId(int userId);
 
 /**
  *  Fuzzy query through user name
  * @Title: findByUserNameLike   
  * @Description: TODO
  * @param: @param userName
  * @param: @return      
  * @return: List<User>      
  * @throws
  */
 public List<User> findByUserNameLike(String userName);
 
 /**
  *  Through user name and password Like To query
  * @Title: findByUserNameLikeAndPasswordLike   
  * @Description: TODO
  * @param: @param userName
  * @param: @return      
  * @return: List<User>      
  * @throws
  */
 public List<User> findByUserNameLikeAndPasswordLike(String userName,String password);
 /**
  *  User name and password like  then id Less than a range
  * @Title: findByUserNameLikeAndPasswordLikeAndUserIdLessThan   
  * @Description: TODO
  * @param: @param userName
  * @param: @param password
  * @param: @param userId
  * @param: @return      
  * @return: List<User>      
  * @throws
  */
 public List<User> findByUserNameLikeAndPasswordLikeAndUserIdLessThan(String userName,String password,int userId);
}

Be careful : In general, the corresponding method will not be written directly by name , Because if there are too many conditions, then we have the problem of very long names at this time

Query is realized through annotation mode

Code demonstration :

Examples are as follows

 /**
     *  Query all    Direct query without conditions
     * @Title: findUserAll   
     * @Description: TODO
     * @param: @return      
     * @return: List<User>      
     * @throws
     */
 @Query("from User")
 public List<User> findUserAll();
 
 /**
  *  adopt id To find the data       The parameters are spliced directly to the back
  * @Title: findUserById   
  * @Description: TODO
  * @param: @param userId
  * @param: @return      
  * @return: List<User>      
  * @throws
  */
 @Query("from User u  where u.userId<3")
 public List<User> findUserById();
 /**
  *  adopt id Where there are placeholders in the query
  * @Title: findUserById1   
  * @Description: TODO
  * @param: @param userId
  * @param: @return      
  * @return: List<User>      
  * @throws
  */
 @Query("from User u  where u.userId<?")
 public List<User> findUserById1(int userId);
 
 /**
  *  Multi condition query    You can specify the location of the current parameter mapping
  * @Title: getUserByNameAndId   
  * @Description: TODO
  * @param: @param userName
  * @param: @param userId
  * @param: @return      
  * @return: User      
  * @throws
  */
 @Query("from User u where u.userId=?2 and u.userName=?1")
 public User getUserByNameAndId(String userName,int userId);
 
 /**
  *  Dynamic stitching when fuzzy query   % The problem of
  * @Title: findUserByLike1   
  * @Description: TODO
  * @param: @param userName
  * @param: @return      
  * @return: List<User>      
  * @throws
  */
 @Query("from User u where u.userName like concat ('%',?,'%')")
 public List<User> findUserByLike1(String userName);

Write local SQL Inquire about

Code demonstration :

Examples are as follows

 /**
  *  adopt
  * @Title: findUserAll11   
  * @Description: TODO
  * @param: @return      
  * @return: List<User>      
  * @throws
  */
 @Query(nativeQuery=true,value="select * from t_user")
 public List<User> findUserAll11();

How to add, delete and change

Code demonstration :

Add business logic Add transaction environment

 @Service
@Transactional                  // Provide a transactional environment
public class UserService {
 
 @Autowired
 private UserRepository userRepository=null;
 
 /**
  *  Update of data
  * @Title: update   
  * @Description: TODO
  * @param: @param userName
  * @param: @param password
  * @param: @param userId      
  * @return: void      
  * @throws
  */
 public void update(String userName,String password,int userId){
  userRepository.update(userName, password, userId);
 }
 
 
 public void delete(int userId){
  userRepository.delete(userId);
 }
 
 public void insert(String userName,String password){
  userRepository.insert(userName, password);
 }
}

To write repository The object of

 public interface UserRepository extends Repository<User,Integer>{
 /**
  *  How to add, delete and modify
  * @Title: add   
  * @Description: TODO
  * @param: @param userName
  * @param: @param password      
  * @return: void      
  * @throws
  */
 @Modifying    // The purpose of this annotation is to update the data
 @Query("update User u set u.userName=?,u.password=? where u.userId=?")
 public void update(String userName,String password,int userId);
 
 /**
  *  Update data
  * @Title: delete   
  * @Description: TODO
  * @param: @param userId      
  * @return: void      
  * @throws
  */
 @Modifying    // The purpose of this annotation is to update the data
 @Query("delete User u where u.userId=?")
 public void delete(int userId);
 /**
  *  Add data
  * @Title: insert   
  * @Description: TODO
  * @param: @param userName
  * @param: @param password      
  * @return: void      
  * @throws
  */
 @Modifying    // The purpose of this annotation is to update the data
 @Query(nativeQuery=true,value="insert into t_user(userName,password) values(?,?)")
 public void insert(String userName,String password);
 
}

test

 @Test
 public void testHelloWorld() throws Exception {
  
  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml");
  // obtain DAO The object of
  UserService userService=applicationContext.getBean(UserService.class);
  userService.insert(" Small feather "," Programming ");
 }

Use the method of adding, deleting, modifying and querying provided in the framework

Code demonstration :

What is offered is Repository

 public interface UserRepository extends CrudRepository<User,Integer>{
}

Paging and sorting

Code demonstration :

Provided Repository

 public interface UserRepository extends PagingAndSortingRepository<User,Integer>{
}

test

 public class Test001 {
 
 @Test
 public void testPaging() throws Exception {
  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml");
  // obtain DAO The object of
  UserRepository userRepository=applicationContext.getBean(UserRepository.class);
 /**
  *  The first parameter : What is the number of pages on the current page    The number of pages is from 0 At the beginning     The second page :2-1
  *  The second parameter : Represents the number of entries per page
  */
  Page<User> pages=userRepository.findAll(new PageRequest(2-1,2));
 
  System.out.println(" Data queried :"+pages.getContent());
  System.out.println(" The number of entries in the data :"+pages.getSize());
  System.out.println(" the number of pages :"+pages.getNumber());
  System.out.println(" The total number of data entries :"+pages.getTotalElements());
  System.out.println(" The total number of pages :"+pages.getTotalPages());
  System.out.println(" The rules of sorting :"+pages.getSort());
 
 }
 
 /**
  *  Sort
  * @Title: testSort   
  * @Description: TODO
  * @param: @throws Exception      
  * @return: void      
  * @throws
  */
 @Test
 public void testSort() throws Exception {
  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml");
  // obtain DAO The object of
  UserRepository userRepository=applicationContext.getBean(UserRepository.class);
  /**
   *  Sort
   *  The first parameter : Ascending or descending   Direction.ASC/DESC
   *  The second parameter :  The sorted column
   */
  List<User> users=(List<User>) userRepository.findAll(new Sort(Direction.DESC,"userId"));
  
  System.out.println(users);
 }
 
 /**
  *  Sort and paginate
  * @Title: testSortAndPaging   
  * @Description: TODO
  * @param: @throws Exception      
  * @return: void      
  * @throws
  */
 @Test
 public void testSortAndPaging() throws Exception {
  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml");
  // obtain DAO The object of
  UserRepository userRepository=applicationContext.getBean(UserRepository.class);
  
  Page<User> pages=userRepository.findAll(new PageRequest(2-1,2,new Sort(Direction.DESC,"userId")));
  
  System.out.println(pages.getContent());
 }
}

JpaRepository Use

Code demonstration :

Provided repository

 public interface UserRepository extends JpaRepository<User,Integer>{
}

test

 public class Test001 {
 @Test
 public void testPaging() throws Exception {
  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml");
  // obtain DAO The object of
  UserRepository userRepository=applicationContext.getBean(UserRepository.class);
    
//  long count=userRepository.count();
  
//  User user=userRepository.findOne(15);
//  user.setUserName(" Small feather ");
  
  // Save or update data
//  userRepository.saveAndFlush(user);
  
 
  List<User> users=userRepository.findAll();
  
  // The batch
  userRepository.deleteInBatch(users);
   
  //System.out.println(" Statistics :"+count);
 }
}

Conclusion

Spring Data It's a technology that we often use in our development , It involves more technology and knowledge than those listed above .

Follow up shallow feather will continue to update about Spring Data Development knowledge of , I just hope it can help you , Thank you for your support !

Writing with original intention , Committed to let every Internet person make progress together .

Good articles in the past

Previous recommendation

Spring Data Development Manual |Java Persistence API(JPA) How much do you need to know ?

Dynamic resource technology JSP|Java And Html The beautiful meeting of

Whether can food | The technology is more and more new , I love my old friends jQuery Or love it as always

Farewell to praying programming | Unit test the correct landing position in the project

Component must know must know | The wheels we used for years —Filter and Proxy

ES Development of guidelines | How to get started quickly ElasticSearch

Get along well with Redis| Learn this 10 I'll let you take it every minute Redis, Satisfy all your doubts

Super detailed |Linux System from 0 To 1 The complete play of the game

If you think that asamura's article will help you , Please search and follow on wechat 「 Shallow feathered IT hut 」 WeChat official account , I'll share my computer information knowledge here 、 Theoretical Technology 、 Tool resources 、 The software is introduced 、 The backend development 、 interview 、 A series of articles, such as thoughts on work and some thoughts on life . What you see and what you get , It's all about life . take your time , Work harder , You and I grew up together ...

 

Dot , One button and three companies are here !