一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Spring Data開發手冊 手把手教你簡化持久層開發工作

Spring Data開發手冊 手把手教你簡化持久層開發工作

2020-11-26 23:07淺羽的IT小屋淺羽Eric Java教程

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

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

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

Spring Data開發手冊 手把手教你簡化持久層開發工作

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

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

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

是不是很清晰呢,現在開始進入正文,一個一個來:

Spring Data是什么

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

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

傳統的增刪改查在我們的Spring Data中已經實現了,也就是說大部分的DAO層操作部分不用寫了,僅僅只是需要編寫復雜的業務的調用就可以啦

Spring Data開發手冊 手把手教你簡化持久層開發工作

寫的這部分的代碼,是需要寫接口的聲明就可以啦,不用寫實現,這個實現是自動實現的

Spring Data能干什么

主要用途:

  • 傳統的增刪改查
  • 排序
  • 分頁
  • 排序后分頁

即使你需要寫DAO,也只是寫聲明就可以啦,不用寫實現

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

導包

Spring Data開發手冊 手把手教你簡化持久層開發工作

編寫配置文件

  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實現產品的適配器--> 
  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.            <!--注入數據源--> 
  44.            <property name="dataSource" ref="dataSource"></property> 
  45.            <!--掃描entity包的-->  
  46.            <property name="packagesToScan" value="com.qy.helloworld"></property> 
  47.            <!--注入JPA實現產品的適配器--> 
  48.            <property name="jpaVendorAdapter" ref="jpaVendorAdapter"></property> 
  49.            <!--配置的是Hibernate的其他配置  除了連接數據庫4大要素之外的其余配置--> 
  50.            <property name="jpaProperties"
  51.               <props> 
  52.                <!--是否自動創建表 --> 
  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.                <!--連接數據庫的方言--> 
  59.                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> 
  60.             </props> 
  61.            </property> 
  62.         </bean> 
  63.          
  64.          
  65.         <!--配置事務環境--> 
  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.         <!--使用事務--> 
  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>         

編寫實體類和映射

 

  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來進行查詢 
  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); 

注意:一般情況下不會通過名字直接來寫相應的方法,因為如果條件過多那么這個時候我們就存在名字特別長的問題

通過注解的模式來實現查詢

代碼演示:

舉例如下:

  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來查找數據     參數直接拼接到后面 
  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.  * 多條件的查詢  可以指定當前的參數映射的這個位置 
  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.  * 模糊查詢的時候動態拼接上  %的問題 
  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(); 

增刪改的玩法

代碼演示:

添加業務邏輯 增加事務環境:

  1.  @Service 
  2. @Transactional                  //提供一個事務的環境 
  3. public class UserService { 
  4.   
  5.  @Autowired 
  6.  private UserRepository userRepository=null
  7.   
  8.  /** 
  9.   * 數據的更新 
  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.   * 實現增刪改的方法 
  4.   * @Title: add    
  5.   * @Description: TODO 
  6.   * @param: @param userName 
  7.   * @param: @param password       
  8.   * @return: void       
  9.   * @throws 
  10.   */ 
  11.  @Modifying    //這個注解的作用表示的是更新數據 
  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.   * 更新數據 
  17.   * @Title: delete    
  18.   * @Description: TODO 
  19.   * @param: @param userId       
  20.   * @return: void       
  21.   * @throws 
  22.   */ 
  23.  @Modifying    //這個注解的作用表示的是更新數據 
  24.  @Query("delete User u where u.userId=?"
  25.  public void delete(int userId); 
  26.  /** 
  27.   * 添加數據 
  28.   * @Title: insert    
  29.   * @Description: TODO 
  30.   * @param: @param userName 
  31.   * @param: @param password       
  32.   * @return: void       
  33.   * @throws 
  34.   */ 
  35.  @Modifying    //這個注解的作用表示的是更新數據 
  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.  * 第一個參數:當前的頁的頁數是多少  頁數是從0開始的   第二頁:2-1 
  11.  * 第二個參數:表示的是每一頁條目數 
  12.  */ 
  13.  Page<User> pages=userRepository.findAll(new PageRequest(2-1,2)); 
  14.  
  15.  System.out.println("查詢到的數據:"+pages.getContent()); 
  16.  System.out.println("數據的條目數:"+pages.getSize()); 
  17.  System.out.println("頁數:"+pages.getNumber()); 
  18.  System.out.println("數據條目的總數:"+pages.getTotalElements()); 
  19.  System.out.println("一共的頁數:"+pages.getTotalPages()); 
  20.  System.out.println("排序的規則:"+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.   * 第一個參數:升序或者降序  Direction.ASC/DESC 
  39.   * 第二個參數: 排序的這個列 
  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.   //保存或者更新數據 
  14. //  userRepository.saveAndFlush(user); 
  15.    
  16.   
  17.   List<User> users=userRepository.findAll(); 
  18.    
  19.   //批處理 
  20.   userRepository.deleteInBatch(users); 
  21.     
  22.   //System.out.println("統計:"+count); 
  23.  } 

結語

Spring Data是我們開發中離不開的經常用到的技術,其涉及的技術和知識面其實遠不止上面列出的這些。

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 桥本有菜ssni-677在线观看 | 成人操| 日韩欧美不卡视频 | 91午夜剧场| 操mm| 免费国产好深啊好涨好硬视频 | 日韩色在线观看 | 国产高清dvd| 亚州性夜夜射在线观看 | 四虎国产欧美成人影院 | 韩国一区二区三区 | 日本三级s级在线播放 | 日韩中文字幕视频在线观看 | 不卡视频一区二区 | 秋霞一级毛片 | 九九热在线视频观看这里只有精品 | 公翁的舌尖研磨她的花蒂小说 | 男人操女人动图 | 农夫成人网 | a天堂视频 | 国产精品久久亚洲一区二区 | 范冰冰性xxxxhd| 欧美日韩亚洲综合在线一区二区 | 强插美女| bestialitysex杂交| 欧美精品国产一区二区 | 日本网 | 亚洲日韩男人网在线 | 久久精品在现线观看免费15 | 99精品在线 | 成人国产精品视频 | 2019亚洲男人天堂 | 99久久精品国产免看国产一区 | 四虎最新网址在线观看 | 亚洲成色WWW久久网站夜月 | 国产精品亚洲精品观看不卡 | 男男双性生子产乳高辣h | 午夜在线观看免费观看 视频 | 亚洲a图| 免费av在线视频 | videojapan日本孕交孕 |