使用jpa,mapper接口继承JpaRepository就行了
项目结构
效果图
yml文件
server:
port: 8081
spring:
jpa:
show-sql: true
database: mysql
hibernate:
ddl-auto: update
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl #驼峰命名
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/spring?useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
#模板引擎
thymeleaf:
#禁用缓存 默认false
cache: false
mode: HTML5
prefix: classpath:/templates/
suffix: .html
#指定编码
encoding: utf-8
pom.xml
<?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.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wang</groupId>
<artifactId>springBoot-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springBoot-jpa</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
实体类
package com.wang.pojo;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "goods")
@Data
public class Goods {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "price")
private Integer price;
@Column(name = "count")
private Integer count;
@ManyToOne
@JoinColumn(name = "type")
private Type types;
}
package com.wang.pojo;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "type")
@Data
public class Type {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "typename")
private String typename;
}
工具类
首页访问
package com.wang.util;
import com.github.pagehelper.PageInterceptor;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import java.io.IOException;
import java.util.Properties;
@Configuration
public class MybatisConfig {
// @Bean
// public PageInterceptor pageInterceptor() {
// PageInterceptor pageInterceptor = new PageInterceptor();
// // 详见 com.github.pagehelper.page.PageParams
// Properties p = new Properties();
p.setProperty("offsetAsPageNum", "false");
p.setProperty("rowBoundsWithCount", "false");
p.setProperty("reasonable", "false");
// // 设置数据库方言 , 也可以不设置,会动态获取
// p.setProperty("helperDialect", "mysql");
// pageInterceptor.setProperties(p);
// return pageInterceptor;
// }
@EventListener({ApplicationReadyEvent.class})
void applicationReadyEvent() {
// System.out.println("应用已经准备就绪 ... 启动浏览器");
// 这里需要注url:端口号+测试类方法名
String url = "http://localhost:8081/findAll";
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
继承JpaRepository就不用自己sql了,针对简单的增删改查和分页都进行了封装
service
package com.wang.service;
import com.wang.pojo.Goods;
import java.util.List;
import java.util.Optional;
public interface GoodsService {
List<Goods> findAll(String name);
List<Goods> findAllByName(Goods goods, Integer pageNum, Integer pageSize);
void add(Goods goods);
void delGoods(Integer id);
Goods findByIds(Integer id);
void updGoods(Goods goods);
}
package com.wang.service;
import com.wang.pojo.Type;
import java.util.List;
public interface TypeService {
List<Type> findAll();
}
Impl
package com.wang.service.Impl;
import com.wang.mapper.GoodsRepository;
import com.wang.pojo.Goods;
import com.wang.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class GoodsServiceImpl implements GoodsService {
@Autowired
private GoodsRepository customerRepository;
@Override
public List<Goods> findAll(String name) {
List<Goods> goodsList = null;
Specification<Goods> specification = new Specification<Goods>() {
@Override
public Predicate toPredicate(Root<Goods> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if (name != null && !"".equals(name)) {
predicates.add(criteriaBuilder.like(root.get("name"),"%"+name+"%"));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
goodsList=this.customerRepository.findAll(specification);
return goodsList;
}
@Override
public List<Goods> findAllByName(Goods goods, Integer pageNum,Integer pageSize) {
List<Goods> goodsList = null;
Specification<Goods> specification = new Specification<Goods>() {
@Override
public Predicate toPredicate(Root<Goods> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if (goods.getName() != null && !"".equals(goods.getName())) {
predicates.add(criteriaBuilder.like(root.get("name"),"%"+goods.getName()+"%"));
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
PageRequest pageable = PageRequest.of(pageNum - 1, pageSize);
goodsList=this.customerRepository.findAll(specification, pageable).getContent();
return goodsList;
}
@Override
public void add(Goods goods) {
customerRepository.save(goods);
}
@Override
public void delGoods(Integer id) {
customerRepository.deleteById(id);
}
@Override
public Goods findByIds(Integer id) {
return customerRepository.getReferenceById(id);
}
@Override
public void updGoods(Goods goods) {
customerRepository.save(goods);
}
}
package com.wang.service.Impl;
import com.wang.mapper.TypeRepository;
import com.wang.pojo.Type;
import com.wang.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TypeServiceImpl implements TypeService {
@Autowired
private TypeRepository typeRepository;
@Override
public List<Type> findAll() {
return typeRepository.findAll();
}
}
controller层
package com.wang.controller;
import com.github.pagehelper.PageInfo;
import com.wang.pojo.Goods;
import com.wang.pojo.Type;
import com.wang.service.Impl.GoodsServiceImpl;
import com.wang.service.Impl.TypeServiceImpl;
import com.wang.util.ResponseResult;
import javafx.print.PageLayout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;
@Controller
public class GoodsController {
@Autowired
private GoodsServiceImpl goodsService;
@Autowired
private TypeServiceImpl typeService;
@RequestMapping("/findAll")
public String findAll(Model model, Goods goods,@RequestParam(value = "pageNum",required = false,defaultValue = "1")Integer pageNum,@RequestParam(value = "pageSize",required = false,defaultValue = "1")Integer pageSize,String name){
List<Goods> all = goodsService.findAll(name);
int size = all.size();
if (pageNum==0){
pageNum=1;
}
int pageCount=size%pageSize==0?size/pageSize:size/pageSize+1;
if (pageNum>pageCount){
pageNum=pageCount;
}
List<Goods> goodsList= goodsService.findAllByName(goods,pageNum,pageSize);
model.addAttribute("goodsList",goodsList);
model.addAttribute("pageCount",pageCount);
model.addAttribute("all",all);
model.addAttribute("name",name);
model.addAttribute("pageNum",pageNum);
return "allList";
}
@RequestMapping("/add")
public String add(Model model){
List<Type> type = typeService.findAll();
model.addAttribute("type",type);
return "add";
}
@RequestMapping("/addG")
public String addG(Goods goods, String name, HttpSession session){
if (goods.getName().equals(name)){
session.setAttribute("msg","该商品已存在");
}else{
goodsService.add(goods);
}
return "redirect:/findAll";
}
@RequestMapping("/dele")
public String del(Integer id,Integer types,HttpSession session,Goods goods){
if (goods.getTypes().getId().equals(types)){
session.setAttribute("msg","该商品类型存在无法删除");
}else{
goodsService.delGoods(id);
}
return "redirect:/findAll";
}
@RequestMapping("/upd")
public String upd(Integer id,Model model){
List<Type> type = typeService.findAll();
model.addAttribute("type",type);
Goods byIds = goodsService.findByIds(id);
model.addAttribute("all",byIds);
return "upd";
}
@RequestMapping("/upda")
public String upda(Goods goods){
goodsService.updGoods(goods);
return "redirect:/findAll";
}
}
前端页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<body>
<div style="width: 680px;height:100%; margin:0px auto">
<p>
<form th:action="@{/findAll}" method="post">
食品名称:<input name="name" type="text" th:value="${name}"/>
<input type="submit" value="查询">
</form>
</p>
<a type="button" th:href="@{/add}" style="text-decoration: none">添加</a>
<span th:text="${session.msg}" style="color: aqua" id="mu"></span>
<table border="2px">
<thead>
<tr>
<th>食品名称</th>
<th>价格</th>
<th>库存</th>
<th>食品类型</th>
<th>相关操作</th>
</tr>
</thead>
<tbody>
<tr th:each="list:${goodsList}">
<td th:text="${list.name}"></td>
<td th:text="${list.price}"></td>
<td th:text="${list.count}"></td>
<td th:text="${list.types.typename}"></td>
<td>
<a th:href="@{/dele/(id=${list.id},types=${list.types.id})}">删除</a>
<a th:href="@{/upd/(id=${list.id})}">编辑</a>
</td>
</tr>
<tr align="center">
<td colspan="4">
<a th:if="${pageNum}==1">
<label style="color: gray">首页</label>
<label style="color: gray">上一页</label>
</a>
<a th:if="${pageNum}>1" th:href="@{/findAll(pageNum=1,name=${name})}">首页</a>
<a th:if="${pageNum}>1" th:href="@{/findAll(pageNum=${pageNum}-1,name=${name})}">上一页</a>
<a th:if="${pageNum}<${pageCount}" th:href="@{/findAll(pageNum=${pageNum}+1,name=${name})}">下一页</a>
<a th:if="${pageNum}<${pageCount}" th:href="@{/findAll(pageNum=${pageCount},name=${name})}">尾页</a>
<a th:if="${pageNum}==${pageCount}">
<label style="color: gray">下一页</label>
<label style="color: gray">尾页</label>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
$(function (){
var hides= function (){
// $( "#mu" ).hide();
$("#mu").html("");
}
window.setTimeout(hides,1000);
})
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:method="post" th:action="@{/addG}">
<div style="width: 450px;height:100%; margin:0px auto">
<h1 style="color: aquamarine">新增</h1>
<table border="2px">
<tr>
<td>零食名称</td>
<td><input type="text" th:name="name" required></td>
</tr>
<tr>
<td>价格</td>
<td><input type="number" th:name="price" required></td>
</tr>
<tr>
<td>库存</td>
<td><input type="text" th:name="count" required></td>
</tr>
<tr>
<td>零食类型</td>
<td>
<select th:name="types">
<option th:value="${t.id}" th:each="t:${type}" th:text="${t.typename}"></option>
</select>
</td>
</tr>
<tr>
<td>相关操作</td>
<td><input th:type="submit" th:value="新增"/><a th:href="@{/findAll}" style="text-decoration: none"> 返回</a></td>
</tr>
</table>
</div>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/upda}" th:method="post">
<div style="width: 450px;height:100%; margin:0px auto">
<h1 style="color:red">修改页面</h1>
<table border="2px">
<input type="hidden" th:name="id" th:value="${all.id}">
<tr>
<td>零食名称</td>
<td><input type="text" th:name="name" th:value="${all.name}" required ></td>
</tr>
<tr>
<td>价格</td>
<td><input type="text" th:name="price" th:value="${all.price}" required ></td>
</tr>
<tr>
<td>库存</td>
<td><input type="text" th:name="count" th:value="${all.count}" required ></td>
</tr>
<tr>
<td>食品类型</td>
<td>
<select th:name="types">
<option th:value="${t.id}" th:each="t:${type}" th:text="${t.typename}"></option>
</select>
</td>
</tr>
<td>操作</td>
<td><input th:type="submit" th:value="修改"><a th:href="@{/findAll}" style="text-decoration: none"> 返回</a></td>
</tr>
</table>
</div>
</form>
</body>
</html>
对于jpa它对简单的增删改查都进行了封装,对于复杂的sql还是要自己写,jpa大大简化了代码的书写量