1、springboot jdbc操作数据库 最简单方式
pom.xml添加依赖
dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
package modle
package com.dj.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Article {
private Long id;
private String author;
private String title;
private String content;
private Date createTime;
// private List<Reader> reader;
}
package dao
package com.dj.dao;
import com.dj.model.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository //持久层依赖注入注解
public class ArticleJDBCDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
//保存文章
public void save(Article article) {
//jdbcTemplate.update适合于insert 、update和delete操作;
jdbcTemplate.update("INSERT INTO article(author, title,content,create_time) values(?, ?, ?, ?)",
article.getAuthor(),
article.getTitle(),
article.getContent(),
article.getCreateTime());
}
//删除文章
public void deleteById(Long id) {
//jdbcTemplate.update适合于insert 、update和delete操作;
jdbcTemplate.update("DELETE FROM article WHERE id = ?",id);
}
//更新文章
public void updateById(Article article) {
//jdbcTemplate.update适合于insert 、update和delete操作;
jdbcTemplate.update("UPDATE article SET author = ?, title = ? ,content = ?,create_time = ? WHERE id = ?",
article.getAuthor(),
article.getTitle(),
article.getContent(),
article.getCreateTime(),
article.getId());
}
//根据id查找文章
public Article findById(Long id) {
//queryForObject用于查询单条记录返回结果
return (Article) jdbcTemplate.queryForObject("SELECT * FROM article WHERE id=?",
new Object[]{id},new BeanPropertyRowMapper<>(Article.class));
}
//查询所有
public List<Article> findAll(){
//query用于查询结果列表
return (List<Article>) jdbcTemplate.query("SELECT * FROM article ", new BeanPropertyRowMapper<>(Article.class));
}
}
package controller
package com.dj.controller;
import com.dj.dao.ArticleJDBCDAO;
import com.dj.model.Article;
import com.dj.response.AjaxResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleController {
@Autowired
ArticleJDBCDAO articlejdbcdao;
//获取一篇Article,使用GET方法,根据id查询一篇文章
//@RequestMapping(value = "/articles/{id}",method = RequestMethod.GET)
@GetMapping("/articles/{id}")
public AjaxResponse getArticle(@PathVariable("id") Long id){
System.out.println("查询文章");
//使用lombok提供的builder构建对象
Article a = articlejdbcdao.findById(id);
System.out.println("测试");
System.out.println(a);
log.info("article:" + a);
return AjaxResponse.success(a);
}
//增加一篇Article ,使用POST方法(RequestBody方式接收参数)
//@RequestMapping(value = "/articles",method = RequestMethod.POST)
@PostMapping("/articles")
public AjaxResponse saveArticle(@RequestBody Article article)
{
//因为使用了lombok的Slf4j注解,这里可以直接使用log变量打印日志
log.info("saveArticle:" + article);
return AjaxResponse.success();
}
//增加一篇Article ,使用POST方法(RequestParam方式接收参数)
/*@PostMapping("/articles")
public AjaxResponse saveArticle(@RequestParam String author,
@RequestParam String title,
@RequestParam String content,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam Date createTime){
log.info("saveArticle:" + createTime);
return AjaxResponse.success();
}*/
//更新一篇Article,使用PUT方法,以id为主键进行更新
//@RequestMapping(value = "/articles",method = RequestMethod.PUT)
@PutMapping("/articles")
public AjaxResponse updateArticle(@RequestBody Article article){
if(article.getId() == null){
//article.id是必传参数,因为通常根据id去修改数据
//TODO 抛出一个自定义的异常
}
log.info("updateArticle:" + article);
return AjaxResponse.success();
}
//删除一篇Article,使用DELETE方法,参数是id
//@RequestMapping(value = "/articles/{id}",method = RequestMethod.DELETE)
@DeleteMapping("/articles/{id}")
public AjaxResponse deleteArticle(@PathVariable("id") Long id){
log.info("deleteArticle:" + id);
return AjaxResponse.success();
}
}
2、添加service层操作数据库
添加service
package com.dj.sercive;
import com.dj.model.Article;
import java.util.List;
public interface ArticleService {
Object saveArticle(Article article);
void deleteArticle(Long id);
void updateArticle(Article article);
Article getArticle(Long id);
List<Article> getAll();
}
修改package controller
package com.dj.controller;
import com.dj.model.Article;
import com.dj.response.AjaxResponse;
import com.dj.sercive.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleController {
@Autowired
ArticleService articleservice;
//获取一篇Article,使用GET方法,根据id查询一篇文章
//@RequestMapping(value = "/articles/{id}",method = RequestMethod.GET)
@GetMapping("/articles/{id}")
public AjaxResponse getArticle(@PathVariable("id") Long id){
System.out.println("查询文章");
//使用lombok提供的builder构建对象
Article a = articleservice.getArticle(id);
System.out.println("测试");
System.out.println(a);
log.info("article:" + a);
return AjaxResponse.success(a);
}
//增加一篇Article ,使用POST方法(RequestBody方式接收参数)
//@RequestMapping(value = "/articles",method = RequestMethod.POST)
@PostMapping("/articles")
public AjaxResponse saveArticle(@RequestBody Article article)
{
//因为使用了lombok的Slf4j注解,这里可以直接使用log变量打印日志
log.info("saveArticle:" + article);
return AjaxResponse.success();
}
//增加一篇Article ,使用POST方法(RequestParam方式接收参数)
/*@PostMapping("/articles")
public AjaxResponse saveArticle(@RequestParam String author,
@RequestParam String title,
@RequestParam String content,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam Date createTime){
log.info("saveArticle:" + createTime);
return AjaxResponse.success();
}*/
//更新一篇Article,使用PUT方法,以id为主键进行更新
//@RequestMapping(value = "/articles",method = RequestMethod.PUT)
@PutMapping("/articles")
public AjaxResponse updateArticle(@RequestBody Article article){
if(article.getId() == null){
//article.id是必传参数,因为通常根据id去修改数据
//TODO 抛出一个自定义的异常
}
log.info("updateArticle:" + article);
return AjaxResponse.success();
}
//删除一篇Article,使用DELETE方法,参数是id
//@RequestMapping(value = "/articles/{id}",method = RequestMethod.DELETE)
@DeleteMapping("/articles/{id}")
public AjaxResponse deleteArticle(@PathVariable("id") Long id){
log.info("deleteArticle:" + id);
return AjaxResponse.success();
}
}
3、添加service层操作JDBC持久层
package service
package com.dj.sercive;
import com.dj.dao.ArticleJDBCDAO;
import com.dj.model.Article;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Slf4j
@Service //服务层依赖注入注解
public class ArticlleJDBCService implements ArticleService {
@Resource
private
ArticleJDBCDAO articleJDBCDAO;
@Transactional
public Object saveArticle(Article article) {
articleJDBCDAO.save(article);
//int a = 2/0; //人为制造一个异常,用于测试事务
return article;
}
public void deleteArticle(Long id){
articleJDBCDAO.deleteById(id);
}
public void updateArticle(Article article){
articleJDBCDAO.updateById(article);
}
public Article getArticle(Long id){
return articleJDBCDAO.findById(id);
}
public List<Article> getAll(){
return articleJDBCDAO.findAll();
}
}
package controller
package com.dj.controller;
import com.dj.model.Article;
import com.dj.response.AjaxResponse;
import com.dj.sercive.ArticlleJDBCService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleController {
@Autowired
ArticlleJDBCService ArticlleJDBCService;
//获取一篇Article,使用GET方法,根据id查询一篇文章
//@RequestMapping(value = "/articles/{id}",method = RequestMethod.GET)
@GetMapping("/articles/{id}")
public AjaxResponse getArticle(@PathVariable("id") Long id){
System.out.println("查询文章");
//使用lombok提供的builder构建对象
Article a = ArticlleJDBCService.getArticle(id);
System.out.println("测试");
System.out.println(a);
log.info("article:" + a);
return AjaxResponse.success(a);
}
//增加一篇Article ,使用POST方法(RequestBody方式接收参数)
//@RequestMapping(value = "/articles",method = RequestMethod.POST)
@PostMapping("/articles")
public AjaxResponse saveArticle(@RequestBody Article article)
{
//因为使用了lombok的Slf4j注解,这里可以直接使用log变量打印日志
log.info("saveArticle:" + article);
return AjaxResponse.success();
}
//增加一篇Article ,使用POST方法(RequestParam方式接收参数)
/*@PostMapping("/articles")
public AjaxResponse saveArticle(@RequestParam String author,
@RequestParam String title,
@RequestParam String content,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam Date createTime){
log.info("saveArticle:" + createTime);
return AjaxResponse.success();
}*/
//更新一篇Article,使用PUT方法,以id为主键进行更新
//@RequestMapping(value = "/articles",method = RequestMethod.PUT)
@PutMapping("/articles")
public AjaxResponse updateArticle(@RequestBody Article article){
if(article.getId() == null){
//article.id是必传参数,因为通常根据id去修改数据
//TODO 抛出一个自定义的异常
}
log.info("updateArticle:" + article);
return AjaxResponse.success();
}
//删除一篇Article,使用DELETE方法,参数是id
//@RequestMapping(value = "/articles/{id}",method = RequestMethod.DELETE)
@DeleteMapping("/articles/{id}")
public AjaxResponse deleteArticle(@PathVariable("id") Long id){
log.info("deleteArticle:" + id);
return AjaxResponse.success();
}
}