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

来源:互联网 发布:一个皇冠什么软件 编辑:程序博客网 时间:2024/06/05 14:57

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

步骤一:在pom.xml文件中添加MYSQl和JPA的相关Jar包依赖,具体添加位置在dependencies中,具体添加的内容如下所示。
[html] view plain copy
  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配置文件中加入数据库的相关配置,配置信息如下所示。
[html] view plain copy
  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是密码
步骤三:编写数据库操作的实体类,实体类具体信息如下所示:
[java] view plain copy
  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.   
  13.     @Column(name = "name", nullable = true, length = 30)  
  14.     private String name;  
  15.   
  16.     @Column(name = "height", nullable = true, length = 10)  
  17.     private int height;  
  18.   
  19.     @Column(name = "sex", nullable = true, length = 2)  
  20.     private char sex;  
  21.   
  22.     @Temporal(TemporalType.DATE)  
  23.     private Date birthday;  
  24.   
  25.     @Temporal(TemporalType.TIMESTAMP)  
  26.     private Date sendtime; // 日期类型,格式:yyyy-MM-dd HH:mm:ss  
  27.   
  28.     @Column(name = "price", nullable = true, length = 10)  
  29.     private BigDecimal price;  
  30.   
  31.     @Column(name = "floatprice", nullable = true, length = 10)  
  32.     private float floatprice;  
  33.   
  34.   
  35.     @Column(name = "doubleprice", nullable = true, length = 10)  
  36.     private double doubleprice;  
  37.   
  38.     public Date getSendtime() {  
  39.         return sendtime;  
  40.     }  
  41.   
  42.     public void setSendtime(Date sendtime) {  
  43.         this.sendtime = sendtime;  
  44.     }  
  45.   
  46.     public BigDecimal getPrice() {  
  47.         return price;  
  48.     }  
  49.   
  50.     public void setPrice(BigDecimal price) {  
  51.         this.price = price;  
  52.     }  
  53.   
  54.     public float getFloatprice() {  
  55.         return floatprice;  
  56.     }  
  57.   
  58.     public void setFloatprice(float floatprice) {  
  59.         this.floatprice = floatprice;  
  60.     }  
  61.   
  62.     public double getDoubleprice() {  
  63.         return doubleprice;  
  64.     }  
  65.   
  66.     public void setDoubleprice(double doubleprice) {  
  67.         this.doubleprice = doubleprice;  
  68.     }  
  69.   
  70.     public User() { }  
  71.   
  72.     public char getSex() {  
  73.         return sex;  
  74.     }  
  75.   
  76.     public void setSex(char sex) {  
  77.         this.sex = sex;  
  78.     }  
  79.   
  80.     public Date getBirthday() {  
  81.         return birthday;  
  82.     }  
  83.   
  84.     public void setBirthday(Date birthday) {  
  85.         this.birthday = birthday;  
  86.     }  
  87.   
  88.     public User(int id) {  
  89.         this.id = id;  
  90.     }  
  91.   
  92.     public int getId() {  
  93.         return id;  
  94.     }  
  95.   
  96.     public void setId(int id) {  
  97.         this.id = id;  
  98.     }  
  99.   
  100.     public String getName() {  
  101.         return name;  
  102.     }  
  103.   
  104.     public void setName(String name) {  
  105.         this.name = name;  
  106.     }  
  107.   
  108.     public int getHeight() {  
  109.         return height;  
  110.     }  
  111.   
  112.     public void setHeight(int height) {  
  113.         this.height = height;  
  114.     }  
  115. }  
大家这里需要注意的是:实体类中的类名和字段属性都要和数据库中表和字段相互对应。下面给出一张MYSQL-JAVA各种属性的对应关系图:


步骤四:编写dao层的数据操作类,dao数据操作类如下所示:
[java] view plain copy
  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.   
  9. @Transactional  
  10. public interface UserDao extends CrudRepository<User, Integer> {  
  11.     public List<User> findByName(String name);  
  12.     public List<User> findBySex(char sex);  
  13.     public List<User> findByBirthday(Date birthday);  
  14.     public List<User> findBySendtime(Date sendtime);  
  15.     public List<User> findByPrice(BigDecimal price);  
  16.     public List<User> findByFloatprice(float floatprice);  
  17.     public List<User> findByDoubleprice(double doubleprice);  
  18. }  
大家这里可能会有疑问,为什么要继承CrudRepository<User, Integer>,具体有什么作用呢?
我这里给大家简单的介绍一下JPA中一些常用的用法和使用准则:
1.首先就是要继承CrudRepository这个方法,里面包含的两个参数的具体含义是:第一个参数表示所操作的实体类名称,第二个参数表示实体类中主键的类型。
2.继承完之后就可以使用一些继承自父类的方法了,比如上面所示可以使用findBy+“你要查询的字段名称”,通过这样的方法就可以轻轻松松实现SQL查询的功能了。
说道这里可能大家还是有点迷糊,给大家举一个例子就知道了:
例如上面的findByName(String name)其实等价于SQL语句中的 select *from user where name=?。这样一对比大家是不是马上就清楚这个方法到底代表什么含义了吧。
步骤五:编写controller这个控制类,控制类具体信息如下所示:
[java] view plain copy
  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.   
  27.     @RequestMapping("/getSex")  
  28.     @ResponseBody  
  29.     public String getBySex(char sex) {  
  30.         List<User> userList = userDao.findBySex(sex);  
  31.         if (userList != null && userList.size()!=0) {  
  32.             return "The user length is: " + userList.size();  
  33.         }  
  34.         return "user " + sex + " is not exist.";  
  35.     }  
  36.   
  37.     @RequestMapping("/getBirthday")  
  38.     @ResponseBody  
  39.     public String findByBirthday(String birthday) {  
  40.         System.out.println("birthday:"+birthday);  
  41.         SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd");  
  42.         List<User> userList = null;  
  43.         try {  
  44.             userList = userDao.findByBirthday(formate.parse(birthday));  
  45.         } catch (ParseException e) {  
  46.             e.printStackTrace();  
  47.         }  
  48.         if (userList != null && userList.size()!=0) {  
  49.             return "The user length is: " + userList.size();  
  50.         }  
  51.         return "user " + birthday + " is not exist.";  
  52.     }  
  53.   
  54.     @RequestMapping("/getSendtime")  
  55.     @ResponseBody  
  56.     public String findBySendtime(String sendtime) {  
  57.         System.out.println("sendtime:"+sendtime);  
  58.         SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  59.         List<User> userList = null;  
  60.         try {  
  61.             userList = userDao.findBySendtime(formate.parse(sendtime));  
  62.         } catch (ParseException e) {  
  63.             e.printStackTrace();  
  64.         }  
  65.         if (userList != null && userList.size()!=0) {  
  66.             return "The user length is: " + userList.size();  
  67.         }  
  68.         return "user " + sendtime + " is not exist.";  
  69.     }  
  70.   
  71.     @RequestMapping("/getPrice")  
  72.     @ResponseBody  
  73.     public String findByPrice(BigDecimal price) {  
  74.         List<User> userList = null;  
  75.         userList = userDao.findByPrice(price);  
  76.         if (userList != null && userList.size()!=0) {  
  77.             return "The user length is: " + userList.size();  
  78.         }  
  79.         return "user " + price + " is not exist.";  
  80.     }  
  81.   
  82.     @RequestMapping("/getFloatprice")  
  83.     @ResponseBody  
  84.     public String findFloatprice(float floatprice) {  
  85.         List<User> userList = null;  
  86.         userList = userDao.findByFloatprice(floatprice);  
  87.         if (userList != null && userList.size()!=0) {  
  88.             return "The user length is: " + userList.size();  
  89.         }  
  90.         return "user " + floatprice + " is not exist.";  
  91.     }  
  92.   
  93.     @RequestMapping("/getDoubleprice")  
  94.     @ResponseBody  
  95.     public String findByPrice(double doubleprice) {  
  96.         List<User> userList = null;  
  97.         userList = userDao.findByDoubleprice(doubleprice);  
  98.         if (userList != null && userList.size()!=0) {  
  99.             return "The user length is: " + userList.size();  
  100.         }  
  101.         return "user " + doubleprice + " is not exist.";  
  102.     }  
  103. }  
大家这里可能会有一个很大的疑问,我当初也对这个问题深深的不理,那就是userDao没有实例化为什么能够直接使用呢?
现在我就为大家解释一下为什么会这样:
其实不是这个userDao没有实例化,只是实例化是由系统自动完成的。只要在userDao的上方添加@Autowired属性就可以实现接口自动的实例化了,完全不需要像以前一样需要去写什么userDaoImp之类的实现类了。这样做就可以大大的挺高代码的简易程度,开发速度大大的挺高。
我知道现在可能还会有人问这样一个问题:那就是自动实例化了,可是实例化怎么知道dao类要实现什么的增删改查的功能呀,dao代码里面压根就没说啊?其实有心人可能已经发现了,上一步的时候我们解释了一下findBy+“字段名”的具体作用是什么,这其实就是这个问题的答案。其实dao层中各种方法就是daoimp中各种实现类中的SQl命令,具体是怎么对应的我会再下一节中给大家详细的介绍一下,现在先卖个关子。
步骤六:数据库的表名和字段信息如下所示:


原创粉丝点击