sql数据库JDBCTemplate和JPA使用
《SpringBoot實戰(zhàn)派》一書第八章用ORM操作SQL數(shù)據(jù)庫,具體操作過程和踩坑實錄。
第一,由于本臺計算機上沒有安裝mysql,在練習(xí)書中代碼的時候,誤以為本機不需要數(shù)據(jù)庫便可以運行代碼,導(dǎo)致卡了好久。
第二,把當時學(xué)習(xí)Mysql重拾起來,算是學(xué)以致用。
第三,遇到問題就一步一步解決問題,有挫敗感正常,學(xué)會越挫越勇,轉(zhuǎn)移挫敗感逐漸找回信心直到正反饋的出現(xiàn)。任何人學(xué)習(xí)代碼都是這個過程。
文章目錄
- 0.認識JDBC Template
- 1.使用JDBCTemplate實現(xiàn)數(shù)據(jù)的增加、刪除、修改和查詢
- 2.用JPA構(gòu)建mysql實體數(shù)據(jù)表
0.認識JDBC Template
JDBC(Java DataBase Connectivity)是Java用于連接數(shù)據(jù)庫的規(guī)范,也就是用于執(zhí)行數(shù)據(jù)庫SQL語句的Java API。它是由一組用Java語言編寫的類和接口組成,為大部分關(guān)系型數(shù)據(jù)庫提供訪問接口。
JDBC需要每次進行數(shù)據(jù)庫連接,然后處理SQL語句、傳值、關(guān)閉數(shù)據(jù)庫。如果都由開發(fā)人員編寫代碼,則很容易出錯,可能會出現(xiàn)使用完成之后,數(shù)據(jù)庫連接忘記關(guān)閉的情況。這容易導(dǎo)致連接被占用而降低性能,為了減少這種可能的錯誤,減少開發(fā)人員的工作量,JDBCTemplate被設(shè)計出來。
JDBCTemplate
JDBCTemplate=JDBC+Template,是對JDBC的封裝。它更便于程序?qū)崿F(xiàn),替我們完成所有的JDBC底層工作。因此,對于數(shù)據(jù)庫的操作,再不需要每次都進行連接、打開、關(guān)閉了。
JDBC和JDBCTemplate就像倉庫管理員,負責(zé)從倉庫中存取物品。而后者不需要每次進入都開門,取完關(guān)門,因為有電動門自動控制。
1.使用JDBCTemplate實現(xiàn)數(shù)據(jù)的增加、刪除、修改和查詢
項目結(jié)構(gòu)
添加依賴
要使用JDBCTemplate,則需要添加其Starter依賴。因為要操作數(shù)據(jù)庫,所有也需要配置數(shù)據(jù)庫(以mysql為例)的連接依賴
添加完依賴之后,還需要配置數(shù)據(jù)庫的連接信息。這樣JDBC才能正常連接到數(shù)據(jù)庫。在application.properties配置文件中配置數(shù)據(jù)庫的地址和用戶信息
//配置ip地址,編碼,時區(qū)和SSL spring.datasource.url=jdbc:mysql://127.0.0.1/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true //用戶名 spring.datasource.username=root //密碼 spring.datasource.password= spring.datasource.driver-class-name=com.mysql.cj.jdbc.DriverUser.java
新建一個測試實體類User,實現(xiàn)RowMapper類,重寫mapRow方法,以便實現(xiàn)字段和數(shù)據(jù)表字段映射。映射是指把Java中設(shè)置的實體字段和mysql數(shù)據(jù)庫的字段對應(yīng)起來,因為實體id可以對應(yīng)數(shù)據(jù)庫字段的u_id,也可以對應(yīng)id、那么等。如果不重寫,則程序不知道如何對應(yīng)。
JDBCTemplate提供了以下操作數(shù)據(jù)的3個方法
| execute | 表示執(zhí)行,用于直接執(zhí)行sql語句 |
| update | 表示更新,包括新增、修改、刪除操作 |
| query | 表示查詢 |
1)創(chuàng)建數(shù)據(jù)表
在使用JDBCTemplate之前,需要在控制器中注入JDBCTemplate,然后可以通過execute方法執(zhí)行sql語句
2)添加數(shù)據(jù)
通過update方法
3)查詢修改刪除數(shù)據(jù)
執(zhí)行sql字符串里面的SQL語句,通過query,update方法
UserController.java
package com.example.demo.controller;import com.example.demo.model.User; import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList; import java.util.List; import java.util.Map;import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @SpringBootTest @RunWith(SpringRunner.class)/*** @author longzhonghua* @data 2/24/2019 9:51 AM*/ @RestController @RequestMapping("user") public class UserController {@Autowiredprivate JdbcTemplate jdbcTemplate;@Test//創(chuàng)建數(shù)據(jù)表@GetMapping("createUserTable")public void createUserTable() throws Exception {String sql = "CREATE TABLE `user` (\n" +" `id` int(10) NOT NULL AUTO_INCREMENT,\n" +" `username` varchar(100) DEFAULT NULL,\n" +" `password` varchar(100) DEFAULT NULL,\n" +" PRIMARY KEY (`id`)\n" +") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;\n" +"\n";jdbcTemplate.execute(sql);}@Test//saveUserTest//添加一個測試數(shù)據(jù)@GetMapping("saveUserTest")public void saveUserTest()throws Exception {String sql = "INSERT INTO user (USERNAME,PASSWORD) VALUES ('longzhiran','123456')";int rows = jdbcTemplate.update(sql);System.out.println(rows);}@Test//updateUserPassword?id=1&passWord=12345678@GetMapping("updateUserPassword")public void updateUserPassword() throws Exception {Integer id=1;String passWord="999888";String sql = "UPDATE user SET PASSWORD = ? WHERE ID = ?";int rows = jdbcTemplate.update(sql, passWord, id);System.out.println(rows);}@Test//deleteUserById?id=1@GetMapping("deleteUserById")public void deleteUserById() throws Exception {String sql = "DELETE FROM user WHERE ID = ?";int rows = jdbcTemplate.update(sql, 1);System.out.println(rows);}@Test//getUserByName?userName=longzhiran@GetMapping("getUserByName")public void getUserByName()throws Exception {String name="longzhonghua";String sql = "SELECT * FROM user WHERE USERNAME = ?";List<User> list = jdbcTemplate.query(sql, new User(), new Object[]{name});for(User user:list){System.out.println(user);}}@Test//getAll@GetMapping("list")public void list() throws Exception {String sql = "SELECT * FROM user limit 1000";List<User> userList = jdbcTemplate.query(sql,new BeanPropertyRowMapper(User.class));for(User userLists:userList){System.out.println(userLists);}}}運行項目
然后運行test創(chuàng)建數(shù)據(jù)表
打開book數(shù)據(jù)庫,發(fā)現(xiàn)多了一張名為user的表
運行測試
在mysql中查看,發(fā)現(xiàn)多了一個用戶
運行測試
在mysql中查看,密碼已經(jīng)修改
運行測試
在mysql中查看
id=1的用戶信息已經(jīng)刪除
2.用JPA構(gòu)建mysql實體數(shù)據(jù)表
第一步:安裝mysql,這里筆者安裝的是mysql 8.0.20
安裝請移步筆者的另一篇博客:Mysql8.0.20下載和安裝
第二步:創(chuàng)建數(shù)據(jù)庫book
第三步就是IDEA中的操作
0.添加依賴
需要注意的是:注意mysql的版本需要設(shè)置正確
1.配置文件
這里的數(shù)據(jù)庫用戶名和密碼是自己的,一般為root和root
spring.datasource.url=jdbc:mysql://127.0.0.1/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql= truespring.thymeleaf.cache=false server.port=8080當時報錯:
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
學(xué)習(xí)《Spring Boot實戰(zhàn)派》時由于沒有本臺電腦上沒有安裝mysql,所以自然連不上,需要先安裝mysql 然后創(chuàng)建數(shù)據(jù)庫book。
后面踩過的坑
遇到問題
解決方法:更改mysql依賴的版本
然后接著報錯
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 08001 o.h.engine.jdbc.spi.SqlExceptionHelper : Public Key Retrieval is not allowed解決方案:cmd中登錄mysql數(shù)據(jù)庫 mysql -u root -p 輸入密碼
又遇到錯誤
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1049, SQLState: 42000 o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown database 'book'新建數(shù)據(jù)庫book,使得本機存在book數(shù)據(jù)庫
Article.java
package com.example.demo.entity;import com.sun.org.apache.xpath.internal.operations.Bool; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Arrays; import java.util.List;@Entity @Data public class Article implements Serializable{@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private long id;@Column(nullable = false,unique = true)@NotEmpty(message = "標題不能為空")private String title;@Column(columnDefinition = "enum('圖','圖文','文')")private String type;private Boolean available=Boolean.FALSE;@Size(min=0,max=20)private String keyword;@Size(max=255)private String description;@Column(nullable = false)private String body;@Transientprivate List keywordlists;public List getKeywordlists(){return Arrays.asList(this.keyword.trim().split("|"));}public void setKeywordlists(List keywordlists){this.keywordlists=keywordlists;} }運行項目之后會生成數(shù)據(jù)表如下圖
總結(jié)
以上是生活随笔為你收集整理的sql数据库JDBCTemplate和JPA使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java元注解
- 下一篇: cmd中如何切换指定目录