前言
最近学完ssm框架了,闲来无事想学学spring boot。spring的入门程序"HelloWorld"就不写了,前两天写的时候没有把过程记录下来,我那时候入门是直接写了一个增删改查的页面,至于前端页面我用的是Thymeleaf模板引擎,相关资料我参考的是这里,这是大神自己写的springBoot系列教程demo,可以把项目clone下来慢慢学。
我这里就直接从spring boot访问数据库的几种方式开始做学习笔记了,如果有人看并且可以从中学到东西,那就太好了(虽然并不会有人看到...)
方式一:spring boot+jdbcTemplate
1.导入需要的依赖包
4.0.0
com.baidu
ch7-thymeleaf
0.0.1-SNAPSHOT
jar
ch7-thymeleaf
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.4.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-jdbc
com.h2database
h2
runtime
mysql
mysql-connector-java
org.springframework.boot
spring-boot-maven-plugin
2.实体类
package com.baidu.ch7thymeleaf.pojo;
import java.io.Serializable;
/**
* @author huangdongjiang
* @date 2018/8/27 16:07
*/
public class Book implements Serializable {
private static final long serialVersionUID = 3537921742065870581L;
/**
* 编号
*/
private Long id;
/**
* 书名
*/
private String name;
/**
* 作者
*/
private String writer;
/**
* 简介
*/
private String introduction;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
}
3.根据上面的的实体类创建好对应的数据表,数据库我用的是Mysql
4.配置application.properties文件
## 是否开启缓存
spring.thymeleaf.cache=false
## 渲染之前检查模板是否存在
spring.thymeleaf.check-template=true
##检查模板位置是否存在。
spring.thymeleaf.check-template-location=true
##为Web框架启用Thymeleaf视图解析。
spring.thymeleaf.enabled=true
##模板文件编码。
spring.thymeleaf.encoding=UTF-8
#模板
spring.thymeleaf.mode=HTML5
#前缀
spring.thymeleaf.prefix=classpath:/templates/
#响应数据格式
spring.thymeleaf.servlet.content-type=text/html
#后缀
spring.thymeleaf.suffix=.html
#mysql相关配置
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
5.DAO层接口IBookDao
package com.baidu.ch7thymeleaf.dao;
import com.baidu.ch7thymeleaf.pojo.Book;
import java.util.List;
/**
* @author huangdongjiang
* @date 2018/8/27 21:53
*/
public interface IBookDao {
/**
* 查所有书
* @return 所有的书本
*/
List findAll();
/**
* 添加一本书
* @return 返回添加的书本
*/
Book insertByBook(Book book);
/**
* 更新书本信息
* @param book 要更新的书
* @return 跟新的书
*/
Book update(Book book);
/**
* 根据id删除书本
* @param id 要删除的书本的id
* @return 删除的书本
*/
void delete(Long id);
/**
* 根据id查找书本
* @param id 要查找书本的id
* @return 返回要查找的书本
*/
Book findById(Long id);
}
实现类:BookDaoImpl
package com.baidu.ch7thymeleaf.dao.impl;
import com.baidu.ch7thymeleaf.dao.IBookDao;
import com.baidu.ch7thymeleaf.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* @author huangdongjiang
* @date 2018/8/27 22:04
*/
@Repository
public class BookDaoImpl implements IBookDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List findAll() {
String sql = "SELECT id,name,writer,introduction FROM t_book";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper(Book.class));
}
@Override
public Book insertByBook(Book book) {
String sql = "INSERT INTO t_book(name,writer,introduction) VALUES(?,?,?)";
jdbcTemplate.update(sql, book.getName(),book.getWriter(), book.getIntroduction());
return book;
}
@Override
public Book update(Book book) {
String sql = "UPDATE t_book SET name=?,writer=?,introduction=? WHERE id=?";
int i = jdbcTemplate.update(sql, book.getName(), book.getWriter(),
book.getIntroduction(), book.getId());
System.out.println("更新书本的id是:" + book.getId());
return book;
}
@Override
public void delete(Long id) {
String sql = "DELETE FROM t_book WHERE id=?";
jdbcTemplate.update(sql, id);
}
@Override
public Book findById(Long id) {
String sql = "SELECT id,name,writer,introduction FROM t_book WHERE id=?";
return (Book) jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper(Book.class));
}
}
6.业务层接口和实现类
IBookService
package com.baidu.ch7thymeleaf.service;
import com.baidu.ch7thymeleaf.pojo.Book;
import java.util.List;
/**
* @author huangdongjiang
* @date 2018/8/27 16:10
*/
public interface IBookService {
/**
* 获取所有 Book
*/
List findAll();
/**
* 新增 Book
*
* @param book {@link Book}
*/
Book insertByBook(Book book);
/**
* 更新 Book
*
* @param book {@link Book}
*/
Book update(Book book);
/**
* 删除 Book
*
* @param id 编号
*/
void delete(Long id);
/**
* 获取 Book
*
* @param id 编号
*/
Book findById(Long id);
}
BookServiceImpl
package com.baidu.ch7thymeleaf.service.impl;
import com.baidu.ch7thymeleaf.dao.IBookDao;
import com.baidu.ch7thymeleaf.pojo.Book;
import com.baidu.ch7thymeleaf.service.IBookService;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author huangdongjiang
* @date 2018/8/27 16:11
*/
@Service
public class BookServiceImpl implements IBookService {
@Autowired
private IBookDao bookDao;
@Override
public List findAll() {
return bookDao.findAll();
}
@Override
public Book insertByBook(Book book) {
bookDao.insertByBook(book);
return book;
}
@Override
public Book update(Book book) {
bookDao.update(book);
return book;
}
@Override
public void delete(Long id) {
bookDao.delete(id);
}
@Override
public Book findById(Long id) {
return bookDao.findById(id);
}
}
7.控制层
package com.baidu.ch7thymeleaf.controller;
import com.baidu.ch7thymeleaf.pojo.Book;
import com.baidu.ch7thymeleaf.service.IBookService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
/**
* @author huangdongjiang
* @date 2018/8/27 16:23
*/
@Controller//@RESTController
@RequestMapping("/book")
public class BookController {
private static final Log log = LogFactory.getLog(BookController.class);
private static final String BOOK_FORM_PATH_NAME = "bookForm";
private static final String BOOK_LIST_PATH_NAME = "bookList";
private static final String REDIRECT_TO_BOOK_URL = "redirect:/book";
@Autowired
private IBookService bookService;
/**
* 获取数的列表
* 处理"/book"的get请求,获取所有书的列表
* @return 书的列表
*/
@RequestMapping(method = RequestMethod.GET)
public String getBookList(ModelMap modelMap) {
log.info("展示书单方法运行...");
modelMap.addAttribute("bookList", bookService.findAll());
return BOOK_LIST_PATH_NAME;
}
/**
* 获取创建book表单
* @return book表单
*/
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String createBookForm(ModelMap modelMap) {
log.info("跳转到列表...");
modelMap.addAttribute("book", new Book());
modelMap.addAttribute("action", "create");
return BOOK_FORM_PATH_NAME;
}
/**
* 创建book
* 处理"/book/create"的post请求,用来新建book信息
* 通过@ModelAttribute绑定表单实体参数,也通过@RequestParam传递参数
*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String postBook(@ModelAttribute Book book) {
log.info("添加书本到列表中...");
bookService.insertByBook(book);
return REDIRECT_TO_BOOK_URL;
}
/**
* 获取更新Book表单
* 处理"/book/update/{id}"的get请求,通过URL中的id来获取Book信息
* URL中的id,通过@PathVariable
*/
@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
public String updateBook(@PathVariable Long id, ModelMap modelmap) {
log.info("更新方法运行...");
log.info(bookService.findById(id));
modelmap.addAttribute("book", bookService.findById(id));
modelmap.addAttribute("action", "update");
return BOOK_FORM_PATH_NAME;
}
/**
* 更新book
* 处理"/update"的PUT请求,用来更新Book的信息
*/
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String putBook(@ModelAttribute Book book) {
log.info("更新书本到列表中...");
log.info(book);
bookService.update(book);
return REDIRECT_TO_BOOK_URL;
}
/**
*删除book
* 处理"/book/{id}"的get请求,用来删除book信息
*/
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String delete(@PathVariable Long id) {
log.info("删除书本...");
bookService.delete(id);
return REDIRECT_TO_BOOK_URL;
}
}
8.三层架构到这里就写完了,这里就应该结合Thymeleaf加入前端页面了,另外要注意spring boot工程的目录结构的最佳实践,也就是大家公认的目录结构应该这样建,之所以有这个东西是因为spring boot有一个启动类,要扫描加载的注解很多,如果目录结构的层级关系建的不好的话有可能有些类不能被扫描到,从而导致项目启动失败。具体怎么建请参考这篇文章
bookList.html
书籍列表
bookForm.html
书籍管理
《Spring Boot 2.x 核心技术实战 - 上 基础篇》第 4 章《模板引擎》Demo
方式二:spring Data JPA
用完JDBCTemplate后再用JPA操作数据库简直太方便了,JPA好像跟Hibernate语法比较相近?我之前没学过Hibernate,所以学起来相对慢一丢丢,但是问题不大。这里不再贴详细代码了,制铁关键步骤的代码,需要完整代码请去上面给出的github地址中自取。
1.导入依赖包
org.springframework.boot
spring-boot-starter-data-jpa
com.h2database
h2
runtime
2.建一个实体类,这个实体类很重要,因为自动生成的数据表是根据这个实体类来生成的。建好这个类表就会自动生成。感觉这是Hibernate强大的地方,当然,这样也是有弊端的,就是不能很灵活地处理sql语句。
这里要特别关注这些注解。
@Id是声明表的主键
@GeneraterValue 指定主键的生成策略
@Column 声明该属性与数据库字段的映射关系。
/**
* id
*/
@Id
@GeneratedValue
private Long id;
/**
* 书名
*/
@Column(nullable = false)
private String name;
/**
* 作者
*/
@Column(nullable = false)
private String writer;
/**
* 简介
*/
@Column(nullable = false)
private String introduction;
/**
* 空参构造
*/
public JPABook() {
}
/**
* 有参构造
*/
public JPABook(String name, String writer, String introduction) {
this.name = name;
this.writer = writer;
this.introduction = introduction;
}
//省略了setter和getter方法
3.这里才是spring JPA神奇地方,只需要写一个dao接口继承JpaRepository
package com.baidu.ch08spring_data_jpa.pojo.repository;
import com.baidu.ch08spring_data_jpa.pojo.JPABook;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author huangdongjiang
* @date 2018/8/28 16:25
*/
public interface JPABookRepository extends JpaRepository {
}
4.业务层
@Service
public class JPABookServiceImpl implements IJPABookService {
@Autowired
private JPABookRepository jpaBookRepository;
@Override
public List findAll() {
return jpaBookRepository.findAll();
}
@Override
public JPABook insertByBook(JPABook jpaBook) {
return jpaBookRepository.save(jpaBook);
}
@Override
public JPABook update(JPABook jpaBook) {
return jpaBookRepository.save(jpaBook);
}
@Override
public void delete(Long id) {
jpaBookRepository.deleteById(id);
}
@Override
public JPABook findById(Long id) {
return jpaBookRepository.getOne(id);
}
}
方式三:spring boot + mybatis
1.导入mybatis的相关依赖包
mysql
mysql-connector-java
2.配置application.properties文件
## Mybatis 配置
mybatis.typeAliasesPackage=com.baidu.ch8mybatis.pojo
mybatis.mapperLocations=classpath:mapper/*.xml
前者用来设置别名,后者指定mapper.xml文件的位置。
另外除了以上配置还有下面这些怕配置可以选择来用:
#mybatis.type-handlers-package=type handlers处理器包路径
#mybatis.check-config-location=检查mybatis配置是否存在,一般命名为mybatis配置是否存在,一般命名为mybatis-config.xml
3.BookMapper.xml
id, name, writer, introduction
insert into
t_book(name,writer,introduction)
values (#{name},#{writer},#{introduction})
update
t_book
set name=#{name},writer=#{writer},introduction=#{introduction}
delete from
t_book
where id=#{id}
4.在DAO接口上加上注解,不加的话会报注入不了Bean的错误
@Mapper
public interface IBookMapper {
....
}
5.在启动类上加上扫描DAO的注解@MapperScan("DAO的完整包名")
@SpringBootApplication
@MapperScan("com.baidu.ch8mybatis.dao.IBookMapper")
public class Ch8MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Ch8MybatisApplication.class, args);
}
}
参考文献
JPA
【参考一】https://blog.csdn.net/dandandeshangni/article/details/79497804
mybatis
【参考二】http://www.spring4all.com/article/145