SpringBoot連接MYSQL數(shù)據(jù)庫并使用JPA進行操作
今天給大家介紹一下如何SpringBoot中連接Mysql數(shù)據(jù)庫,并使用JPA進行數(shù)據(jù)庫的相關(guān)操作。
步驟一:在pom.xml文件中添加MYSQl和JPA的相關(guān)Jar包依賴,具體添加位置在dependencies中,具體添加的內(nèi)容如下所示。
<!--數(shù)據(jù)庫相關(guān)配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
步驟二:在application.properties配置文件中加入數(shù)據(jù)庫的相關(guān)配置,配置信息如下所示。
spring.datasource.url = jdbc:mysql://localhost:3306/webtest spring.datasource.username = root spring.datasource.password = 220316 spring.datasource.driverClassName = com.mysql.jdbc.Driver # Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update) spring.jpa.hibernate.ddl-auto = update # Naming strategy spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager) spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
這里給大家解釋一下:webtest代表數(shù)據(jù)庫名稱、root是用戶名、220316是密碼
步驟三:編寫數(shù)據(jù)庫操作的實體類,實體類具體信息如下所示:
package example.entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "name", nullable = true, length = 30)
private String name;
@Column(name = "height", nullable = true, length = 10)
private int height;
@Column(name = "sex", nullable = true, length = 2)
private char sex;
@Temporal(TemporalType.DATE)
private Date birthday;
@Temporal(TemporalType.TIMESTAMP)
private Date sendtime; // 日期類型,格式:yyyy-MM-dd HH:mm:ss
@Column(name = "price", nullable = true, length = 10)
private BigDecimal price;
@Column(name = "floatprice", nullable = true, length = 10)
private float floatprice;
@Column(name = "doubleprice", nullable = true, length = 10)
private double doubleprice;
public Date getSendtime() {
return sendtime;
}
public void setSendtime(Date sendtime) {
this.sendtime = sendtime;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public float getFloatprice() {
return floatprice;
}
public void setFloatprice(float floatprice) {
this.floatprice = floatprice;
}
public double getDoubleprice() {
return doubleprice;
}
public void setDoubleprice(double doubleprice) {
this.doubleprice = doubleprice;
}
public User() { }
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public User(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
大家這里需要注意的是:實體類中的類名和字段屬性都要和數(shù)據(jù)庫中表和字段相互對應(yīng)。下面給出一張MYSQL-JAVA各種屬性的對應(yīng)關(guān)系圖:

步驟四:編寫dao層的數(shù)據(jù)操作類,dao數(shù)據(jù)操作類如下所示:
package example.dao;
import example.entity.User;
import org.springframework.data.repository.CrudRepository;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Transactional
public interface UserDao extends CrudRepository<User, Integer> {
public List<User> findByName(String name);
public List<User> findBySex(char sex);
public List<User> findByBirthday(Date birthday);
public List<User> findBySendtime(Date sendtime);
public List<User> findByPrice(BigDecimal price);
public List<User> findByFloatprice(float floatprice);
public List<User> findByDoubleprice(double doubleprice);
}
大家這里可能會有疑問,為什么要繼承CrudRepository<User, Integer>,具體有什么作用呢?
我這里給大家簡單的介紹一下JPA中一些常用的用法和使用準則:
1.首先就是要繼承CrudRepository這個方法,里面包含的兩個參數(shù)的具體含義是:第一個參數(shù)表示所操作的實體類名稱,第二個參數(shù)表示實體類中主鍵的類型。
2.繼承完之后就可以使用一些繼承自父類的方法了,比如上面所示可以使用findBy+“你要查詢的字段名稱”,通過這樣的方法就可以輕輕松松實現(xiàn)SQL查詢的功能了。
說道這里可能大家還是有點迷糊,給大家舉一個例子就知道了:
例如上面的findByName(String name)其實等價于SQL語句中的 select *from user where name=?。這樣一對比大家是不是馬上就清楚這個方法到底代表什么含義了吧。
步驟五:編寫controller這個控制類,控制類具體信息如下所示:
package example.controller;
import example.dao.UserDao;
import example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserDao userDao;
@RequestMapping("/getName")
@ResponseBody
public String getByName(String name) {
List<User> userList = userDao.findByName(name);
if (userList != null && userList.size()!=0) {
return "The user length is: " + userList.size();
}
return "user " + name + " is not exist.";
}
@RequestMapping("/getSex")
@ResponseBody
public String getBySex(char sex) {
List<User> userList = userDao.findBySex(sex);
if (userList != null && userList.size()!=0) {
return "The user length is: " + userList.size();
}
return "user " + sex + " is not exist.";
}
@RequestMapping("/getBirthday")
@ResponseBody
public String findByBirthday(String birthday) {
System.out.println("birthday:"+birthday);
SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd");
List<User> userList = null;
try {
userList = userDao.findByBirthday(formate.parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
if (userList != null && userList.size()!=0) {
return "The user length is: " + userList.size();
}
return "user " + birthday + " is not exist.";
}
@RequestMapping("/getSendtime")
@ResponseBody
public String findBySendtime(String sendtime) {
System.out.println("sendtime:"+sendtime);
SimpleDateFormat formate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<User> userList = null;
try {
userList = userDao.findBySendtime(formate.parse(sendtime));
} catch (ParseException e) {
e.printStackTrace();
}
if (userList != null && userList.size()!=0) {
return "The user length is: " + userList.size();
}
return "user " + sendtime + " is not exist.";
}
@RequestMapping("/getPrice")
@ResponseBody
public String findByPrice(BigDecimal price) {
List<User> userList = null;
userList = userDao.findByPrice(price);
if (userList != null && userList.size()!=0) {
return "The user length is: " + userList.size();
}
return "user " + price + " is not exist.";
}
@RequestMapping("/getFloatprice")
@ResponseBody
public String findFloatprice(float floatprice) {
List<User> userList = null;
userList = userDao.findByFloatprice(floatprice);
if (userList != null && userList.size()!=0) {
return "The user length is: " + userList.size();
}
return "user " + floatprice + " is not exist.";
}
@RequestMapping("/getDoubleprice")
@ResponseBody
public String findByPrice(double doubleprice) {
List<User> userList = null;
userList = userDao.findByDoubleprice(doubleprice);
if (userList != null && userList.size()!=0) {
return "The user length is: " + userList.size();
}
return "user " + doubleprice + " is not exist.";
}
}
大家這里可能會有一個很大的疑問,我當初也對這個問題深深的不理,那就是userDao沒有實例化為什么能夠直接使用呢?
現(xiàn)在我就為大家解釋一下為什么會這樣:
其實不是這個userDao沒有實例化,只是實例化是由系統(tǒng)自動完成的。只要在userDao的上方添加@Autowired屬性就可以實現(xiàn)接口自動的實例化了,完全不需要像以前一樣需要去寫什么userDaoImp之類的實現(xiàn)類了。這樣做就可以大大的挺高代碼的簡易程度,開發(fā)速度大大的挺高。
我知道現(xiàn)在可能還會有人問這樣一個問題:那就是自動實例化了,可是實例化怎么知道dao類要實現(xiàn)什么的增刪改查的功能呀,dao代碼里面壓根就沒說?。科鋵嵱行娜丝赡芤呀?jīng)發(fā)現(xiàn)了,上一步的時候我們解釋了一下findBy+“字段名”的具體作用是什么,這其實就是這個問題的答案。其實dao層中各種方法就是daoimp中各種實現(xiàn)類中的SQl命令,具體是怎么對應(yīng)的我會再下一節(jié)中給大家詳細的介紹一下,現(xiàn)在先賣個關(guān)子。
步驟六:數(shù)據(jù)庫的表名和字段信息如下所示:

到這里關(guān)于SpringBoot中連接MYSQL數(shù)據(jù)庫,并使用JPA進行數(shù)據(jù)庫的相關(guān)操作就介紹完畢了,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- JPA之映射mysql text類型的問題
- Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式
- Spring boot基于JPA訪問MySQL數(shù)據(jù)庫的實現(xiàn)
- 解決springboot的JPA在Mysql8新增記錄失敗的問題
- Spring Data Jpa Mysql使用utf8mb4編碼的示例代碼
- springboot使用spring-data-jpa操作MySQL數(shù)據(jù)庫
- Spring-Data-JPA整合MySQL和配置的方法
- Spring Boot 添加MySQL數(shù)據(jù)庫及JPA實例
- 在JPA項目啟動時如何新增MySQL字段
相關(guān)文章
Java中String和StringBuffer及StringBuilder?有什么區(qū)別
這篇文章主要介紹了Java中String和StringBuffer及StringBuilder?有什么區(qū)別,String?是?Java?語言非?;A(chǔ)和重要的類,更多相關(guān)內(nèi)容需要的小伙伴可以參考下面文章內(nèi)容2022-06-06
break和continue的作用和區(qū)別解析(案例分析)
break和continue都是用來控制循環(huán)結(jié)構(gòu)的,主要作用是停止循環(huán),這篇文章主要介紹了break和continue的作用和區(qū)別,需要的朋友可以參考下2023-03-03

