我們在使用springBoot操作數據庫的時候,可以使用jdbcTemplate來操作數據庫,當我們使用的是spring-jdbc,Spring Boot會自動創建一個JdbcTemplate
。並可以使用 @Autowired JdbcTemplate
字段自動加載它並使其可用。
當然了我們還可以整合的MyBatis和休眠與此同時,SpringBoot默認使用的是Tomcat的JDBC連接池,如果需要使用別的連接池,例如:C3P0,DBCP,德,可以加入相關的依賴以及配置即可。
在這裏作爲囉嗦,演示一下怎麼使用C3P0,並鞏固一下自己的知識。
首先加入Maven的依賴:
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.1</version>
</dependency>
然後加入配置信息,寫入到application.yml或者application.properties中。
c3p0.jdbcUrl=jdbc:mysql://loclhost:3306/test
c3p0.user=${username}
c3p0.password=${password}
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.minPoolSize=2
c3p0.maxPoolSize=10
c3p0.maxIdleTime=1800000
c3p0.acquireIncrement=3
c3p0.maxStatements=1000
c3p0.initialPoolSize=3
c3p0.idleConnectionTestPeriod=60
c3p0.acquireRetryAttempts=30
c3p0.acquireRetryDelay=1000
c3p0.breakAfterAcquireFailure=false
c3p0.testConnectionOnCheckout=false
接着配置數據源數據源
@Configuration
public class DatasourceConfiguration {
@Bean(name = "dataSource")
@Qualifier(value = "dataSource")
@Primary
@ConfigurationProperties(prefix = "c3p0")
public DataSource dataSource()
{
return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
}
}
此時就可以使用,廢話不多說,開始說明本篇的重點。
首先加入以下springBoot的JDBC的Maven的的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
開發服務層(爲了方便,將DAO層作爲服務層的實現寫在這裏)
服務層接口定義如下:
package hello.mysql.service;
import java.util.List;
import hello.mysql.entry.User;
/**
* 業務層接口定義
* @author zhao
*
*/
public interface UserService {
User getUserById(Integer id);
public List<User> getUserList();
public int add(User user);
public int update(Integer id, User user);
public int delete(Integer id);
}
其實現如下:
package hello.mysql.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import hello.mysql.dao.UserDao;
import hello.mysql.entry.User;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate ; // 在容器中已經自動有了這個,可以直接注入並使用
@Override
public User getUserById(Integer id) {
List<User> list = jdbcTemplate.query("select *from zhao where id=?",
new Object[]{id},new BeanPropertyRowMapper(User.class));
if(list !=null && list.size() >0)
return list.get(0);
return null;
}
@Override
public List<User> getUserList() {
List<User> list = jdbcTemplate.query("select *from zhao",
new Object[]{},new BeanPropertyRowMapper(User.class));
if(list !=null && list.size() >0)
return list;
return null;
}
@Override
public int add(User user) {
return jdbcTemplate.update("insert into zhao(username,age) values(?,?)"
,new Object[] {user.getUsername(),user.getAge()});
}
@Override
public int update(Integer id, User user) {
return jdbcTemplate.update("update zhao set username=? ,age=? where id=?"
,new Object[] {user.getUsername(),user.getAge(),id} );
}
@Override
public int delete(Integer id) {
return jdbcTemplate.update("delete from zhao where id=?",id);
}
}
最後控制器層代碼如下:
package hello.mysql.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import hello.mysql.entry.Result;
import hello.mysql.entry.User;
import hello.mysql.service.UserService;
/**
* user controller控制器開發
* @author zhao
*
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService ;
/**
* 根據id查詢用戶。
* @param id
* @return Postman測試通過
*/
@GetMapping(value="/{id}")
public ResponseEntity<Result> getUserById(@PathVariable Integer id){
Result r=new Result();
try {
User user = userService.getUserById(id);
r.setStatus("200");
r.setResult(user);
} catch (Exception e) {
r.setResult(e.getClass().getName()+":"+ e.getMessage());
r.setStatus("error");
}
return ResponseEntity.ok(r);
}
/**
* 查詢用戶列表
* @return
*/
@GetMapping(value="/list")
public ResponseEntity<Result> getUserList(){
Result r= new Result() ;
try {
List<User> list = userService.getUserList();
r.setResult(list);
r.setStatus("200");
} catch (Exception e) {
r.setResult(e.getClass().getName()+":"+ e.getMessage());
r.setStatus("error");
}
return ResponseEntity.ok(r);
}
/**
* 添加用戶
* @param user
* @return Postman測試通過,選擇 post 提交, 選擇 raw 並選中 json(application/json)
*/
@PostMapping(value="/add")
public ResponseEntity<Result> add(@RequestBody User user){
Result r =new Result() ;
try {
int num = userService.add(user);
if (num <=0) {
r.setStatus("fail");
}else {
r.setStatus("ok");
}
r.setResult(num);
} catch (Exception e) {
r.setResult(e.getClass().getName()+":"+ e.getMessage());
r.setStatus("error");
}
return ResponseEntity.ok(r);
}
/**
* 根據id 刪除用戶
* @param id
* @return
*/
@DeleteMapping(value="delete/{id}")
public ResponseEntity<Result> delete(@PathVariable Integer id){
Result r =new Result() ;
try {
int result = userService.delete(id);
if(result <=0)
r.setStatus("fail");
else
r.setStatus("ok");
r.setResult(result);
} catch (Exception e) {
r.setResult(e.getClass().getName()+":"+e.getMessage());
r.setStatus("error");
}
return ResponseEntity.ok(r);
}
/** 更新用戶信息可以使用put提交方式,更關心一個具體資源對應的url
* 根據id修改用戶信息
* @param id
* @param user
* @return 通過測試
*/
@RequestMapping(value="update/{id}",method=RequestMethod.PUT)
public ResponseEntity<Result>update(@PathVariable Integer id ,@RequestBody User user){
Result r=new Result() ;
try {
int result = userService.update(id, user);
if(result <=0)
r.setStatus("fail");
else
r.setStatus("ok");
r.setResult(result);
} catch (Exception e) {
r.setResult(e.getClass().getName()+":"+ e.getMessage());
r.setStatus("error");
}
return ResponseEntity.ok(r);
}
}
ResponseEntity和ResponseBody,但是ResponseEntity中在org.springframework.http.HttpEntity的基礎上添加了http狀態碼(所述,所以,@ ResponseBody可以直接返回Json結果,但@ResponseEntity不僅可以返回json結果,還可以定義返回的HttpHeaders和HttpStatus .Result是一個自定義結構體,用於封裝返回信息。其代碼如下:
package hello.mysql.util;
public class Result {
private String status=null;
private Object result =null;
public Result status(String status) {
this.status = status;
return this ;
}
//Getter 和Setter
}
此時啓動springBoot程序(Application.java中的主函數),運行爲JavaApplication,啓動項目。
然後可通過,谷歌瀏覽器的郵遞員插件,進行測試。本程序已經過測試,全部通過,並返回正確的結果。放一張測試返回的圖吧。