今天給大家介紹一下如何SpringBoot中連接Mysql數(shù)據(jù)庫(kù),并使用JPA進(jìn)行數(shù)據(jù)庫(kù)的相關(guān)操作。
步驟一:在pom.xml文件中添加MYSQl和JPA的相關(guān)Jar包依賴,具體添加位置在dependencies中,具體添加的內(nèi)容如下所示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<!--數(shù)據(jù)庫(kù)相關(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ù)庫(kù)的相關(guān)配置,配置信息如下所示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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ù)庫(kù)名稱、root是用戶名、220316是密碼
步驟三:編寫數(shù)據(jù)庫(kù)操作的實(shí)體類,實(shí)體類具體信息如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
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ù)庫(kù)中表和字段相互對(duì)應(yīng)。下面給出一張MYSQL-JAVA各種屬性的對(duì)應(yīng)關(guān)系圖:
步驟四:編寫dao層的數(shù)據(jù)操作類,dao數(shù)據(jù)操作類如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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ì)有疑問(wèn),為什么要繼承CrudRepository<User, Integer>,具體有什么作用呢?
我這里給大家簡(jiǎn)單的介紹一下JPA中一些常用的用法和使用準(zhǔn)則:
1.首先就是要繼承CrudRepository這個(gè)方法,里面包含的兩個(gè)參數(shù)的具體含義是:第一個(gè)參數(shù)表示所操作的實(shí)體類名稱,第二個(gè)參數(shù)表示實(shí)體類中主鍵的類型。
2.繼承完之后就可以使用一些繼承自父類的方法了,比如上面所示可以使用findBy+“你要查詢的字段名稱”,通過(guò)這樣的方法就可以輕輕松松實(shí)現(xiàn)SQL查詢的功能了。
說(shuō)道這里可能大家還是有點(diǎn)迷糊,給大家舉一個(gè)例子就知道了:
例如上面的findByName(String name)其實(shí)等價(jià)于SQL語(yǔ)句中的 select *from user where name=?。這樣一對(duì)比大家是不是馬上就清楚這個(gè)方法到底代表什么含義了吧。
步驟五:編寫controller這個(gè)控制類,控制類具體信息如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
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è)很大的疑問(wèn),我當(dāng)初也對(duì)這個(gè)問(wèn)題深深的不理,那就是userDao沒(méi)有實(shí)例化為什么能夠直接使用呢?
現(xiàn)在我就為大家解釋一下為什么會(huì)這樣:
其實(shí)不是這個(gè)userDao沒(méi)有實(shí)例化,只是實(shí)例化是由系統(tǒng)自動(dòng)完成的。只要在userDao的上方添加@Autowired屬性就可以實(shí)現(xiàn)接口自動(dòng)的實(shí)例化了,完全不需要像以前一樣需要去寫什么userDaoImp之類的實(shí)現(xiàn)類了。這樣做就可以大大的挺高代碼的簡(jiǎn)易程度,開(kāi)發(fā)速度大大的挺高。
我知道現(xiàn)在可能還會(huì)有人問(wèn)這樣一個(gè)問(wèn)題:那就是自動(dòng)實(shí)例化了,可是實(shí)例化怎么知道dao類要實(shí)現(xiàn)什么的增刪改查的功能呀,dao代碼里面壓根就沒(méi)說(shuō)啊?其實(shí)有心人可能已經(jīng)發(fā)現(xiàn)了,上一步的時(shí)候我們解釋了一下findBy+“字段名”的具體作用是什么,這其實(shí)就是這個(gè)問(wèn)題的答案。其實(shí)dao層中各種方法就是daoimp中各種實(shí)現(xiàn)類中的SQl命令,具體是怎么對(duì)應(yīng)的我會(huì)再下一節(jié)中給大家詳細(xì)的介紹一下,現(xiàn)在先賣個(gè)關(guān)子。
步驟六:數(shù)據(jù)庫(kù)的表名和字段信息如下所示:
到這里關(guān)于SpringBoot中連接MYSQL數(shù)據(jù)庫(kù),并使用JPA進(jìn)行數(shù)據(jù)庫(kù)的相關(guān)操作就介紹完畢了,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/linzhiqiang0316/article/details/52609162