当前位置:   article > 正文

SpringBoot中连接MYSQL数据库,并使用JPA进行数据库的相关操作_springboot jpa mysql

springboot jpa mysql

今天给大家介绍一下如何SpringBoot中连接Mysql数据库,并使用JPA进行数据库的相关操作。

史上最全Java技术栈面试题都在这里面了:Java面试题

步骤一:在pom.xml文件中添加MYSQl和JPA的相关Jar包依赖,具体添加位置在dependencies中,具体添加的内容如下所示。

  1. <!--数据库相关配置-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-data-jpa</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>mysql</groupId>
  12. <artifactId>mysql-connector-java</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.apache.poi</groupId>
  16. <artifactId>poi</artifactId>
  17. <version>3.11</version>
  18. </dependency>

步骤二:在application.properties配置文件中加入数据库的相关配置,配置信息如下所示。

  1. spring.datasource.url = jdbc:mysql://localhost:3306/webtest
  2. spring.datasource.username = root
  3. spring.datasource.password = 220316
  4. spring.datasource.driverClassName = com.mysql.jdbc.Driver
  5. # Specify the DBMS
  6. spring.jpa.database = MYSQL
  7. # Show or not log for each sql query
  8. spring.jpa.show-sql = true
  9. # Hibernate ddl auto (create, create-drop, update)
  10. spring.jpa.hibernate.ddl-auto = update
  11. # Naming strategy
  12. spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
  13. # stripped before adding them to the entity manager)
  14. spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

这里给大家解释一下:webtest代表数据库名称、root是用户名、220316是密码

步骤三:编写数据库操作的实体类,实体类具体信息如下所示:

  1. package example.entity;
  2. import javax.persistence.*;
  3. import javax.validation.constraints.NotNull;
  4. import java.math.BigDecimal;
  5. import java.util.Date;
  6. @Entity
  7. @Table(name = "user")
  8. public class User {
  9. @Id
  10. @GeneratedValue(strategy = GenerationType.AUTO)
  11. private int id;
  12. @Column(name = "name", nullable = true, length = 30)
  13. private String name;
  14. @Column(name = "height", nullable = true, length = 10)
  15. private int height;
  16. @Column(name = "sex", nullable = true, length = 2)
  17. private char sex;
  18. @Temporal(TemporalType.DATE)
  19. private Date birthday;
  20. @Temporal(TemporalType.TIMESTAMP)
  21. private Date sendtime; // 日期类型,格式:yyyy-MM-dd HH:mm:ss
  22. @Column(name = "price", nullable = true, length = 10)
  23. private BigDecimal price;
  24. @Column(name = "floatprice", nullable = true, length = 10)
  25. private float floatprice;
  26. @Column(name = "doubleprice", nullable = true, length = 10)
  27. private double doubleprice;
  28. public Date getSendtime() {
  29. return sendtime;
  30. }
  31. public void setSendtime(Date sendtime) {
  32. this.sendtime = sendtime;
  33. }
  34. public BigDecimal getPrice() {
  35. return price;
  36. }
  37. public void setPrice(BigDecimal price) {
  38. this.price = price;
  39. }
  40. public float getFloatprice() {
  41. return floatprice;
  42. }
  43. public void setFloatprice(float floatprice) {
  44. this.floatprice = floatprice;
  45. }
  46. public double getDoubleprice() {
  47. return doubleprice;
  48. }
  49. public void setDoubleprice(double doubleprice) {
  50. this.doubleprice = doubleprice;
  51. }
  52. public User() { }
  53. public char getSex() {
  54. return sex;
  55. }
  56. public void setSex(char sex) {
  57. this.sex = sex;
  58. }
  59. public Date getBirthday() {
  60. return birthday;
  61. }
  62. public void setBirthday(Date birthday) {
  63. this.birthday = birthday;
  64. }
  65. public User(int id) {
  66. this.id = id;
  67. }
  68. public int getId() {
  69. return id;
  70. }
  71. public void setId(int id) {
  72. this.id = id;
  73. }
  74. public String getName() {
  75. return name;
  76. }
  77. public void setName(String name) {
  78. this.name = name;
  79. }
  80. public int getHeight() {
  81. return height;
  82. }
  83. public void setHeight(int height) {
  84. this.height = height;
  85. }
  86. }

大家这里需要注意的是:实体类中的类名和字段属性都要和数据库中表和字段相互对应。下面给出一张MYSQL-JAVA各种属性的对应关系图:


 

步骤四:编写dao层的数据操作类,dao数据操作类如下所示:

  1. package example.dao;
  2. import example.entity.User;
  3. import org.springframework.data.repository.CrudRepository;
  4. import javax.transaction.Transactional;
  5. import java.math.BigDecimal;
  6. import java.util.Date;
  7. import java.util.List;
  8. @Transactional
  9. public interface UserDao extends CrudRepository<User, Integer> {
  10. public List<User> findByName(String name);
  11. public List<User> findBySex(char sex);
  12. public List<User> findByBirthday(Date birthday);
  13. public List<User> findBySendtime(Date sendtime);
  14. public List<User> findByPrice(BigDecimal price);
  15. public List<User> findByFloatprice(float floatprice);
  16. public List<User> findByDoubleprice(double doubleprice);
  17. }

大家这里可能会有疑问,为什么要继承CrudRepository<User, Integer>,具体有什么作用呢?

我这里给大家简单的介绍一下JPA中一些常用的用法和使用准则:

1.首先就是要继承CrudRepository这个方法,里面包含的两个参数的具体含义是:第一个参数表示所操作的实体类名称,第二个参数表示实体类中主键的类型。

2.继承完之后就可以使用一些继承自父类的方法了,比如上面所示可以使用findBy+“你要查询的字段名称”,通过这样的方法就可以轻轻松松实现SQL查询的功能了。

说道这里可能大家还是有点迷糊,给大家举一个例子就知道了:

例如上面的findByName(String name)其实等价于SQL语句中的 select *from user where name=?。这样一对比大家是不是马上就清楚这个方法到底代表什么含义了吧。

步骤五:编写controller这个控制类,控制类具体信息如下所示:

  1. package example.controller;
  2. import example.dao.UserDao;
  3. import example.entity.User;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import java.math.BigDecimal;
  9. import java.text.ParseException;
  10. import java.text.SimpleDateFormat;
  11. import java.util.Date;
  12. import java.util.List;
  13. @Controller
  14. public class UserController {
  15. @Autowired
  16. private UserDao userDao;
  17. @RequestMapping("/getName")
  18. @ResponseBody
  19. public String getByName(String name) {
  20. List<User> userList = userDao.findByName(name);
  21. if (userList != null && userList.size()!=0) {
  22. return "The user length is: " + userList.size();
  23. }
  24. return "user " + name + " is not exist.";
  25. }
  26. @RequestMapping("/getSex")
  27. @ResponseBody
  28. public String getBySex(char sex) {
  29. List<User> userList = userDao.findBySex(sex);
  30. if (userList != null && userList.size()!=0) {
  31. return "The user length is: " + userList.size();
  32. }
  33. return "user " + sex + " is not exist.";
  34. }
  35. @RequestMapping("/getBirthday")
  36. @ResponseBody
  37. public String findByBirthday(String birthday) {
  38. System.out.println("birthday:"+birthday);
  39. SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd");
  40. List<User> userList = null;
  41. try {
  42. userList = userDao.findByBirthday(formate.parse(birthday));
  43. } catch (ParseException e) {
  44. e.printStackTrace();
  45. }
  46. if (userList != null && userList.size()!=0) {
  47. return "The user length is: " + userList.size();
  48. }
  49. return "user " + birthday + " is not exist.";
  50. }
  51. @RequestMapping("/getSendtime")
  52. @ResponseBody
  53. public String findBySendtime(String sendtime) {
  54. System.out.println("sendtime:"+sendtime);
  55. SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  56. List<User> userList = null;
  57. try {
  58. userList = userDao.findBySendtime(formate.parse(sendtime));
  59. } catch (ParseException e) {
  60. e.printStackTrace();
  61. }
  62. if (userList != null && userList.size()!=0) {
  63. return "The user length is: " + userList.size();
  64. }
  65. return "user " + sendtime + " is not exist.";
  66. }
  67. @RequestMapping("/getPrice")
  68. @ResponseBody
  69. public String findByPrice(BigDecimal price) {
  70. List<User> userList = null;
  71. userList = userDao.findByPrice(price);
  72. if (userList != null && userList.size()!=0) {
  73. return "The user length is: " + userList.size();
  74. }
  75. return "user " + price + " is not exist.";
  76. }
  77. @RequestMapping("/getFloatprice")
  78. @ResponseBody
  79. public String findFloatprice(float floatprice) {
  80. List<User> userList = null;
  81. userList = userDao.findByFloatprice(floatprice);
  82. if (userList != null && userList.size()!=0) {
  83. return "The user length is: " + userList.size();
  84. }
  85. return "user " + floatprice + " is not exist.";
  86. }
  87. @RequestMapping("/getDoubleprice")
  88. @ResponseBody
  89. public String findByPrice(double doubleprice) {
  90. List<User> userList = null;
  91. userList = userDao.findByDoubleprice(doubleprice);
  92. if (userList != null && userList.size()!=0) {
  93. return "The user length is: " + userList.size();
  94. }
  95. return "user " + doubleprice + " is not exist.";
  96. }
  97. }

大家这里可能会有一个很大的疑问,我当初也对这个问题深深的不理,那就是userDao没有实例化为什么能够直接使用呢?

现在我就为大家解释一下为什么会这样:

其实不是这个userDao没有实例化,只是实例化是由系统自动完成的。只要在userDao的上方添加@Autowired属性就可以实现接口自动的实例化了,完全不需要像以前一样需要去写什么userDaoImp之类的实现类了。这样做就可以大大的挺高代码的简易程度,开发速度大大的挺高。

我知道现在可能还会有人问这样一个问题:那就是自动实例化了,可是实例化怎么知道dao类要实现什么的增删改查的功能呀,dao代码里面压根就没说啊?其实有心人可能已经发现了,上一步的时候我们解释了一下findBy+“字段名”的具体作用是什么,这其实就是这个问题的答案。其实dao层中各种方法就是daoimp中各种实现类中的SQl命令,具体是怎么对应的我会再下一节中给大家详细的介绍一下,现在先卖个关子。

步骤六:数据库的表名和字段信息如下所示:

 
 

到这里关于SpringBoot中连接MYSQL数据库,并使用JPA进行数据库的相关操作就介绍完毕了。

如果大家对文章有什么问题或者疑意之类的,可以加我订阅号在上面留言,订阅号上面我会定期更新最新博客。如果嫌麻烦可以直接加我wechat:lzqcode


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/498118
推荐阅读
相关标签
  

闽ICP备14008679号