MyBatis 是一款优秀的持久层框架,Spring Boot官方虽然没有对MyBatis进行整合,但是MyBatis团队自行适配了对应的启动器,进一步简化了使用MyBatis进行数据的操作
# 创建数据库 CREATE DATABASE springbootdata; # 选择使用数据库 USE springbootdata; # 创建表t_article并插入相关数据 DROP TABLE IF EXISTS t_article; CREATE TABLE t_article ( id int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id', title varchar(200) DEFAULT NULL COMMENT '文章标题', content longtext COMMENT '文章内容', PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO t_article VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...'); INSERT INTO t_article VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...'); # 创建表t_comment并插入相关数据 DROP TABLE IF EXISTS t_comment; CREATE TABLE t_comment ( id int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id', content longtext COMMENT '评论内容', author varchar(200) DEFAULT NULL COMMENT '评论作者', a_id int(20) DEFAULT NULL COMMENT '关联的文章id', PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; INSERT INTO t_comment VALUES ('1', '很全、很详细', 'lucy', '1'); INSERT INTO t_comment VALUES ('2', '赞一个', 'tom', '1'); INSERT INTO t_comment VALUES ('3', '很详细', 'eric', '1'); INSERT INTO t_comment VALUES ('4', '很好,非常详细', '张三', '1'); INSERT INTO t_comment VALUES ('5', '很不错', '李四', '2');
package com.rf.entity; import lombok.Data; @Data public class Comment { private Integer id; private String content; private String author; private Integer aId; } package com.rf.entity; import lombok.Data; @Data public class Article { private Integer id; private String title; private String content; }
#MySQL数据库连接配置 spring: datasource: driver-class-name: com.mysql.jdbc.Driver username: root url: jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC&characterEncoding=UTF-8 password: 123456
package com.rf.mapper; import com.rf.entity.Comment; import org.apache.ibatis.annotations.Select; @Component public interface CommentMapper { /** * 通过ID查询Comment信息 * @param id * @return */ @Select("select * from t_comment where id=#{id}") public Comment findById(Integer id); }
package com.rf; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan("com.rf.mapper") @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
package com.rf.demo; import com.rf.entity.Comment; import com.rf.mapper.CommentMapper; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest class DemoApplicationTests { @Test void contextLoads() { } @Autowired private CommentMapper commentMapper; @Test public void commentTest(){ Comment comment = commentMapper.findById(1); System.out.println("comment = " + comment); } }
# 开启驼峰命名匹配映射 mybatis: configuration: map-underscore-to-camel-case: true
package com.rf.entity; import java.io.Serializable; import lombok.Data; /** * t_article * @author */ @Data public class TArticle implements Serializable { /** * 文章id */ private Integer id; /** * 文章标题 */ private String title; /** * 文章内容 */ private String content; private static final long serialVersionUID = 1L; @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } TArticle other = (TArticle) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle())) && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", title=").append(title); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } package com.rf.mapper; import com.rf.entity.TArticle; @Component public interface TArticleMapper { int deleteByPrimaryKey(Integer id); int insert(TArticle record); int insertSelective(TArticle record); TArticle selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(TArticle record); int updateByPrimaryKey(TArticle record); }
<?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.rf.mapper.TArticleMapper"> <resultMap id="BaseResultMap" type="com.rf.entity.TArticle"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="title" jdbcType="VARCHAR" property="title" /> <result column="content" jdbcType="VARCHAR" property="content" /> </resultMap> <sql id="Base_Column_List"> id, title, content </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_article where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from t_article where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.rf.entity.TArticle" useGeneratedKeys="true"> insert into t_article (title, content) values (#{title,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.rf.entity.TArticle" useGeneratedKeys="true"> insert into t_article <trim prefix="(" suffix=")" suffixOverrides=","> <if test="title != null"> title, </if> <if test="content != null"> content, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="title != null"> #{title,jdbcType=VARCHAR}, </if> <if test="content != null"> #{content,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.rf.entity.TArticle"> update t_article <set> <if test="title != null"> title = #{title,jdbcType=VARCHAR}, </if> <if test="content != null"> content = #{content,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.rf.entity.TArticle"> update t_article set title = #{title,jdbcType=VARCHAR}, content = #{content,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> </mapper>
# 开启驼峰命名匹配映射 mybatis: configuration: map-underscore-to-camel-case: true #配置MyBatis的xml配置文件路径 mapper-locations: classpath:mapper/*.xml #配置XML映射文件中指定的实体类别名路径 type-aliases-package: com.rf.entity
@Autowired private TArticleMapper articleMapper; @Test public void articleTest(){ TArticle article = articleMapper.selectByPrimaryKey(1); System.out.println("article = " + article); }
<!-- redis依赖包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
#redis配置 #Redis服务器地址 spring.redis.host=192.168.80.128 #Redis服务器连接端口 spring.redis.port=6379 #Redis数据库索引(默认为0) spring.redis.database=0 #连接池最大连接数(使用负值表示没有限制) spring.redis.jedis.pool.max-active=50 #连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.jedis.pool.max-wait=3000 #连接池中的最大空闲连接 spring.redis.jedis.pool.max-idle=20 #连接池中的最小空闲连接 spring.redis.jedis.pool.min-idle=2 #连接超时时间(毫秒) spring.redis.timeout=5000
package com.rf.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import javax.annotation.security.DenyAll; import java.util.concurrent.TimeUnit; @Component public class RedisUtils { @Autowired private RedisTemplate redisTemplate; /** * 读取缓存 * * @param key * @return */ public Object get(final String key) { return redisTemplate.opsForValue().get(key); } /** * 写入缓存 */ public boolean set( String key, Object value) { boolean result = false; try { redisTemplate.opsForValue().set(key, value,1, TimeUnit.DAYS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 更新缓存 */ public boolean getAndSet(final String key, String value) { boolean result = false; try { redisTemplate.opsForValue().getAndSet(key, value); result = true; } catch (Exception e) {e.printStackTrace(); } return result; } /** * 删除缓存 */ public boolean delete(final String key) { boolean result = false; try { redisTemplate.delete(key); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } }
package com.rf.demo; import com.rf.config.RedisUtils; import com.rf.entity.Comment; import com.rf.entity.TArticle; import com.rf.mapper.CommentMapper; import com.rf.mapper.TArticleMapper; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest class DemoApplicationTests { @Autowired private TArticleMapper articleMapper; @Autowired private RedisUtils redisUtils; @Test public void setRedisData() { redisUtils.set("article_1",articleMapper.selectByPrimaryKey(1)); System.out.println("success"); } @Test public void getRedisData() { TArticle article = (TArticle) redisUtils.get("article_1"); System.out.println(article); } }
Thymeleaf是一种现代的基于服务器端的Java模板引擎技术,也是一个优秀的面向Java的XML、XHTML、HTML5页面模板,它具有丰富的标签语言、函数和表达式,在使用Spring Boot框架进行页面
设计时,一般会选择Thymeleaf模板
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" media="all" href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" /> <title>Title</title> </head> <body> <p th:text="${hello}">欢迎进入Thymeleaf的学习</p> </body> </html>
在HTML页面上使用Thymeleaf标签,Thymeleaf 标签能够动态地替换掉静态内容,使页面动态展示。上述代码中,“xmlns:th="http://www.thymeleaf.org"“ 用于引入Thymeleaf模板引擎标签,使用关键字“th”标注标签是Thymeleaf模板提供的标签,其中,“th:href”用于引入外联样式文件,“th:text”用于动态显示标签文本内容。除此之外,Thymeleaf模板提供了很多标签
th:标签 | 说明 |
th:insert | 布局标签,替换内容到引入的文件 |
th:replace | 页面片段包含(类似JSP中的include标签) |
th:each | 元素遍历(类似JSP中的c:forEach标签) |
th:if | 条件判断,如果为真 |
th:unless | 条件判断,如果为假 |
th:switch | 条件判断,进行选择性匹配 |
th:case | 条件判断,进行选择性匹配 |
th:value | 属性值修改,指定标签属性值 |
th:href | 用于设定链接地址 |
th:src | 用于设定链接地址 |
th:text | 用于指定标签显示的文本内容 |
<p th:text="${title}">这是标题</p> <!-- 如果当前程序没有启动或者当前上下文中不存在title变量,该片段会显示标签默认值“这是标题”; 如果当前上下文中存在title变量并且程序已经启动,当前P标签中的默认文本内容将会被title变量的值所替换,从而达到模板引擎页面数据动态替换的效果 -->
Thymeleaf为变量所在域提供了一些内置对象 # ctx:上下文对象 # vars:上下文变量 # locale:上下文区域设置 # request:(仅限Web Context)HttpServletRequest对象 # response:(仅限Web Context)HttpServletResponse对象 # session:(仅限Web Context)HttpSession对象 # servletContext:(仅限Web Context)ServletContext对象
The locale country is: <span th:text="${#locale.country}">US</span> <!-- 使用th:text="${#locale.country}"动态获取当前用户所在国家信息,其中标签内默认内容为US(美国), 程序启动后通过浏览器查看当前页面时,Thymeleaf会通过浏览器语言设置来识别当前用户所在国家信息,从而实现动态替换-->
<div th:object="${book}"> <p>titile: <span th:text="*{title}">标题</span>.</p> </div> <!-- *{title} 选择变量表达式获取当前指定对象book的title属性值 -->
<a th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a> <a th:href="@{/order/details(orderId=${o.id},pid=${p.id})}">view</a> <!-- 链接表达式@{...}分别编写了绝对链接地址和相对链接地址。 在有参表达式中,需要按照@{路径(参数名称=参数值,参数名称=参数值...)}的形式编写,\同时该参数的值可以使用变量表达式来传递动态参数值-->
<div th:insert="~{thymeleafDemo::title}"></div> <!-- 使用th:insert属性将title片段模板引用到该标签中。 thymeleafDemo为模板名称,Thymeleaf会自动查找“/resources/templates/”目录下的thymeleafDemo模板,title为片段名称-->
<!-- 引入Thymeleaf依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
在全局配置文件中配置Thymeleaf模板的一些参数。一般Web项目都会使用下列配置
spring.thymeleaf.cache = true #启用模板缓存 spring.thymeleaf.encoding = UTF-8 #模板编码 spring.thymeleaf.mode = HTML5 #应用于模板的模板模式 spring.thymeleaf.prefix = classpath:/templates/ #指定模板页面存放路径 spring.thymeleaf.suffix = .html #指定模板页面名称的后缀
上述配置中,spring.thymeleaf.cache表示是否开启Thymeleaf模板缓存,默认为true,在开发过程中通常会关闭缓存,保证项目调试过程中数据能够及时响应;
spring.thymeleaf.prefix指定了Thymeleaf模板页面的存放路径,默认为classpath:/templates/;
spring.thymeleaf.suffix指定了Thymeleaf模板页面的名称后缀,默认为.html
#启用模板缓存 spring.thymeleaf.cache = true
package com.rf.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Calendar; @Controller public class LoginController { @RequestMapping("/toLoginPage") public String toLoginPage(Model model){ model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR)); return "login"; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1,shrinkto-fit=no"> <title>用户登录界面</title> <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet"> <link th:href="@{/login/css/signin.css}" rel="stylesheet"> </head> <body class="text-center"> <!-- 用户登录form表单 --> <form class="form-signin"> <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72"> <h1 class="h3 mb-3 font-weight-normal">请登录</h1> <input type="text" class="form-control" th:placeholder="用户名" required="" autofocus=""> <input type="password" class="form-control" th:placeholder="密码" required=""> <div class="checkbox mb-3"> <label> <input type="checkbox" value="remember-me"> 记住我 </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit" >登录</button> <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2019</span>-<span th:text="${currentYear}+1">2020</span></p> </form> </body> </html>
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.3</version> </dependency>
package com.rf.entity; import java.io.Serializable; import lombok.Data; /** * users * @author */ @Data public class Users implements Serializable { private Integer uid; private String username; private String password; private String phone; private String createtime; private static final long serialVersionUID = 1L; @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } Users other = (Users) that; return (this.getUid() == null ? other.getUid() == null : this.getUid().equals(other.getUid())) && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername())) && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword())) && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone())) && (this.getCreatetime() == null ? other.getCreatetime() == null : this.getCreatetime().equals(other.getCreatetime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUid() == null) ? 0 : getUid().hashCode()); result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode()); result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode()); result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode()); result = prime * result + ((getCreatetime() == null) ? 0 : getCreatetime().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", uid=").append(uid); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", phone=").append(phone); sb.append(", createtime=").append(createtime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
package com.rf.mapper; import com.rf.entity.Users; import java.util.List; public interface UsersDao { /** * 按ID删除 * @param uid * @return */ int deleteByPrimaryKey(Integer uid); /** * 新增 * @param record * @return */ int insert(Users record); /** * 判断是否为空的新增 * @param record * @return */ int insertSelective(Users record); /** * g根据ID查询 * @param uid * @return */ Users selectByPrimaryKey(Integer uid); /** * 判断是否为空的修改 * @param record * @return */ int updateByPrimaryKeySelective(Users record); /** * 修改 * @param record * @return */ int updateByPrimaryKey(Users record); /** * 查询所有 * @return */ List<Users> queryAll(); }
<?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.rf.mapper.UsersDao"> <resultMap id="BaseResultMap" type="com.rf.entity.Users"> <id column="uid" jdbcType="INTEGER" property="uid" /> <result column="username" jdbcType="VARCHAR" property="username" /> <result column="PASSWORD" jdbcType="VARCHAR" property="password" /> <result column="phone" jdbcType="VARCHAR" property="phone" /> <result column="createtime" jdbcType="VARCHAR" property="createtime" /> </resultMap> <sql id="Base_Column_List"> `uid`, username, `PASSWORD`, phone, createtime </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from users where `uid` = #{uid,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from users where `uid` = #{uid,jdbcType=INTEGER} </delete> <insert id="insert" keyColumn="uid" keyProperty="uid" parameterType="com.rf.entity.Users" useGeneratedKeys="true"> insert into users (username, `PASSWORD`, phone, createtime) values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{createtime,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" keyColumn="uid" keyProperty="uid" parameterType="com.rf.entity.Users" useGeneratedKeys="true"> insert into users <trim prefix="(" suffix=")" suffixOverrides=","> <if test="username != null"> username, </if> <if test="password != null"> `PASSWORD`, </if> <if test="phone != null"> phone, </if> <if test="createtime != null"> createtime, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="username != null"> #{username,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> <if test="phone != null"> #{phone,jdbcType=VARCHAR}, </if> <if test="createtime != null"> #{createtime,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.rf.entity.Users"> update users <set> <if test="username != null"> username = #{username,jdbcType=VARCHAR}, </if> <if test="password != null"> `PASSWORD` = #{password,jdbcType=VARCHAR}, </if> <if test="phone != null"> phone = #{phone,jdbcType=VARCHAR}, </if> <if test="createtime != null"> createtime = #{createtime,jdbcType=VARCHAR}, </if> </set> where `uid` = #{uid,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.rf.entity.Users"> update users set username = #{username,jdbcType=VARCHAR}, `PASSWORD` = #{password,jdbcType=VARCHAR}, phone = #{phone,jdbcType=VARCHAR}, createtime = #{createtime,jdbcType=VARCHAR} where `uid` = #{uid,jdbcType=INTEGER} </update> <select id="queryAll" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from users </select> </mapper>
package com.rf.service; import com.rf.entity.Users; import java.util.List; /** * (Users)表服务接口 * * @author rf * @since 2021-08-16 21:00:31 */ public interface UsersService { /** * 按ID删除 * @param uid * @return */ void deleteByPrimaryKey(Integer uid); /** * 新增 * @param record * @return */ void insert(Users record); /** * 判断是否为空的新增 * @param record * @return */ void insertSelective(Users record); /** * g根据ID查询 * @param uid * @return */ Users selectByPrimaryKey(Integer uid); /** * 判断是否为空的修改 * @param record * @return */ void updateByPrimaryKeySelective(Users record); /** * 修改 * @param record * @return */ void updateByPrimaryKey(Users record); /** * 查询所有 * @return */ List<Users> queryAll(); }
package com.rf.service.impl; import com.rf.entity.Users; import com.rf.mapper.UsersDao; import com.rf.service.UsersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * (Users)表服务实现类 * * @author rf * @since 2021-08-16 21:00:31 */ @Service("usersService") public class UsersServiceImpl implements UsersService { @Autowired private UsersDao usersDao; @Override public void deleteByPrimaryKey(Integer uid) { usersDao.deleteByPrimaryKey(uid); } @Override public void insert(Users record) { usersDao.insert(record); } @Override public void insertSelective(Users record) { usersDao.insertSelective(record); } @Override public Users selectByPrimaryKey(Integer uid) { return usersDao.selectByPrimaryKey(uid); } @Override public void updateByPrimaryKeySelective(Users record) { usersDao.updateByPrimaryKeySelective(record); } @Override public void updateByPrimaryKey(Users record) { usersDao.updateByPrimaryKey(record); } @Override public List<Users> queryAll() { return usersDao.queryAll(); } }
package com.rf.controller; import com.rf.entity.Users; import com.rf.service.UsersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * (Users)表控制层 * * @author rf * @since 2021-08-16 21:00:32 */ @RestController public class UsersController { /** * 服务对象 */ @Autowired private UsersService usersService; @GetMapping("/user") public List<Users> queryAll(){ return usersService.queryAll(); } @GetMapping("/user/{uid}") public Users selectByPrimaryKey(@PathVariable("uid") Integer uid){ return usersService.selectByPrimaryKey(uid); } @PostMapping("/insert") public String insert(Users users){ usersService.insertSelective(users); return "success"; } @PutMapping("/update") public String update(Users users){ usersService.updateByPrimaryKeySelective(users); return "success"; } @DeleteMapping("/delete/{uid}") public String delete(@PathVariable("uid") Integer uid){ usersService.deleteByPrimaryKey(uid); return "success"; } }
##服务器配置 server: port: 8090 servlet: context-path: / ##数据源配置 spring: datasource: url: jdbc:mysql://localhost:3306/smd?serverTimezone=UTC&characterEncoding=UTF-8 username: root password: 123456 name: druid type: com.alibaba.druid.pool.DruidDataSource #整合mybatis mybatis: #声明Mybatis映射文件所在的位置 mapper-locations: classpath:mapper/*.xml
package com.rf; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.rf.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
<build> <plugins> <!-- 打jar包时如果不配置该插件,打出来的jar包没有清单文件 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
package com.rf.entity; import java.io.Serializable; import lombok.Data; /** * users * @author */ @Data public class Users implements Serializable { private Integer uid; private String username; private String password; private String phone; private String createtime; private static final long serialVersionUID = 1L; @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } Users other = (Users) that; return (this.getUid() == null ? other.getUid() == null : this.getUid().equals(other.getUid())) && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername())) && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword())) && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone())) && (this.getCreatetime() == null ? other.getCreatetime() == null : this.getCreatetime().equals(other.getCreatetime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUid() == null) ? 0 : getUid().hashCode()); result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode()); result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode()); result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode()); result = prime * result + ((getCreatetime() == null) ? 0 : getCreatetime().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", uid=").append(uid); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", phone=").append(phone); sb.append(", createtime=").append(createtime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }