springboot druid+mysql掉瞳、使用JAP
這一節(jié)講述springboot 連接Mysql 數(shù)據(jù)庫(kù)钻蹬,并使用JPA 進(jìn)行CRUD操作
一:Springboot 集成druid+mysql阵难,取得數(shù)據(jù)源
準(zhǔn)備概述: 新建一個(gè)Maven java 項(xiàng)目,注意:是java 項(xiàng)目英上,不是Webapp 項(xiàng)目,以后的章節(jié)將通通采用Springboot 的官網(wǎng)推薦胧瓜,盡可能避免使用jsp、Servlet
01 pom.xml 導(dǎo)入依賴(lài):springboot跺株、熱部署复濒、模板引擎:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--springboot 熱部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!--thymeleaf 模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
02 pom.xml 添加springboot-jdbc、druid乒省、mysql
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
03 創(chuàng)建 resources/application.properties 文件巧颈,并添加數(shù)據(jù)源屬性:
# 配置默認(rèn)數(shù)據(jù)源,并使用 阿里連接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
04 pom.xml添加Springboot Junti 測(cè)試環(huán)境依賴(lài):
<!--測(cè)試環(huán)境-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
05 創(chuàng)建測(cè)試類(lèi)袖扛,測(cè)試
@RunWith(SpringJUnit4ClassRunner.class) /*添加SpringJUnit支持砸泛,引入Spring-Test框架*/
@SpringBootTest(classes = App.class) /*指定Springboot啟動(dòng)類(lèi)啟動(dòng)*/
public class TestMysql {
@Autowired
private DataSource dataSource;
@Test
public void test() throws SQLException {
System.out.println(dataSource);
System.out.println(dataSource.getConnection());
}
}
控制臺(tái)打印:
……
{
CreateTime:"2018-02-07 12:17:10",
ActiveCount:0,
PoolingCount:0,
CreateCount:0,
DestroyCount:0,
CloseCount:0,
ConnectCount:0,
Connections:[
]
}
2018-02-07 12:17:11.745 INFO 20776 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
Wed Feb 07 12:17:11 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
com.mysql.jdbc.JDBC4Connection@736309a9
……
# 數(shù)據(jù)源蛆封、mysql連接獲取成功
二:使用JPA 進(jìn)行 CRUD 操作
01 pom.xml 導(dǎo)入jpa 依賴(lài)
<!--JPA-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
02 何為JPA唇礁?
JPA=JAVA Persistence;AJVA 持久化
針對(duì)持久化操作,java 提供了一套標(biāo)準(zhǔn)的API惨篱,供開(kāi)發(fā)者實(shí)現(xiàn)盏筐,目前最常用的JPA框架是Hibernate-JPA.
spring-boot-starter-data-jpa 采用的就是 Hibernate-JPA
03 配置jpa 屬性:
######JPA 配置#####
# 聲明數(shù)據(jù)庫(kù)
spring.jpa.database=mysql
# 是否顯示SQL語(yǔ)句
spring.jpa.show-sql = true
# Hibernate 自動(dòng)DDL 操作
# create 每次加載hibernate時(shí)都會(huì)刪除上一次的生成的表
# create-drop 每次加載hibernate時(shí)根據(jù)model類(lèi)生成表,但是sessionFactory一關(guān)閉,表就自動(dòng)刪除
# update 最常用的屬性妒蛇,第一次加載hibernate時(shí)根據(jù)model類(lèi)會(huì)自動(dòng)建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫(kù))
spring.jpa.hibernate.ddl-auto=create
#配置方言
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
04 創(chuàng)建實(shí)體類(lèi) person.jack.bean/User.java,對(duì)應(yīng)建包机断、類(lèi):
@Entity
@Table(name = "user_info")
public class User {
@Id @GeneratedValue
private long id;
@Column(name = "user_name")
private String userName;
@Column(name = "user_age")
private String userAge;
@Column(name = "user_sex")
private String userSex;
public User(){
System.out.println("對(duì)象實(shí)例化楷拳!");
}
//get set 方法忽略
}
05 啟功服務(wù)绣夺,查看控制臺(tái)信息,初始體驗(yàn)hibernate JPA
#控制臺(tái)打印
對(duì)象實(shí)例化欢揖!
2018-02-07 13:53:37.617 INFO 25604 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists user_info
Hibernate: create table user_info (id bigint not null auto_increment, user_age varchar(255), user_name varchar(255), user_sex varchar(255), primary key (id))
# 因?yàn)橛性O(shè)置:
spring.jpa.hibernate.ddl-auto=create陶耍,所以服務(wù)在啟動(dòng)時(shí)會(huì)先檢查刪除user_info,然后再建表
# 因?yàn)橛性O(shè)置:
spring.jpa.show-sql = true她混,控制臺(tái)就會(huì)打印JPA操作的Sql 語(yǔ)句
06 新建 person/jack/dao/UserRepository.java 接口烈钞,使其繼承CrudRepository<S,T> 并傳遞相關(guān)泛型:
package person.jack.dao;
import org.springframework.data.repository.CrudRepository;
import person.jack.bean.User;
public interface UserRepository extends CrudRepository<User,Long> {
}
07 新建 person/jack/service/UserService,注入 UserRepository:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional(rollbackFor=Exception.class)
public void save(User user){ //新增或更改;執(zhí)行更改坤按,id字段必須有值毯欣,否則為新增
userRepository.save(user);
}
public List<User> getAll() { //查找所有
/**默認(rèn)返回的是個(gè)迭代**/
Iterable<User> userAll = userRepository.findAll();
/*轉(zhuǎn)換為 List 集合返回*/
Iterator<User> iterator = userAll.iterator();
List<User> userList = new ArrayList<User>();
while (iterator.hasNext()) {
userList.add(iterator.next());
}
return userList;
}
public User findOne(Long id){
return userRepository.findOne(id);
}
public void delete(User user){
userRepository.delete(user);
}
public void delete(Long id){
userRepository.delete(id);
}
}
08 新建 person/jack/controller/UserController,注入 UserService:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/addUser")
public String addUser(Map map,User user){
userRepository.save(user);
map.put("mesg", user);
return "result";
}
}
09 在resources 下新建默認(rèn)模板目錄:templates,創(chuàng)建模板:result.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<h1 th:text="${mesg}"></h1>
</body>
</html>
10 重啟服務(wù)臭脓,ddl-auto=create 會(huì)重新建表酗钞,瀏覽器地址欄輸入:http://localhost:8080/user/addUser/?userName=Jack&userAge=18&userSex=man ,測(cè)試新增
#頁(yè)面打印 剛剛添加的user對(duì)象的內(nèi)存地址
person.jack.bean.User@68ee4410
11 檢查控制臺(tái):
#控制臺(tái)打印
對(duì)象實(shí)例化!
Hibernate: insert into user_info (user_age, user_name, user_sex) values (?, ?, ?)
12 檢查數(shù)據(jù)庫(kù):
mysql> select * from user_info;
+----+----------+-----------+----------+
| id | user_age | user_name | user_sex |
+----+----------+-----------+----------+
| 1 | 18 | Jack | man |
+----+----------+-----------+----------+
1 row in set (0.00 sec)
mysql>
# 數(shù)據(jù)添加成功砚作!
13 瀏覽器地址欄重新輸入:http://localhost:8080/user/addUser/?id=1&userName=Jack&userAge=19&userSex=man窘奏,現(xiàn)在有id參數(shù),查看數(shù)據(jù)庫(kù)是否更新葫录!
#瀏覽器打印
person.jack.bean.User@58bd6a84
14 檢查數(shù)據(jù):
mysql> select * from user_info;
+----+----------+-----------+----------+
| id | user_age | user_name | user_sex |
+----+----------+-----------+----------+
| 1 | 19 | Jack | man |
+----+----------+-----------+----------+
1 row in set (0.00 sec)
mysql>
# user_age 由18->19 數(shù)據(jù)成功更改着裹!
總結(jié):以上即為:druid+mysql+jpa 操作數(shù)據(jù)庫(kù)