使用Spring Data JPA操作Mysql

举报
清雨小竹 发表于 2022/09/25 02:04:29 2022/09/25
【摘要】 参考:Open-source development – IBM Developer – IBM Developer 1.添加依赖: dependencies { compile('io.springfox:springfox-swagger2:2.2.2') compile('io.springfox:springfo...

参考:Open-source development – IBM Developer – IBM Developer

1.添加依赖:


  
  1. dependencies {
  2. compile('io.springfox:springfox-swagger2:2.2.2')
  3. compile('io.springfox:springfox-swagger-ui:2.2.2')
  4. compile('org.springframework.boot:spring-boot-starter-data-jpa')
  5. compile('org.springframework.boot:spring-boot-starter-jdbc')
  6. compile('org.springframework.boot:spring-boot-starter-web')
  7. runtime('mysql:mysql-connector-java')
  8. providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
  9. testCompile('org.springframework.boot:spring-boot-starter-test')
  10. }

2. application.properties文件添加链接串


  
  1. spring.datasource.url=jdbc:mysql://localhost/yfeid  
  2. spring.datasource.username=root  
  3. spring.datasource.password=root  
  4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver  
  5.   
  6. #update database by model  
  7. spring.jpa.show-sql= true   
  8. spring.jpa.properties.hibernate.hbm2ddl.auto=update  
  9. spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect  
  10. spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

3.添加实体类:User


  
  1. package com.yunfeng.TestMySQL.Model;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9. import com.fasterxml.jackson.annotation.JsonFormat;
  10. import javax.persistence.*;
  11. @Entity
  12. @Table(name = "user")
  13. public class User implements Serializable {
  14. /**
  15. * @Fields serialVersionUID : TODO
  16. */
  17. private static final long serialVersionUID = -6550777752269466791L;
  18. @Id
  19. @GeneratedValue(strategy = GenerationType.IDENTITY)
  20. private int id;
  21. private String name;
  22. private String password;
  23. private String address;
  24. @Column(name="loginName")
  25.     private String loginName;
  26. @Temporal(TemporalType.TIMESTAMP)
  27. private Date createTime;
  28. public String getName() {
  29. return name;
  30. }
  31. public void setName(String name) {
  32. this.name = name;
  33. }
  34. public String getPassword() {
  35. return password;
  36. }
  37. public void setPassword(String password) {
  38. this.password = password;
  39. }
  40. public String getAddress() {
  41. return address;
  42. }
  43. public void setAddress(String address) {
  44. this.address = address;
  45. }
  46. public String getLoginName() {
  47. return loginName;
  48. }
  49. public void setLoginName(String loginName) {
  50. this.loginName = loginName;
  51. }
  52. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  53. public Date getCreateTime() {
  54. return createTime;
  55. }
  56. public void setCreateTime(Date createTime) {
  57. this.createTime = createTime;
  58. }
  59. }

4.建立仓库类:


  
  1. package com.yunfeng.TestMySQL.Repository;
  2. import java.util.List;
  3. import org.springframework.data.domain.Page;
  4. import org.springframework.data.domain.Pageable;
  5. import org.springframework.data.jpa.repository.JpaRepository;
  6. import org.springframework.data.jpa.repository.Query;
  7. import org.springframework.data.repository.query.Param;
  8. import com.yunfeng.TestMySQL.Model.User;
  9. public interface UserRepository extends JpaRepository<User, Integer> {
  10. List<User> findByNameOrAddress(String name, String address);
  11. @Query("select a from User a where a.address = ?1")
  12. public User findAddress(String address);
  13. @Query("from User a where a.id = :id")
  14. public User findByUserId(@Param("id")int userId);
  15. @Query("from User a where a.id > :userId")
  16. public Page<User> findByUserIdGreaterThan(@Param("userId")int userId,Pageable pageable);
  17. }

在查询时,通常需要同时根据多个属性进行查询,且查询的条件也格式各样(大于某个值、在某个范围等等),Spring Data JPA 为此提供了一些表达条件查询的关键字,大致如下:

  • And --- 等价于 SQL 中的 and 关键字,比如 findByUsernameAndPassword(String user, Striang pwd);
  • Or --- 等价于 SQL 中的 or 关键字,比如 findByUsernameOrAddress(String user, String addr);
  • Between --- 等价于 SQL 中的 between 关键字,比如 findBySalaryBetween(int max, int min);
  • LessThan --- 等价于 SQL 中的 "<",比如 findBySalaryLessThan(int max);
  • GreaterThan --- 等价于 SQL 中的">",比如 findBySalaryGreaterThan(int min);
  • IsNull --- 等价于 SQL 中的 "is null",比如 findByUsernameIsNull();
  • IsNotNull --- 等价于 SQL 中的 "is not null",比如 findByUsernameIsNotNull();
  • NotNull --- 与 IsNotNull 等价;
  • Like --- 等价于 SQL 中的 "like",比如 findByUsernameLike(String user);
  • NotLike --- 等价于 SQL 中的 "not like",比如 findByUsernameNotLike(String user);
  • OrderBy --- 等价于 SQL 中的 "order by",比如 findByUsernameOrderBySalaryAsc(String user);
  • Not --- 等价于 SQL 中的 "! =",比如 findByUsernameNot(String user);
  • In --- 等价于 SQL 中的 "in",比如 findByUsernameIn(Collection<String> userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;
  • NotIn --- 等价于 SQL 中的 "not in",比如 findByUsernameNotIn(Collection<String> userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;

关于Spring Data JPA的动态关联查询,参看:【一目了然】Spring Data JPA使用Specification动态构建多表查询、复杂查询及排序示例 - 简书

5.使用:


  
  1. package com.yunfeng.TestMySQL;
  2. import Request.*;
  3. import Response.*;
  4. import java.util.List;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.domain.Page;
  7. import org.springframework.data.domain.PageRequest;
  8. import org.springframework.data.domain.Pageable;
  9. import org.springframework.data.domain.Sort;
  10. import org.springframework.web.bind.annotation.RequestBody;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import io.swagger.annotations.ApiOperation;
  14. @RestController
  15. public class TestController {
  16. @ApiOperation(value = "查找用户", httpMethod = "POST")
  17. @RequestMapping("/api/Test1")
  18. public TestResponse showPerson(@RequestBody TestRequest input) {
  19. TestResponse res = new TestResponse();
  20. res.setUserName("zzzili");
  21. res.setUserPass("pass");
  22. return res;
  23. }
  24. @Autowired//(required=false)
  25. private UserRepository context;
  26. @ApiOperation(value="测试mysql2_通过JPA自带方法查询",httpMethod="POST")
  27. @RequestMapping("/api/testmysql2")
  28. public List<User> TestMysql2() {
  29. List<User> list = context.findAll();
  30. System.out.println(list);
  31. return list;
  32. }
  33. @ApiOperation(value="测试mysql3_根据自定义方法名查询",httpMethod="POST")
  34. @RequestMapping("/api/testmysql3")
  35. public List<User> TestMysql3() {
  36. List<User> list = context.findByNameOrAddress("zz","ss");
  37. System.out.println(list);
  38. return list;
  39. }
  40. @ApiOperation(value="测试mysql4_自定义query查询",httpMethod="POST")
  41. @RequestMapping("/api/testmysql4")
  42. public User TestMysql4() {
  43. //User user = context.findEmail("zz");
  44. User user2 = context.findByUserId(1);
  45. System.out.println(user2);
  46. return user2;
  47. }
  48. @ApiOperation(value="测试mysql5_分页查询",httpMethod="POST")
  49. @RequestMapping("/api/testmysql5")
  50. public List<User> TestMysql5() {
  51. Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"id");
  52. Page<User> list = context.findByUserIdGreaterThan(1,pageable);
  53. System.out.println(list);
  54. return list.getContent();
  55. }
  56. }

文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。

原文链接:zzzili.blog.csdn.net/article/details/79347753

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。