您好,登錄后才能下訂單哦!
今天給大家介紹一下如何SpringBoot中連接Mysql數(shù)據(jù)庫,并使用JPA進(jìn)行數(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ù)庫操作的實(shí)體類,實(shí)體類具體信息如下所示:
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í)體類中的類名和字段屬性都要和數(shù)據(jù)庫中表和字段相互對(duì)應(yīng)。下面給出一張MYSQL-JAVA各種屬性的對(duì)應(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); }
大家這里可能會(huì)有疑問,為什么要繼承CrudRepository<User, Integer>,具體有什么作用呢?
我這里給大家簡單的介紹一下JPA中一些常用的用法和使用準(zhǔn)則:
1.首先就是要繼承CrudRepository這個(gè)方法,里面包含的兩個(gè)參數(shù)的具體含義是:第一個(gè)參數(shù)表示所操作的實(shí)體類名稱,第二個(gè)參數(shù)表示實(shí)體類中主鍵的類型。
2.繼承完之后就可以使用一些繼承自父類的方法了,比如上面所示可以使用findBy+“你要查詢的字段名稱”,通過這樣的方法就可以輕輕松松實(shí)現(xiàn)SQL查詢的功能了。
說道這里可能大家還是有點(diǎn)迷糊,給大家舉一個(gè)例子就知道了:
例如上面的findByName(String name)其實(shí)等價(jià)于SQL語句中的 select *from user where name=?。這樣一對(duì)比大家是不是馬上就清楚這個(gè)方法到底代表什么含義了吧。
步驟五:編寫controller這個(gè)控制類,控制類具體信息如下所示:
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."; } }
大家這里可能會(huì)有一個(gè)很大的疑問,我當(dāng)初也對(duì)這個(gè)問題深深的不理,那就是userDao沒有實(shí)例化為什么能夠直接使用呢?
現(xiàn)在我就為大家解釋一下為什么會(huì)這樣:
其實(shí)不是這個(gè)userDao沒有實(shí)例化,只是實(shí)例化是由系統(tǒng)自動(dòng)完成的。只要在userDao的上方添加@Autowired屬性就可以實(shí)現(xiàn)接口自動(dòng)的實(shí)例化了,完全不需要像以前一樣需要去寫什么userDaoImp之類的實(shí)現(xiàn)類了。這樣做就可以大大的挺高代碼的簡易程度,開發(fā)速度大大的挺高。
我知道現(xiàn)在可能還會(huì)有人問這樣一個(gè)問題:那就是自動(dòng)實(shí)例化了,可是實(shí)例化怎么知道dao類要實(shí)現(xiàn)什么的增刪改查的功能呀,dao代碼里面壓根就沒說???其實(shí)有心人可能已經(jīng)發(fā)現(xiàn)了,上一步的時(shí)候我們解釋了一下findBy+“字段名”的具體作用是什么,這其實(shí)就是這個(gè)問題的答案。其實(shí)dao層中各種方法就是daoimp中各種實(shí)現(xiàn)類中的SQl命令,具體是怎么對(duì)應(yīng)的我會(huì)再下一節(jié)中給大家詳細(xì)的介紹一下,現(xiàn)在先賣個(gè)關(guān)子。
步驟六:數(shù)據(jù)庫的表名和字段信息如下所示:
到這里關(guān)于SpringBoot中連接MYSQL數(shù)據(jù)庫,并使用JPA進(jìn)行數(shù)據(jù)庫的相關(guān)操作就介紹完畢了,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。