项目结构
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">
<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);
}
}