项目结构

pom文件

<?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.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bjsxt</groupId>
<artifactId>spring-bootdata-hotel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-bootdata-hotel</name>
<description>spring-bootdata-hotel</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot 缓存支持启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehcache 坐标 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

俩个配置文件

application.properties

#项目端口配置
server.port=8080
server.address=0.0.0.0
#Mysql数据源配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/sys?characterEncoding=UTF8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root #JPA相关配置
#项目启动生成数据库
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
#josn数据格式
spring.jackson.serialization.indent-output=true #对于ehcache缓存进行相关配置
spring.cache.ehcache.config=classpath:ehcache.xml

ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir"/> <!--defaultCache:echcache 的默认缓存策略 -->
<defaultCache maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache> <!-- 自定义缓存策略 -->
<cache name="room"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>

三个页面,一个异常处理页面,一个添加页面,一个主页面(所有的查询操作,以及删除操作)

templates/error.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>页面崩溃了呢,主人~~~</h1>
<br/>
<h1>主人,页面异常是因为</h1>
<span th:text="${error}"></span>
</body>
</html>

templates/addhotel.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>添加房间</title>
</head>
<body>
<h1 align="center">添加房间</h1>
<hr/>
<form method="post" th:action="@{/addroom}" >
<p>
房型:<select name="type" >
<option value="1" selected="selected">标准间</option>
<option value="2">双人间</option>
<option value="3">豪华间</option>
<option value="4">总统间</option>
<option value="5">大床房</option>
</select>
</p>
<p>
价格:<input type="number" name="price"><font color="red" th:errors="${room.price}"></font>
</p>
<p>
所属酒店:
<select name="hotel" >
<option value="0">=请选择=</option>
<span th:each="h:${hotel}">
<option th:value="${h.hid}"><span th:text="${h.hname}"></span></option>
</span>
</select>
</p>
<p>描述:</p>
<textarea name="info" style="height: 60px"></textarea>
<p>
<input type="submit" value="发布">
</p>
</form>
</body>
</html>

templates/index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>主页面</title>
</head>
<body>
<h1 align="center">酒店管理系统</h1>
<hr/>
<form th:action="@{/findlike}" method="post">
按照酒店名称:<input type="text" name="hname">&nbsp;
<input type="submit" value="查询">
</form> <hr/>
<a th:href="@{/hotel}">添加宾馆</a>
<h1>房型:</h1>
<h1>1:标准间 2:双人间 3:豪华间</h1>
<h1>4:总统间 5:大床房</h1>
<hr/>
<table border="1" align="center" width="50%">
<tr>
<th>ID</th>
<th>酒店名称</th>
<th>房型</th>
<th>价格</th>
<th>地址</th>
<th>电话</th>
<th>操作</th>
</tr>
<tr th:each="room:${room}">
<th th:text="${room.id}"></th>
<th th:text="${room.hotel.hname}">
<th th:text="${room.type}"></th>
<th th:text="${room.price}"></th>
<th th:text="${room.hotel.address}"></th>
<th th:text="${room.hotel.mobile}"></th>
<th><a th:href="@{/deleteById(id=${room.id})}">删除</a></th>
</tr>
</table>
</body>
</html>

业务代码

处理异常

package com.bjsxt.exception;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @Configuration
public class GolableException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mav=new ModelAndView();
if (e instanceof Exception){
mav.setViewName("error");
}
mav.addObject("error",e.toString());
return mav;
}
}

Spring Boot正向工程

俩个实体类,表是一对多的关系

com.bjsxt.pojo.Hotel

package com.bjsxt.pojo;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set; @Entity
@Table(name = "hotel")
@Data
public class Hotel implements Serializable { @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "hid")
private int hid; @Column(name = "hname")
private String hname; @Column(name = "address")
private String address; @Column(name = "mobile")
private String mobile; @OneToMany(mappedBy = "hotel",cascade = CascadeType.PERSIST)
private Set<Room> room=new HashSet<>(); public Hotel() {
} public Hotel(String hname, String address, String mobile, Set<Room> room) {
this.hname = hname;
this.address = address;
this.mobile = mobile;
this.room = room;
}
}

com.bjsxt.pojo.Room

package com.bjsxt.pojo;

import lombok.Data;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable; @Entity
@Table(name = "room")
@Data
public class Room implements Serializable { @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id; @Column(name = "type")
private int type; @Column(name = "price")
@NotNull
private double price; @Column(name = "info")
private String info; @ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "hid")
private Hotel hotel; public Room() {
} public Room(int type, double price, String info, Hotel hotel) {
this.type = type;
this.price = price;
this.info = info;
this.hotel = hotel;
}
}

dao层

com.bjsxt.dao.HotelDao

package com.bjsxt.dao;

import com.bjsxt.pojo.Hotel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface HotelDao extends JpaRepository<Hotel,Integer> , JpaSpecificationExecutor<Hotel> {
}

com.bjsxt.dao.RoomDao

package com.bjsxt.dao;

import com.bjsxt.pojo.Room;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query; import java.util.List; public interface RoomDao extends JpaRepository<Room,Integer>, JpaSpecificationExecutor<Room> { @Query(value = "select h.*,r.* from hotel h,room r where h.hid=r.hid and h.hname like ?",nativeQuery = true)
List<Room> findLikeByhname(String hname); }

service层(接口)

com.bjsxt.service.impl.HotelService

package com.bjsxt.service;

import com.bjsxt.pojo.Hotel;

import java.util.List;

public interface HotelService {
/**
* 查询所有的宾馆信息
* @return
*/
List<Hotel> findall();
}

com.bjsxt.service.RoomService

package com.bjsxt.service;

import com.bjsxt.pojo.Hotel;
import com.bjsxt.pojo.Room;
import org.springframework.data.domain.Page; import java.util.List; public interface RoomService { /**
* 添加房间
* @param room
*/
void addRoom(Room room); /**
* 查询所有房间 * @return
*/
public List<Room> findAll(); /**
* 模糊查询
* @param hname
* @return
*/
public List<Room> findLike(String hname); /**
* 指定id删除
* @param id
*/
void deleteid(int id);
}

实现类

com.bjsxt.service.impl.HotelServiceImpl

package com.bjsxt.service.impl;

import com.bjsxt.dao.HotelDao;
import com.bjsxt.pojo.Hotel;
import com.bjsxt.service.HotelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class HotelServiceImpl implements HotelService { @Autowired
private HotelDao hotelDao; @Override
public List<Hotel> findall() {
List<Hotel> hotels = hotelDao.findAll();
return hotels;
}
}

com.bjsxt.service.impl.RoomServiceImpl

package com.bjsxt.service.impl;

import com.bjsxt.dao.HotelDao;
import com.bjsxt.dao.RoomDao;
import com.bjsxt.pojo.Hotel;
import com.bjsxt.pojo.Room;
import com.bjsxt.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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.List; /**
* 处理放假的操作
*/
@Service
public class RoomServiceImpl implements RoomService {
@Autowired
private RoomDao roomDao; /**
* 添加房间
* @param room
*/
@CacheEvict(value = "room",allEntries = true)//清空缓存
@Override
public void addRoom(Room room) {
roomDao.save(room);
} /**
* 查询所有房间
* @return
*/
@Cacheable(value = "room")//配置缓存
@Override
public List<Room> findAll() {
List<Room> roomList = roomDao.findAll();
return roomList;
} @Override
public List<Room> findLike(String hname) {
List<Room> roomList = roomDao.findLikeByhname(hname);
return roomList;
} @Override
@CacheEvict(value = "room",allEntries = true)//清空缓存
public void deleteid(int id) {
roomDao.deleteById(id);
}
}

控制层

com.bjsxt.controller.HotelController

package com.bjsxt.controller;

import com.bjsxt.pojo.Hotel;
import com.bjsxt.pojo.Room;
import com.bjsxt.service.HotelService;
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.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller
public class HotelController { /**
* 跳转页面
*/
@RequestMapping("/go")
private String goIndex(){
return "index";
} @Autowired
private HotelService hs; /**
* 查询所有的酒店
*/
@RequestMapping("/hotel")
private String findAll(Model model,Room room){
List<Hotel> hotel = hs.findall();
model.addAttribute("hotel",hotel);
return "addhotel";
} }

com.bjsxt.controller.RoomController

package com.bjsxt.controller;

import com.bjsxt.pojo.Hotel;
import com.bjsxt.pojo.Room;
import com.bjsxt.service.RoomService;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import javax.validation.Valid;
import java.util.List; @Controller
public class RoomController { @Autowired
private RoomService rs; /**
* 新增
* @param room
* @return
*/
@RequestMapping("/addroom")
private String addRoom(@Valid Room room, BindingResult result){
if(result.hasErrors()){
return "addhotel";
}else {
rs.addRoom(room);
return "redirect:/findall";
}
} /**
* 查询所有
* @param model
* @return
*/
@RequestMapping("/findall")
public String findAll(Model model){
List<Room> rooms = rs.findAll();
model.addAttribute("room",rooms);
return "index";
} /**
* 模糊查询
* @param hname * @param model
* @return
*/
@RequestMapping("/findlike")
public String findLike(String hname,Model model){
List<Room> rooms ;
if (hname==""){
rooms = rs.findAll();
}else {
hname="%"+hname+"%";
rooms = rs.findLike(hname);
}
model.addAttribute("room",rooms);
return "index";
} @RequestMapping("/deleteById")
public String deleteById(int id){
rs.deleteid(id);
return "redirect:/findall";
} }

启动类

com.bjsxt.SpringBootdataHotelApplication

package com.bjsxt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication
@EnableCaching
@EnableSwagger2
public class SpringBootdataHotelApplication { public static void main(String[] args) {
SpringApplication.run(SpringBootdataHotelApplication.class, args);
} }

Spring Boot结和Spring Data(Ehcache缓存,Thymeleaf页面,自定义异常页面跳转,Swagger2)的更多相关文章

  1. Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 页面

    Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 页面 在<Spring Boot(一):快速开始>中介绍了如何使用 Spring Boot 构建一个工程,并且提 ...

  2. Spring Boot 2.x基础教程:使用 Thymeleaf开发Web页面

    通过本系列教程的前几章内容(API开发.数据访问).我们已经具备完成一个涵盖数据存储.提供HTTP接口的完整后端服务了.依托这些技能,我们已经可以配合前端开发人员,一起来完成一些前后端分离的Web项目 ...

  3. 【spring boot 系列】spring data jpa 全面解析(实践 + 源码分析)

    前言 本文将从示例.原理.应用3个方面介绍spring data jpa. 以下分析基于spring boot 2.0 + spring 5.0.4版本源码 概述 JPA是什么? JPA (Java ...

  4. spring boot(五):spring data jpa的使用

    在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...

  5. Spring Boot 中集成 Redis 作为数据缓存

    只添加注解:@Cacheable,不配置key时,redis 中默认存的 key 是:users::SimpleKey [](1.redis-cli 中,通过命令:keys * 查看:2.key:缓存 ...

  6. Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)

    号外:为读者持续整理了几份最新教程,覆盖了 Spring Boot.Spring Cloud.微服务架构等PDF.获取方式:关注右侧公众号"泥瓦匠BYSocket",来领取吧! 摘 ...

  7. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件

    精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件 内容简介:本文介绍 Spring Boot 的配置文件和配置管理,以及介绍了三种读取配置文 ...

  8. 使用 Spring Boot 快速构建 Spring 框架应用--转

    原文地址:https://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/ Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2 ...

  9. 使用 Spring Boot 快速构建 Spring 框架应用,PropertyPlaceholderConfigurer

    Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2002 年发布以来,Spring 框架已经成为企业应用开发领域非常流行的基础框架.有大量的企业应用基于 Spring 框架来开发.S ...

随机推荐

  1. mpvue+小程序云开发,纯前端实现婚礼邀请函

    请勿使用本文章及源码作为商业用途! 前言 当初做这个小程序是为了婚礼前的需要,结婚之后,希望这个小程序能够留存下来,特地花了一些空闲时间将小程序转化成为“相册类小程序” 体验码 准备工作 mpvue框 ...

  2. Java升级那么快,多个版本如何灵活切换和管理?

    前言 近两年,Java 版本升级频繁,感觉刚刚掌握 Java8,写本文时,已听到 java14 的消息,无论是尝鲜新特性(Java12 中 Collectors.teeing 超强功能使用),还是由于 ...

  3. 列转行pivot函数在SQL Sever里面和Oracle里面的用法区别

    首先pivot是一个列转行的函数,反向用是unpivot(行转列). 在SQL sever中可以这么写 SELECT * FROM [TABLE] /*数据源*/ AS A PIVOT ( MAX/* ...

  4. Mybatis批量事务处理

    /** * 批量提交数据 * @param sqlSessionFactory * @param mybatisSQLId SQL语句在Mapper XML文件中的ID * @param commit ...

  5. Java基础:数值类型转换、强制类型转换

    数值类型之间的转换 数值类型之间的转换,在小数值往大数值转换时,不会发生精度的损失.在小数值往大数值转换时有可能发生精度的损失. 比如byte最大值也只有127,如果一个大于127的int类型数据往b ...

  6. [error] hadoop:ls: `.': No such file or directory

    问题: 解决: https://stackoverflow.com/questions/28241251/hadoop-fs-ls-results-in-no-such-file-or-directo ...

  7. 使用 MUI 自制 弹出层

    使用 MUI 自制 弹出层 <div class="zp-mask" style="display: none; width: 100%;height: 100%; ...

  8. Python之selenium自动化PART1

    本文适合有经验的测试童鞋 一.Selenium自动化测试环境搭建 1.cmd --- pip install selenium==2.53.0 (如果selenium后面不跟==,表示默认安装最新版本 ...

  9. Windows使用Java执行cmd代码

    话不多说,直入正题 今天给大家分享下,怎么在Windows上使用Java执行Cmd代码! 首先默认大家都熟悉cmd代码,以及cmd的命令行操作. 直接在main方法中写这一行(需要抛出异常),可以直接 ...

  10. Python 编程语言要掌握的技能之一:使用数字与字符串的技巧

    最佳实践 1. 少写数字字面量 “数字字面量(integer literal)” 是指那些直接出现在代码里的数字.它们分布在代码里的各个角落,比如代码 del users[0] 里的 0 就是一个数字 ...