Springboot集成Mybatis和Thymeleaf开发电影Demo

介绍

本文将使用Springboot、Mybatis、Thymeleaf、Mysql开发一个电影Demo,包括对电影信息的增删改查操作。

1、POM引入依赖

主要有starter-web、thymeleaf、mybatis、druid、lombok组件

<?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.13.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</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</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>
		<!-- 引入thymeleaf依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<!-- 引入mybatis依赖 -->
		<dependency> <groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
		<!-- 引入mysql依赖 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- 引入druid连接池依赖 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>
		<!-- 引入lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.20</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2、配置文件编写

需要配置mysql连接、指定druid数据源和指定sql映射文件位置

# 配置数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

# 指定数据源类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 开启sql日志输出(两种方式都可以)
logging.level.com.example.demo.mapper=debug
#mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

# 指定sql映射文件位置
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

3、创建电影表

CREATE TABLE `t_movie_info` (
  `id` bigint(10) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(32) DEFAULT NULL COMMENT '名称',
  `role` varchar(32) DEFAULT NULL COMMENT '主演',
  `area` varchar(16) DEFAULT NULL COMMENT '地区(大陆、香港、美国)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COMMENT='电影信息表';

4、entity实体

与数据层对应,集成了lombok插件,无需编写构造方法和get、set方法

package com.example.demo.entity;


import lombok.Data;

/**
 *  电影实体类
 */
@Data
public class MovieInfo {

    private Long id;    //主键
    private String name;    //名称
    private String role;    //主演
    private String area;    //地区(大陆、香港、美国)

}

5、model实体

与view层对应
1、新增功能对应请求实体类;

package com.example.demo.model;

import lombok.Data;

/**
 * 新增请求实体
 */
@Data
public class AddMovieReq {

    private String name;    //名称
    private String role;    //主演
    private String area;    //地区(大陆、香港、美国)

}

2、编辑功能对应请求实体类;

package com.example.demo.model;

import lombok.Data;

/**
 * 编辑请求实体
 */
@Data
public class EditMovieReq {

    private Long id;
    private String name;    //名称
    private String role;    //主演
    private String area;    //地区(大陆、香港、美国)

}

6、controller层

package com.example.demo.controller;

import com.example.demo.entity.MovieInfo;
import com.example.demo.model.AddMovieReq;
import com.example.demo.model.EditMovieReq;
import com.example.demo.service.IMovieInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/movie")
public class MovieInfoController {

    @Autowired
    private IMovieInfoService movieInfoService;

    /**
     * 页面跳转
     * @param page
     * @return
     */
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page){
        return "/movie/"+page;
    }

    /**
     * 新增
     * @param req
     * @return
     */
    @RequestMapping("/addSubmit")
    public String addMovie(AddMovieReq req){
        this.movieInfoService.addMovie(req);
        return "redirect:/movie/findMovieInfoList";
    }

    /**
     * 列表查询
     * @param model
     * @return
     */
    @RequestMapping("/findMovieInfoList")
    public String findMovieInfoList(Model model){
        List<MovieInfo> list = this.movieInfoService.findMovieInfoList();
        model.addAttribute("list", list);
        return "/movie/list";
    }

    /**
     * 根据ID查询
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findMovieInfoById")
    public String findMovieInfoById(Long id,Model model){
        MovieInfo movieInfo = this.movieInfoService.selectMovieInfoById(id);
        model.addAttribute("movieInfo", movieInfo);
        return "/movie/edit";
    }

    /**
     * 编辑
     * @param req
     * @return
     */
    @RequestMapping("/editSubmit")
    public String editMovieInfo(EditMovieReq req){
        this.movieInfoService.updateMovieInfo(req);
        return "redirect:/movie/findMovieInfoList";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delMovieInfoById")
    public String delMovieInfoById(Long id){
        this.movieInfoService.deleteMovieInfoById(id);
        return "redirect:/movie/findMovieInfoList";
    }
}

7、service层

1、接口层

package com.example.demo.service;

import com.example.demo.entity.MovieInfo;
import com.example.demo.model.AddMovieReq;
import com.example.demo.model.EditMovieReq;

import java.util.List;

public interface IMovieInfoService {

    /**
     *  新增电影
     * @param req
     */
    void addMovie(AddMovieReq req);

    /**
     * 列表查询
     * @return
     */
    List<MovieInfo> findMovieInfoList();

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    MovieInfo selectMovieInfoById(Long id);

    /**
     * 修改
     */
    void updateMovieInfo(EditMovieReq req);

    /**
     * 删除
     * @param id
     */
    void deleteMovieInfoById(Long id);
}

2、实现层

package com.example.demo.service.impl;

import com.example.demo.entity.MovieInfo;
import com.example.demo.mapper.MovieInfoMapper;
import com.example.demo.model.AddMovieReq;
import com.example.demo.model.EditMovieReq;
import com.example.demo.service.IMovieInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class MovieInfoServiceImpl implements IMovieInfoService {

    @Autowired
    private MovieInfoMapper movieInfoMapper;

    @Override
    public void addMovie(AddMovieReq req) {
        MovieInfo info = new MovieInfo();
        BeanUtils.copyProperties(req,info);
        this.movieInfoMapper.insertMovieInfo(info);
    }

    @Override
    public List<MovieInfo> findMovieInfoList() {
        return this.movieInfoMapper.selectMovieInfoList();
    }

    @Override
    public MovieInfo selectMovieInfoById(Long id) {
        return this.movieInfoMapper.selectMovieInfoById(id);
    }

    @Override
    public void updateMovieInfo(EditMovieReq req) {
        MovieInfo info = new MovieInfo();
        BeanUtils.copyProperties(req,info);
        this.movieInfoMapper.updateMovieInfo(info);
    }

    @Override
    public void deleteMovieInfoById(Long id) {
        this.movieInfoMapper.deleteMovieInfoById(id);
    }
}

8、mapper层

package com.example.demo.mapper;

import com.example.demo.entity.MovieInfo;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MovieInfoMapper {

    void insertMovieInfo(MovieInfo info);

    List<MovieInfo> selectMovieInfoList();

    MovieInfo selectMovieInfoById(Long id);

    void updateMovieInfo(MovieInfo info);

    void deleteMovieInfoById(Long id);

}

9、sql编写

在resources目录下创建mapper文件夹,再新建MovieInfoMapper.xml

<?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.example.demo.mapper.MovieInfoMapper">

    <insert id="insertMovieInfo" parameterType="com.example.demo.entity.MovieInfo">
        insert into t_movie_info(name, role, area) values(#{name}, #{role}, #{area})
    </insert>

    <select id="selectMovieInfoList" resultType="com.example.demo.entity.MovieInfo">
        select id , name, role, area from t_movie_info order by id
    </select>

    <select id="selectMovieInfoById" resultType="com.example.demo.entity.MovieInfo">
        select id , name, role, area from t_movie_info where id = #{value}
    </select>

    <update id="updateMovieInfo" parameterType="com.example.demo.entity.MovieInfo">
        update t_movie_info set name=#{name}, role=#{role}, area=#{area} where id=#{id}
    </update>

    <delete id="deleteMovieInfoById">
        delete from t_movie_info where id = #{value}
    </delete>
</mapper>

10、html模板编写

在resources目录下创建templates文件夹,再创建movie目录,然后编写对应thymeleaf模板
1、列表查询:list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>列表查询</title>
</head>
<body>
    <a th:href="@{/movie/add}">新增</a>
    <table border="1" style="width:360px;">
        <tr>
            <th>ID</th>
            <th>电影名称</th>
            <th>主演</th>
            <th>地区</th>
            <th>操作</th>
        </tr>
        <tr th:each="movie : ${list}">
            <td th:text="${movie.id}"></td>
            <td th:text="${movie.name}"></td>
            <td th:text="${movie.role}"></td>
            <td th:text="${movie.area}"></td>
            <td>
                <a th:href="@{/movie/findMovieInfoById(id=${movie.id})}">编辑</a>
                <a th:href="@{/movie/delMovieInfoById(id=${movie.id})}">删除</a>
            </td>
        </tr>
    </table>
</body>
</html>

2、新增:add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>新增电影</title>
</head>
<body>
    <form th:action="@{/movie/addSubmit}" method="post">
        名称:<input type="text" name="name"/><br/>
        主演:<input type="text" name="role"/><br/>
        地区:<input type="text" name="area"/><br/>
        <input type="submit" value="新增"/><br/>
    </form>
</body>
</html>

3、编辑:edit.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>编辑电影</title>
</head>
<body>
<form th:action="@{/movie/editSubmit}" method="post">
    <input type="hidden" name="id" th:field="${movieInfo.id}"/>
    名称:<input type="text" name="name" th:field="${movieInfo.name}"/><br/>
    主演:<input type="text" name="role" th:field="${movieInfo.role}"/><br/>
    地区:<input type="text" name="area" th:field="${movieInfo.area}"/><br/>
    <input type="submit" value="修改"/><br/>
</form>
</body>
</html>

11、效果查看

启动应用,访问http://localhost:8080/movie/findMovieInfoList地址,效果如下
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值