Spring Data开发手册 手把手教你简化持久层开发工作

2025-05-29 0 21

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. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="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. <!–引入Properties文件–>
  21. <context:property-placeholderlocation="classpath:config/db.properties"/>
  22. <!–配置c3p0的连接池–>
  23. <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">
  24. <propertyname="driverClass"value="${driverClass}"></property>
  25. <propertyname="jdbcUrl"value="${url}"></property>
  26. <propertyname="user"value="${user}"></property>
  27. <propertyname="password"value="${password}"></property>
  28. <propertyname="acquireIncrement"value="${acquireIncrement}"></property>
  29. <propertyname="maxPoolSize"value="${maxPoolSize}"></property>
  30. <propertyname="minPoolSize"value="${minPoolSize}"></property>
  31. <propertyname="maxStatements"value="${maxStatements}"></property>
  32. </bean>
  33. <!–配置JPA实现产品的适配器–>
  34. <beanid="jpaVendorAdapter"class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
  35. </bean>
  36. <!–配置EntityManager对象–>
  37. <beanid="entityManagerFactory"class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  38. <!–注入数据源–>
  39. <propertyname="dataSource"ref="dataSource"></property>
  40. <!–扫描entity包的–>
  41. <propertyname="packagesToScan"value="com.qy.helloworld"></property>
  42. <!–注入JPA实现产品的适配器–>
  43. <propertyname="jpaVendorAdapter"ref="jpaVendorAdapter"></property>
  44. <!–配置的是Hibernate的其他配置除了连接数据库4大要素之外的其余配置–>
  45. <propertyname="jpaProperties">
  46. <props>
  47. <!–是否自动创建表–>
  48. <propkey="hibernate.hbm2ddl.auto">update</prop>
  49. <!–配置是否展示SQL–>
  50. <propkey="hibernate.show_sql">true</prop>
  51. <!–是否格式化SQL–>
  52. <propkey="hibernate.format_sql">true</prop>
  53. <!–连接数据库的方言–>
  54. <propkey="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
  55. </props>
  56. </property>
  57. </bean>
  58. <!–配置事务环境–>
  59. <beanid="jpaTransactionManager"class="org.springframework.orm.jpa.JpaTransactionManager">
  60. <!–注入dataSource–>
  61. <propertyname="dataSource"ref="dataSource"></property>
  62. <!–注入entityManagerFactory对象–>
  63. <propertyname="entityManagerFactory"ref="entityManagerFactory"></property>
  64. </bean>
  65. <!–使用事务–>
  66. <tx:annotation-driventransaction-manager="jpaTransactionManager"/>
  67. <!–配置AOP的自动代理–>
  68. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  69. <!–配置Spring的包扫描–>
  70. <context:component-scanbase-package="com.qy.helloworld"></context:component-scan>
  71. <!–Springdata的包的扫描这里的扫描扫描的是DAO层所在的位置–>
  72. <jpa:repositoriesbase-package="com.qy.helloworld"entity-manager-factory-ref="entityManagerFactory"transaction-manager-ref="jpaTransactionManager"></jpa:repositories>
  73. </beans>

编写实体类和映射

  1. @Entity
  2. @Table(name="t_user")
  3. publicclassUser{
  4. @Id
  5. @GeneratedValue(strategy=GenerationType.IDENTITY)
  6. privateintuserId;
  7. privateStringuserName;
  8. privateStringpassword;
  9. }

编写Repository类

  1. publicinterfaceUserRepositoryextendsRepository<User,Integer>{
  2. /**
  3. *这个的意思是通过id找用户
  4. *@Title:getByUserId
  5. *@Description:TODO
  6. *@param:@paramuserId
  7. *@param:@return
  8. *@return:User
  9. *@throws
  10. */
  11. publicUsergetByUserId(intuserId);
  12. }

测试

  1. ClassPathXmlApplicationContextapplicationContext=newClassPathXmlApplicationContext("config/bean-base.xml");
  2. //获取DAO的对象
  3. UserRepositoryuserRepository=applicationContext.getBean(UserRepository.class);
  4. Userusers=userRepository.findByUserId(1);
  5. }

通过名字来确定方法

代码演示:

举例如下:

  1. publicinterfaceUserRepositoryextendsRepository<User,Integer>{
  2. /**
  3. *这个的意思是通过id找用户
  4. *@Title:getByUserId
  5. *@Description:TODO
  6. *@param:@paramuserId
  7. *@param:@return
  8. *@return:User
  9. *@throws
  10. */
  11. publicUsergetByUserId(intuserId);
  12. /**
  13. *记住查询的开头只能是get或者find开头By:通过什么查询
  14. *@Title:findByUserId
  15. *@Description:TODO
  16. *@param:@paramuserId
  17. *@param:@return
  18. *@return:User
  19. *@throws
  20. */
  21. publicUserfindByUserId(intuserId);
  22. /**
  23. *通过用户名的模糊查询
  24. *@Title:findByUserNameLike
  25. *@Description:TODO
  26. *@param:@paramuserName
  27. *@param:@return
  28. *@return:List<User>
  29. *@throws
  30. */
  31. publicList<User>findByUserNameLike(StringuserName);
  32. /**
  33. *通过用户名和密码的Like来进行查询
  34. *@Title:findByUserNameLikeAndPasswordLike
  35. *@Description:TODO
  36. *@param:@paramuserName
  37. *@param:@return
  38. *@return:List<User>
  39. *@throws
  40. */
  41. publicList<User>findByUserNameLikeAndPasswordLike(StringuserName,Stringpassword);
  42. /**
  43. *用户名和密码like然后id小于一个范围
  44. *@Title:findByUserNameLikeAndPasswordLikeAndUserIdLessThan
  45. *@Description:TODO
  46. *@param:@paramuserName
  47. *@param:@parampassword
  48. *@param:@paramuserId
  49. *@param:@return
  50. *@return:List<User>
  51. *@throws
  52. */
  53. publicList<User>findByUserNameLikeAndPasswordLikeAndUserIdLessThan(StringuserName,Stringpassword,intuserId);
  54. }

注意:一般情况下不会通过名字直接来写相应的方法,因为如果条件过多那么这个时候我们就存在名字特别长的问题

通过注解的模式来实现查询

代码演示:

举例如下:

  1. /**
  2. *查询所有没有条件直接查询
  3. *@Title:findUserAll
  4. *@Description:TODO
  5. *@param:@return
  6. *@return:List<User>
  7. *@throws
  8. */
  9. @Query("fromUser")
  10. publicList<User>findUserAll();
  11. /**
  12. *通过id来查找数据参数直接拼接到后面
  13. *@Title:findUserById
  14. *@Description:TODO
  15. *@param:@paramuserId
  16. *@param:@return
  17. *@return:List<User>
  18. *@throws
  19. */
  20. @Query("fromUseruwhereu.userId<3")
  21. publicList<User>findUserById();
  22. /**
  23. *通过id查询存在占位符的情况
  24. *@Title:findUserById1
  25. *@Description:TODO
  26. *@param:@paramuserId
  27. *@param:@return
  28. *@return:List<User>
  29. *@throws
  30. */
  31. @Query("fromUseruwhereu.userId<?")
  32. publicList<User>findUserById1(intuserId);
  33. /**
  34. *多条件的查询可以指定当前的参数映射的这个位置
  35. *@Title:getUserByNameAndId
  36. *@Description:TODO
  37. *@param:@paramuserName
  38. *@param:@paramuserId
  39. *@param:@return
  40. *@return:User
  41. *@throws
  42. */
  43. @Query("fromUseruwhereu.userId=?2andu.userName=?1")
  44. publicUsergetUserByNameAndId(StringuserName,intuserId);
  45. /**
  46. *模糊查询的时候动态拼接上%的问题
  47. *@Title:findUserByLike1
  48. *@Description:TODO
  49. *@param:@paramuserName
  50. *@param:@return
  51. *@return:List<User>
  52. *@throws
  53. */
  54. @Query("fromUseruwhereu.userNamelikeconcat('%',?,'%')")
  55. publicList<User>findUserByLike1(StringuserName);

写本地的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*fromt_user")
  10. publicList<User>findUserAll11();

增删改的玩法

代码演示:

添加业务逻辑 增加事务环境:

  1. @Service
  2. @Transactional//提供一个事务的环境
  3. publicclassUserService{
  4. @Autowired
  5. privateUserRepositoryuserRepository=null;
  6. /**
  7. *数据的更新
  8. *@Title:update
  9. *@Description:TODO
  10. *@param:@paramuserName
  11. *@param:@parampassword
  12. *@param:@paramuserId
  13. *@return:void
  14. *@throws
  15. */
  16. publicvoidupdate(StringuserName,Stringpassword,intuserId){
  17. userRepository.update(userName,password,userId);
  18. }
  19. publicvoiddelete(intuserId){
  20. userRepository.delete(userId);
  21. }
  22. publicvoidinsert(StringuserName,Stringpassword){
  23. userRepository.insert(userName,password);
  24. }
  25. }

编写repository的对象:

  1. publicinterfaceUserRepositoryextendsRepository<User,Integer>{
  2. /**
  3. *实现增删改的方法
  4. *@Title:add
  5. *@Description:TODO
  6. *@param:@paramuserName
  7. *@param:@parampassword
  8. *@return:void
  9. *@throws
  10. */
  11. @Modifying//这个注解的作用表示的是更新数据
  12. @Query("updateUserusetu.userName=?,u.password=?whereu.userId=?")
  13. publicvoidupdate(StringuserName,Stringpassword,intuserId);
  14. /**
  15. *更新数据
  16. *@Title:delete
  17. *@Description:TODO
  18. *@param:@paramuserId
  19. *@return:void
  20. *@throws
  21. */
  22. @Modifying//这个注解的作用表示的是更新数据
  23. @Query("deleteUseruwhereu.userId=?")
  24. publicvoiddelete(intuserId);
  25. /**
  26. *添加数据
  27. *@Title:insert
  28. *@Description:TODO
  29. *@param:@paramuserName
  30. *@param:@parampassword
  31. *@return:void
  32. *@throws
  33. */
  34. @Modifying//这个注解的作用表示的是更新数据
  35. @Query(nativeQuery=true,value="insertintot_user(userName,password)values(?,?)")
  36. publicvoidinsert(StringuserName,Stringpassword);
  37. }

测试:

  1. @Test
  2. publicvoidtestHelloWorld()throwsException{
  3. ClassPathXmlApplicationContextapplicationContext=newClassPathXmlApplicationContext("config/bean-base.xml");
  4. //获取DAO的对象
  5. UserServiceuserService=applicationContext.getBean(UserService.class);
  6. userService.insert("小羽","做程序的");

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

代码演示:

提供的是Repository:

  1. publicinterfaceUserRepositoryextendsCrudRepository<User,Integer>{

分页和排序

代码演示:

提供的Repository:

  1. publicinterfaceUserRepositoryextendsPagingAndSortingRepository<User,Integer>{

测试:

  1. publicclassTest001{
  2. @Test
  3. publicvoidtestPaging()throwsException{
  4. ClassPathXmlApplicationContextapplicationContext=newClassPathXmlApplicationContext("config/bean-base.xml");
  5. //获取DAO的对象
  6. UserRepositoryuserRepository=applicationContext.getBean(UserRepository.class);
  7. /**
  8. *第一个参数:当前的页的页数是多少页数是从0开始的第二页:2-1
  9. *第二个参数:表示的是每一页条目数
  10. */
  11. Page<User>pages=userRepository.findAll(newPageRequest(2-1,2));
  12. System.out.println("查询到的数据:"+pages.getContent());
  13. System.out.println("数据的条目数:"+pages.getSize());
  14. System.out.println("页数:"+pages.getNumber());
  15. System.out.println("数据条目的总数:"+pages.getTotalElements());
  16. System.out.println("一共的页数:"+pages.getTotalPages());
  17. System.out.println("排序的规则:"+pages.getSort());
  18. }
  19. /**
  20. *排序
  21. *@Title:testSort
  22. *@Description:TODO
  23. *@param:@throwsException
  24. *@return:void
  25. *@throws
  26. */
  27. @Test
  28. publicvoidtestSort()throwsException{
  29. ClassPathXmlApplicationContextapplicationContext=newClassPathXmlApplicationContext("config/bean-base.xml");
  30. //获取DAO的对象
  31. UserRepositoryuserRepository=applicationContext.getBean(UserRepository.class);
  32. /**
  33. *排序
  34. *第一个参数:升序或者降序Direction.ASC/DESC
  35. *第二个参数:排序的这个列
  36. */
  37. List<User>users=(List<User>)userRepository.findAll(newSort(Direction.DESC,"userId"));
  38. System.out.println(users);
  39. }
  40. /**
  41. *排序后分页
  42. *@Title:testSortAndPaging
  43. *@Description:TODO
  44. *@param:@throwsException
  45. *@return:void
  46. *@throws
  47. */
  48. @Test
  49. publicvoidtestSortAndPaging()throwsException{
  50. ClassPathXmlApplicationContextapplicationContext=newClassPathXmlApplicationContext("config/bean-base.xml");
  51. //获取DAO的对象
  52. UserRepositoryuserRepository=applicationContext.getBean(UserRepository.class);
  53. Page<User>pages=userRepository.findAll(newPageRequest(2-1,2,newSort(Direction.DESC,"userId")));
  54. System.out.println(pages.getContent());
  55. }

JpaRepository的使用

代码演示:

提供的repository:

  1. publicinterfaceUserRepositoryextendsJpaRepository<User,Integer>{

测试:

  1. publicclassTest001{
  2. @Test
  3. publicvoidtestPaging()throwsException{
  4. ClassPathXmlApplicationContextapplicationContext=newClassPathXmlApplicationContext("config/bean-base.xml");
  5. //获取DAO的对象
  6. UserRepositoryuserRepository=applicationContext.getBean(UserRepository.class);
  7. //longcount=userRepository.count();
  8. //Useruser=userRepository.findOne(15);
  9. //user.setUserName("小羽");
  10. //保存或者更新数据
  11. //userRepository.saveAndFlush(user);
  12. List<User>users=userRepository.findAll();
  13. //批处理
  14. userRepository.deleteInBatch(users);
  15. //System.out.println("统计:"+count);
  16. }
  17. }

结语

Spring Data是我们开发中离不开的经常用到的技术,其涉及的技术和知识面其实远不止上面列出的这些。

后续浅羽会继续更新关于Spring Data的开发知识,只希望能对大家有所帮助,谢谢大家的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring Data开发手册 手把手教你简化持久层开发工作 https://www.kuaiidc.com/115591.html

相关文章

猜你喜欢
发表评论
暂无评论