一、JPA
1、创建项目
2、在pom.xml文件中导入Thymeleaf的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xjj</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<!-- Thymeleaf的依赖版本号 -->
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<!-- JPA依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- JDBC依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!-- Mysql部分的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Thymeleaf的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 测试时使用的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- web组件依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、配置连接数据库信息和JPA,这里使用yaml文件写法
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
4、创建映射数据表的实体类
package com.xjj.springboot.entity;
import javax.persistence.*;
/**
* @Entity说明是实体类
* @Table指定映射哪一张表,默认为开头首字母小写
* @Id注明是主键
* @GenerationValue(strategy = GenerationType.IDENTIFY)规定了主键策略
* @Column注明了对应的列属性,名字默认都是驼峰规则,length是varchar的长度
* @Author xjj
*/
@Entity
@Table
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer bookId;
@Column(length = 50)
private String bookName;
@Column
private Double bookPrice;
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Double getBookPrice() {
return bookPrice;
}
public void setBookPrice(Double bookPrice) {
this.bookPrice = bookPrice;
}
@Override
public String toString() {
return "Book{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", bookPrice=" + bookPrice +
'}';
}
}
5、创建接口继承JpaRepository
package com.xjj.springboot.dao;
import com.xjj.springboot.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 接口类继承了JpaRepository之后就可以继承基础的增删改查和分页的功能
* 其中的JpaRepository的第一个泛型对应的是哪一个实体类,第二个是主键的类型
* @author xjj
*/
public interface BookRepository extends JpaRepository<Book,Integer> {
}
6、创建service层和controller,并实现查询book表中所有信息
package com.xjj.springboot.service;
import com.xjj.springboot.entity.Book;
import java.util.List;
/**
* @author xjj
*/
public interface BookService {
/**
* 用来查询book表
* @return
*/
List<Book> findAll();
}
package com.xjj.springboot.service.impl;
import com.xjj.springboot.dao.BookRepository;
import com.xjj.springboot.entity.Book;
import com.xjj.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author xjj
* 其中的bookRepository本身自带了基本增删改查方法以及分页
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookRepository bookRepository;
@Override
public List<Book> findAll(){
return bookRepository.findAll();
}
}
package com.xjj.springboot.controller;
import com.xjj.springboot.entity.Book;
import com.xjj.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* @author xjj
*/
@Controller
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/findAll")
@ResponseBody
public List<Book> findAll(){
return bookService.findAll();
}
}
7、启动项目
二、Mybatis—接着上面的Jpa进行操作,创建一个能够给book表按id查询的方法
1、创建Mapper的接口文件
package com.xjj.springboot.dao;
import com.xjj.springboot.entity.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
/**
* @Author xjj
*/
@Mapper
@Component
public interface BookMapper {
/**
* 按照书的id来查询数据
* @param bookId
* @return
*/
Book queryBookByBookId(@Param("bookId") Integer bookId);
}
2、创建Mapper的映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xjj.springboot.dao.BookMapper">
<select id="queryBookByBookId" resultType="com.xjj.springboot.entity.Book">
select * from book
</select>
</mapper>
3、service层和conotroler层
package com.xjj.springboot.service;
import com.xjj.springboot.entity.Book;
import java.util.List;
/**
* @author xjj
*/
public interface BookService {
/**
* 用来查询book表
* @return
*/
List<Book> findAll();
/**
* 用序号来查询book表
* @param bookId
* @return
*/
Book queryBookByBookId(Integer bookId);
}
package com.xjj.springboot.service.impl;
import com.xjj.springboot.dao.BookMapper;
import com.xjj.springboot.dao.BookRepository;
import com.xjj.springboot.entity.Book;
import com.xjj.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author xjj
* 其中的bookRepository本身自带了基本增删改查方法以及分页
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookRepository bookRepository;
@Autowired
private BookMapper bookMapper;
@Override
public List<Book> findAll(){
return bookRepository.findAll();
}
@Override
public Book queryBookByBookId(Integer bookId) {
return bookMapper.queryBookByBookId(bookId);
}
}
package com.xjj.springboot.controller;
import com.xjj.springboot.dao.BookMapper;
import com.xjj.springboot.entity.Book;
import com.xjj.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* @author xjj
*/
@Controller
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping("/findAll")
@ResponseBody
public List<Book> findAll(){
return bookService.findAll();
}
@RequestMapping("/queryBookByBookId/{bookId}")
@ResponseBody
public Book queryBookByBookId(@PathVariable Integer bookId){
return bookService.queryBookByBookId(bookId);
}
}
4、修改yaml文件配置
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
# 引入Druid的数据源以及配置
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdel: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
connectionProperties: druid:stat.mergeSql=true;druid.stat.slowSqlMills=500
jpa:
hibernate:
ddl-auto: update
show-sql: true
mybatis:
configuration:
#开启驼峰命名,因为自动创建的表都是驼峰命名的
map-underscore-to-camel-case: true
mapper-locations: classpath:mybatis/mapper/BookMapper.xml
logging:
level:
#让mapper里面执行的sql语句被打印出来,而Jpa的使用底层hibernate的,会自动打印,所以这样子不论是使用jpa还是mybatis都能够看到sql语句了
com.xjj.springboot.dao: debug
6、启动项目
三、Druid—接着上面的文件进行操作
1、引入Druid和log4j的依赖
<!-- Druid的依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!-- log4j的依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、给Druid注入属性,修改yaml文件
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
# 引入Druid的数据源以及配置
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdel: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
connectionProperties: druid:stat.mergeSql=true;druid.stat.slowSqlMills=500
jpa:
hibernate:
ddl-auto: update
show-sql: true
mybatis:
config-location: classpath:mybatis/config/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/BookMapper.xml
3、创建Druid的配置文件
package com.xjj.springboot.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @Author xjj
*/
@Configuration
public class DruidConfig {
/**
* 将yaml文件中spring.datasource下的属性注入进来
* @return
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
/**
* 配置Druid的监控
* 其中的loginUsername和loginPassword是登陆时的用户和密码
* @return
*/
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams=new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","admin");
initParams.put("allow","localhost");
bean.setInitParameters(initParams);
return bean;
}
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean=new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> map=new HashMap<>();
map.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(map);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
4、启动项目