项目结构

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. css3 input placeholder颜色修改方法

    css3 input placeholder颜色修改方法<pre> input::-webkit-input-placeholder { /* placeholder颜色 */ color ...

  2. MyBatis --- 映射关系【一对一、一对多、多对多】,懒加载机制

    映射(多.一)对一的关联关系 1)若只想得到关联对象的id属性,不用关联数据表 2)若希望得到关联对象的其他属性,要关联其数据表 举例: 员工与部门的映射关系为:多对一 1.创建表 员工表 确定其外键 ...

  3. pxe批量部署脚本

    #!/bin/bash #检查环境 setenforce 0 sed -i 's/=enforce/=disabled/g' /etc/selinux/config systemctl restart ...

  4. Servlet中response的相关案例(重定型,验证码,ServletContext文件下载)

    重定向 首先设置状态码,设置响应头 //访问Demo1自动跳转至Demo2 //设置状态码 response.setStatus(302); //设置响应头 response.setHeader(&q ...

  5. C++中对C的扩展学习新增语法——函数重载

    函数重载 1.函数重载语法 1.同一个作用域(全局作用域.命名空间作用域.类作用域) 2.参数个数不同 3.参数类型不同 4.参数顺序不同 代码实现: 当函数名字一样的时候,通过参数类型.参数个数.参 ...

  6. [Odoo12基础教程]之win10中odoo12环境搭建

    所需材料 1.python3.7 2.pycharm社区版及以上 3.postgresSQL10 下载链接:https://www.enterprisedb.com/thank-you-downloa ...

  7. python--BMI

    #bmi height,weight = eval(input("请输入身高(m) 体重(kg),以逗号隔开\n")) bmi = weight/pow(weight,2) pri ...

  8. 一图读懂Spring Core,Spring MVC, Spring Boot,Spring Cloud 的关系与区别

    Spring框架自诞生到现在,历经多次革新,形成了多种不同的产品,分别应用于不同的项目中,为了帮助自己理解这些产品之间的关系,特此整理此图,以便自己记忆和复习.

  9. Java基础IO类之字节输入输出流

    一.IO流概述 1.IO流:输入输出流(Input/Output) 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象,即数据在设备间的传输流, 流的本质是数据传输,根据数据传输特性将 ...

  10. 在centos7上进行hadoop-3.1.2的伪分布搭建

    第一步:配置网络(静态IP) vi /etc/sysconfig/network-scripts/ifcfg-ens33(网卡名称可能不同) 1. 修改: 将该配置文件中的ONBOOT=no修改为ye ...