自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Spring Data開發(fā)手冊|手把手教你簡化持久層開發(fā)工作

運(yùn)維 數(shù)據(jù)庫運(yùn)維
Spring Data,是為數(shù)據(jù)訪問提供熟悉且一致的基于Spring的編程模型,同時仍然保留底層數(shù)據(jù)存儲的特殊特性。

[[354211]]

 Spring Data,是為數(shù)據(jù)訪問提供熟悉且一致的基于Spring的編程模型,同時仍然保留底層數(shù)據(jù)存儲的特殊特性。

它是對于數(shù)據(jù)訪問技術(shù),關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫,map-reduce框架和基于云的數(shù)據(jù)服務(wù)變得容易。Spring Data是一個總括項(xiàng)目,其中包含很多特定于數(shù)據(jù)庫相關(guān)的子項(xiàng)目。


首先,先帶大家看一下本篇文章的大致介紹。

沒目錄怎么知道這篇到底有多少干貨呢?

  • Spring Data是什么
  • Spring Data能干什么
  • Spring Data的第一個HelloWorld程序
  • 通過名字來確定方法
  • 通過注解的形式來實(shí)現(xiàn)查詢
  • 寫本地的SQL查詢
  • 增刪改的玩法
  • 使用框架中提供的增刪改查的方法
  • 分頁和排序
  • JpaRepository的使用

是不是很清晰呢,現(xiàn)在開始進(jìn)入正文,一個一個來:

Spring Data是什么

我們傳統(tǒng)的開發(fā)中,我們的整個DAO層的代碼上都是相對來說,都是比較復(fù)雜的,在這種情況下,Spring團(tuán)隊(duì)就考慮到一個問題,能不能開發(fā)一個框架,這個框架能夠最大限度的減少DAO層的開發(fā)呢?

Spring Data就是為了簡化DAO層操作的一個框架

傳統(tǒng)的增刪改查在我們的Spring Data中已經(jīng)實(shí)現(xiàn)了,也就是說大部分的DAO層操作部分不用寫了,僅僅只是需要編寫復(fù)雜的業(yè)務(wù)的調(diào)用就可以啦


寫的這部分的代碼,是需要寫接口的聲明就可以啦,不用寫實(shí)現(xiàn),這個實(shí)現(xiàn)是自動實(shí)現(xiàn)的

Spring Data能干什么

主要用途:

  • 傳統(tǒng)的增刪改查
  • 排序
  • 分頁
  • 排序后分頁

即使你需要寫DAO,也只是寫聲明就可以啦,不用寫實(shí)現(xiàn)

Spring Data的第一個HelloWorld程序(JPA、Hibernate、Spring、SpringMVC、Spring Data)

導(dǎo)包


編寫配置文件

  1.  <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.  xmlns:p="http://www.springframework.org/schema/p" 
  5.  xmlns:context="http://www.springframework.org/schema/context"  
  6.  xmlns:tx="http://www.springframework.org/schema/tx" 
  7.  xmlns:aop="http://www.springframework.org/schema/aop" 
  8.  xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
  9.  xsi:schemaLocation=" 
  10.         http://www.springframework.org/schema/beans 
  11.         http://www.springframework.org/schema/beans/spring-beans.xsd 
  12.         http://www.springframework.org/schema/context 
  13.         http://www.springframework.org/schema/context/spring-context.xsd 
  14.         http://www.springframework.org/schema/tx 
  15.         http://www.springframework.org/schema/tx/spring-tx.xsd 
  16.         http://www.springframework.org/schema/aop 
  17.         http://www.springframework.org/schema/aop/spring-aop.xsd 
  18.         http://www.springframework.org/schema/data/jpa  
  19.         http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd"> 
  20.          
  21.         <!--引入Properties文件--> 
  22.         <context:property-placeholder location="classpath:config/db.properties"/> 
  23.          
  24.         <!--配置c3p0的連接池--> 
  25.         <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  26.             <property name="driverClass" value="${driverClass}"></property> 
  27.             <property name="jdbcUrl" value="${url}"></property> 
  28.             <property name="user" value="${user}"></property> 
  29.             <property name="password" value="${password}"></property> 
  30.             <property name="acquireIncrement" value="${acquireIncrement}"></property> 
  31.             <property name="maxPoolSize" value="${maxPoolSize}"></property> 
  32.             <property name="minPoolSize" value="${minPoolSize}"></property> 
  33.             <property name="maxStatements" value="${maxStatements}"></property> 
  34.         </bean> 
  35.          
  36.         <!--配置JPA實(shí)現(xiàn)產(chǎn)品的適配器--> 
  37.         <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
  38.         </bean> 
  39.          
  40.         <!--配置EntityManager對象--> 
  41.          
  42.         <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
  43.            <!--注入數(shù)據(jù)源--> 
  44.            <property name="dataSource" ref="dataSource"></property> 
  45.            <!--掃描entity包的-->  
  46.            <property name="packagesToScan" value="com.qy.helloworld"></property> 
  47.            <!--注入JPA實(shí)現(xiàn)產(chǎn)品的適配器--> 
  48.            <property name="jpaVendorAdapter" ref="jpaVendorAdapter"></property> 
  49.            <!--配置的是Hibernate的其他配置  除了連接數(shù)據(jù)庫4大要素之外的其余配置--> 
  50.            <property name="jpaProperties"
  51.               <props> 
  52.                <!--是否自動創(chuàng)建表 --> 
  53.                <prop key="hibernate.hbm2ddl.auto">update</prop> 
  54.                <!--配置是否展示SQL--> 
  55.                <prop key="hibernate.show_sql">true</prop> 
  56.                <!--是否格式化SQL--> 
  57.                <prop key="hibernate.format_sql">true</prop> 
  58.                <!--連接數(shù)據(jù)庫的方言--> 
  59.                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> 
  60.             </props> 
  61.            </property> 
  62.         </bean> 
  63.          
  64.          
  65.         <!--配置事務(wù)環(huán)境--> 
  66.          
  67.         <bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
  68.            <!--注入dataSource--> 
  69.            <property name="dataSource" ref="dataSource"></property> 
  70.            <!--注入entityManagerFactory對象--> 
  71.            <property name="entityManagerFactory" ref="entityManagerFactory"></property> 
  72.         </bean> 
  73.          
  74.         <!--使用事務(wù)--> 
  75.         <tx:annotation-driven transaction-manager="jpaTransactionManager"/> 
  76.          
  77.         <!--配置AOP的自動代理--> 
  78.         <aop:aspectj-autoproxy></aop:aspectj-autoproxy>  
  79.          
  80.         <!--配置Spring的包掃描--> 
  81.         <context:component-scan base-package="com.qy.helloworld"></context:component-scan> 
  82.          
  83.         <!--Spring data的包的掃描  這里的掃描掃描的是DAO層所在的位置--> 
  84.         <jpa:repositories base-package="com.qy.helloworld" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="jpaTransactionManager"></jpa:repositories> 
  85.  
  86. </beans>         

編寫實(shí)體類和映射

  1. @Entity 
  2. @Table(name="t_user"
  3. public class User { 
  4.  
  5.  @Id 
  6.  @GeneratedValue(strategy=GenerationType.IDENTITY) 
  7.  private int userId; 
  8.   
  9.  private String userName; 
  10.   
  11.  private String password

編寫Repository類

  1. public interface UserRepository extends Repository<User,Integer>{ 
  2.  /** 
  3.   * 這個的意思是通過id找用戶 
  4.   * @Title: getByUserId    
  5.   * @Description: TODO 
  6.   * @param: @param userId 
  7.   * @param: @return       
  8.   * @returnUser       
  9.   * @throws 
  10.   */ 
  11.  public User getByUserId(int userId); 

測試

  1. ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml"); 
  2.   //獲取DAO的對象 
  3.   UserRepository userRepository=applicationContext.getBean(UserRepository.class); 
  4.  User users=userRepository.findByUserId(1); 

通過名字來確定方法

代碼演示:

舉例如下:

  1. public interface UserRepository extends Repository<User,Integer>{ 
  2.  /** 
  3.   * 這個的意思是通過id找用戶 
  4.   * @Title: getByUserId    
  5.   * @Description: TODO 
  6.   * @param: @param userId 
  7.   * @param: @return       
  8.   * @returnUser       
  9.   * @throws 
  10.   */ 
  11.  public User getByUserId(int userId); 
  12.   
  13.  /** 
  14.   * 記住查詢的開頭只能是  get 或者  find 開頭   By:通過什么查詢 
  15.   * @Title: findByUserId    
  16.   * @Description: TODO 
  17.   * @param: @param userId 
  18.   * @param: @return       
  19.   * @returnUser       
  20.   * @throws 
  21.   */ 
  22.  public User findByUserId(int userId); 
  23.   
  24.  /** 
  25.   * 通過用戶名的模糊查詢 
  26.   * @Title: findByUserNameLike    
  27.   * @Description: TODO 
  28.   * @param: @param userName 
  29.   * @param: @return       
  30.   * @return: List<User>       
  31.   * @throws 
  32.   */ 
  33.  public List<User> findByUserNameLike(String userName); 
  34.   
  35.  /** 
  36.   * 通過用戶名和密碼的Like來進(jìn)行查詢 
  37.   * @Title: findByUserNameLikeAndPasswordLike    
  38.   * @Description: TODO 
  39.   * @param: @param userName 
  40.   * @param: @return       
  41.   * @return: List<User>       
  42.   * @throws 
  43.   */ 
  44.  public List<User> findByUserNameLikeAndPasswordLike(String userName,String password); 
  45.  /** 
  46.   * 用戶名和密碼like 然后id小于一個范圍 
  47.   * @Title: findByUserNameLikeAndPasswordLikeAndUserIdLessThan    
  48.   * @Description: TODO 
  49.   * @param: @param userName 
  50.   * @param: @param password 
  51.   * @param: @param userId 
  52.   * @param: @return       
  53.   * @return: List<User>       
  54.   * @throws 
  55.   */ 
  56.  public List<User> findByUserNameLikeAndPasswordLikeAndUserIdLessThan(String userName,String password,int userId); 

注意:一般情況下不會通過名字直接來寫相應(yīng)的方法,因?yàn)槿绻麠l件過多那么這個時候我們就存在名字特別長的問題

通過注解的模式來實(shí)現(xiàn)查詢

代碼演示:

舉例如下:

  1. /** 
  2.     * 查詢所有  沒有條件直接查詢 
  3.     * @Title: findUserAll    
  4.     * @Description: TODO 
  5.     * @param: @return       
  6.     * @return: List<User>       
  7.     * @throws 
  8.     */ 
  9. @Query("from User"
  10. public List<User> findUserAll(); 
  11.  
  12. /** 
  13.  * 通過id來查找數(shù)據(jù)     參數(shù)直接拼接到后面 
  14.  * @Title: findUserById    
  15.  * @Description: TODO 
  16.  * @param: @param userId 
  17.  * @param: @return       
  18.  * @return: List<User>       
  19.  * @throws 
  20.  */ 
  21. @Query("from User u  where u.userId<3"
  22. public List<User> findUserById(); 
  23. /** 
  24.  * 通過id查詢存在占位符的情況 
  25.  * @Title: findUserById1    
  26.  * @Description: TODO 
  27.  * @param: @param userId 
  28.  * @param: @return       
  29.  * @return: List<User>       
  30.  * @throws 
  31.  */ 
  32. @Query("from User u  where u.userId<?"
  33. public List<User> findUserById1(int userId); 
  34.  
  35. /** 
  36.  * 多條件的查詢  可以指定當(dāng)前的參數(shù)映射的這個位置 
  37.  * @Title: getUserByNameAndId    
  38.  * @Description: TODO 
  39.  * @param: @param userName 
  40.  * @param: @param userId 
  41.  * @param: @return       
  42.  * @returnUser       
  43.  * @throws 
  44.  */ 
  45. @Query("from User u where u.userId=?2 and u.userName=?1"
  46. public User getUserByNameAndId(String userName,int userId); 
  47.  
  48. /** 
  49.  * 模糊查詢的時候動態(tài)拼接上  %的問題 
  50.  * @Title: findUserByLike1    
  51.  * @Description: TODO 
  52.  * @param: @param userName 
  53.  * @param: @return       
  54.  * @return: List<User>       
  55.  * @throws 
  56.  */ 
  57. @Query("from User u where u.userName like concat ('%',?,'%')"
  58. public List<User> findUserByLike1(String userName); 

寫本地的SQL 查詢

代碼演示:

舉例如下:

  1. /** 
  2.  * 通過 
  3.  * @Title: findUserAll11    
  4.  * @Description: TODO 
  5.  * @param: @return       
  6.  * @return: List<User>       
  7.  * @throws 
  8.  */ 
  9. @Query(nativeQuery=true,value="select * from t_user"
  10. public List<User> findUserAll11(); 

增刪改的玩法

代碼演示:

添加業(yè)務(wù)邏輯 增加事務(wù)環(huán)境:

  1.  @Service 
  2. @Transactional                  //提供一個事務(wù)的環(huán)境 
  3. public class UserService { 
  4.   
  5.  @Autowired 
  6.  private UserRepository userRepository=null
  7.   
  8.  /** 
  9.   * 數(shù)據(jù)的更新 
  10.   * @Title: update    
  11.   * @Description: TODO 
  12.   * @param: @param userName 
  13.   * @param: @param password 
  14.   * @param: @param userId       
  15.   * @return: void       
  16.   * @throws 
  17.   */ 
  18.  public void update(String userName,String password,int userId){ 
  19.   userRepository.update(userName, password, userId); 
  20.  } 
  21.   
  22.   
  23.  public void delete(int userId){ 
  24.   userRepository.delete(userId); 
  25.  } 
  26.   
  27.  public void insert(String userName,String password){ 
  28.   userRepository.insert(userName, password); 
  29.  } 
  30.  

編寫repository的對象:

  1.  public interface UserRepository extends Repository<User,Integer>{ 
  2.  /** 
  3.   * 實(shí)現(xiàn)增刪改的方法 
  4.   * @Title: add    
  5.   * @Description: TODO 
  6.   * @param: @param userName 
  7.   * @param: @param password       
  8.   * @return: void       
  9.   * @throws 
  10.   */ 
  11.  @Modifying    //這個注解的作用表示的是更新數(shù)據(jù) 
  12.  @Query("update User u set u.userName=?,u.password=? where u.userId=?"
  13.  public void update(String userName,String password,int userId); 
  14.   
  15.  /** 
  16.   * 更新數(shù)據(jù) 
  17.   * @Title: delete    
  18.   * @Description: TODO 
  19.   * @param: @param userId       
  20.   * @return: void       
  21.   * @throws 
  22.   */ 
  23.  @Modifying    //這個注解的作用表示的是更新數(shù)據(jù) 
  24.  @Query("delete User u where u.userId=?"
  25.  public void delete(int userId); 
  26.  /** 
  27.   * 添加數(shù)據(jù) 
  28.   * @Title: insert    
  29.   * @Description: TODO 
  30.   * @param: @param userName 
  31.   * @param: @param password       
  32.   * @return: void       
  33.   * @throws 
  34.   */ 
  35.  @Modifying    //這個注解的作用表示的是更新數(shù)據(jù) 
  36.  @Query(nativeQuery=true,value="insert into t_user(userName,password) values(?,?)"
  37.  public void insert(String userName,String password); 
  38.   

測試:

  1. @Test 
  2. public void testHelloWorld() throws Exception { 
  3.   
  4.  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml"); 
  5.  //獲取DAO的對象 
  6.  UserService userService=applicationContext.getBean(UserService.class); 
  7.  
  8.  userService.insert("小羽","做程序的"); 

使用框架中提供的增刪改查的方法

代碼演示:

提供的是Repository:

  1. public interface UserRepository extends CrudRepository<User,Integer>{ 

分頁和排序

代碼演示:

提供的Repository:

  1. public interface UserRepository extends PagingAndSortingRepository<User,Integer>{ 

測試:

  1. public class Test001 { 
  2.  
  3.  
  4. @Test 
  5. public void testPaging() throws Exception { 
  6.  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml"); 
  7.  //獲取DAO的對象 
  8.  UserRepository userRepository=applicationContext.getBean(UserRepository.class); 
  9. /** 
  10.  * 第一個參數(shù):當(dāng)前的頁的頁數(shù)是多少  頁數(shù)是從0開始的   第二頁:2-1 
  11.  * 第二個參數(shù):表示的是每一頁條目數(shù) 
  12.  */ 
  13.  Page<User> pages=userRepository.findAll(new PageRequest(2-1,2)); 
  14.  
  15.  System.out.println("查詢到的數(shù)據(jù):"+pages.getContent()); 
  16.  System.out.println("數(shù)據(jù)的條目數(shù):"+pages.getSize()); 
  17.  System.out.println("頁數(shù):"+pages.getNumber()); 
  18.  System.out.println("數(shù)據(jù)條目的總數(shù):"+pages.getTotalElements()); 
  19.  System.out.println("一共的頁數(shù):"+pages.getTotalPages()); 
  20.  System.out.println("排序的規(guī)則:"+pages.getSort()); 
  21.  
  22.  
  23. /** 
  24.  * 排序 
  25.  * @Title: testSort    
  26.  * @Description: TODO 
  27.  * @param: @throws Exception       
  28.  * @return: void       
  29.  * @throws 
  30.  */ 
  31. @Test 
  32. public void testSort() throws Exception { 
  33.  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml"); 
  34.  //獲取DAO的對象 
  35.  UserRepository userRepository=applicationContext.getBean(UserRepository.class); 
  36.  /** 
  37.   * 排序 
  38.   * 第一個參數(shù):升序或者降序  Direction.ASC/DESC 
  39.   * 第二個參數(shù): 排序的這個列 
  40.   */ 
  41.  List<User> users=(List<User>) userRepository.findAll(new Sort(Direction.DESC,"userId")); 
  42.   
  43.  System.out.println(users); 
  44.  
  45. /** 
  46.  * 排序后分頁 
  47.  * @Title: testSortAndPaging    
  48.  * @Description: TODO 
  49.  * @param: @throws Exception       
  50.  * @return: void       
  51.  * @throws 
  52.  */ 
  53. @Test 
  54. public void testSortAndPaging() throws Exception { 
  55.  ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml"); 
  56.  //獲取DAO的對象 
  57.  UserRepository userRepository=applicationContext.getBean(UserRepository.class); 
  58.   
  59.  Page<User> pages=userRepository.findAll(new PageRequest(2-1,2,new Sort(Direction.DESC,"userId"))); 
  60.   
  61.  System.out.println(pages.getContent()); 

JpaRepository的使用

代碼演示:

提供的repository:

  1. public interface UserRepository extends JpaRepository<User,Integer>{ 

測試:

  1.  public class Test001 { 
  2.  @Test 
  3.  public void testPaging() throws Exception { 
  4.   ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("config/bean-base.xml"); 
  5.   //獲取DAO的對象 
  6.   UserRepository userRepository=applicationContext.getBean(UserRepository.class); 
  7.      
  8. //  long count=userRepository.count(); 
  9.    
  10. //  User user=userRepository.findOne(15); 
  11. //  user.setUserName("小羽"); 
  12.    
  13.   //保存或者更新數(shù)據(jù) 
  14. //  userRepository.saveAndFlush(user); 
  15.    
  16.   
  17.   List<User> users=userRepository.findAll(); 
  18.    
  19.   //批處理 
  20.   userRepository.deleteInBatch(users); 
  21.     
  22.   //System.out.println("統(tǒng)計:"+count); 
  23.  } 

結(jié)語

Spring Data是我們開發(fā)中離不開的經(jīng)常用到的技術(shù),其涉及的技術(shù)和知識面其實(shí)遠(yuǎn)不止上面列出的這些。

后續(xù)淺羽會繼續(xù)更新關(guān)于Spring Data的開發(fā)知識,只希望能對大家有所幫助,謝謝大家的支持!

 

責(zé)任編輯:姜華 來源: 淺羽的IT小屋
相關(guān)推薦

2021-02-26 11:54:38

MyBatis 插件接口

2024-04-02 08:58:13

2024-03-05 18:27:43

2023-03-27 08:28:57

spring代碼,starter

2021-11-24 16:02:57

鴻蒙HarmonyOS應(yīng)用

2024-03-18 18:07:38

VSCode插件文件

2009-06-02 15:38:36

eclipse streclipse開發(fā)steclipse str

2022-06-30 08:13:44

PythonWeb編程語言

2019-05-05 11:47:09

TypeScript開發(fā)Node.js

2021-07-14 09:00:00

JavaFX開發(fā)應(yīng)用

2011-01-10 14:41:26

2011-05-03 15:59:00

黑盒打印機(jī)

2011-05-27 08:41:26

JavascriptFirefox

2022-02-14 09:11:17

視頻下載器抖音

2015-04-02 11:22:29

2025-02-19 08:00:00

SpringBootOllamaDeepSeek

2021-06-29 12:27:19

Spring BootCAS 登錄

2022-01-08 20:04:20

攔截系統(tǒng)調(diào)用

2022-03-14 14:47:21

HarmonyOS操作系統(tǒng)鴻蒙

2023-04-26 12:46:43

DockerSpringKubernetes
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號