SpringBoot之整合Mybatis范例
依赖包:
<?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 http://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.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.springboot</groupId>
<artifactId>demo</artifactId>
<version>1.0.1-SNAPSHOT</version>
<name>boot_demo</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
<dom4j.version>1.6.1</dom4j.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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency> <!-- 引入freemarker包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency> <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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-autoconfigure</artifactId>
<version>1.3.2</version>
</dependency> <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency> <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency> <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency> <!-- spring事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency> <dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build> </project>
配置文件application.properties:
#数据库配置
spring.datasource.url=jdbc:mysql://20.1.1.11:16306/gxrdb?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassNamee=com.mysql.jdbc.Driver #mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=org.springboot.model
model:
package org.springboot.model; /**
* @Auther:GongXingRui
* @Date:2018/12/24
* @Description:
**/
public class Student {
private String id;
private String name;
private String gender;
private int age;
private String telephone; public Student() { } public Student(String id, String name, String gender) {
this.id = id;
this.name = name;
this.gender = gender;
} public Student(String id, String name, String gender, int age, String telephone) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.telephone = telephone;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getGender() {
return gender;
} public void setGender(String gender) {
this.gender = gender;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getTelephone() {
return telephone;
} public void setTelephone(String telephone) {
this.telephone = telephone;
} @Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", telephone='" + telephone + '\'' +
'}';
}
}
mapper接口
package org.springboot.mapper; import org.apache.ibatis.annotations.Mapper;
import org.springboot.model.Student; import java.util.List; /**
* @Auther:GongXingRui
* @Date:2018/12/26
* @Description:
**/
@Mapper
public interface StudentMapper {
Student getStudentById(String id); List<Student> getAllStudent(); void addStudent(Student student); void deleteStudentById(String id); }
mapper 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="org.springboot.mapper.StudentMapper"> <!--<resultMap id="BaseResultMap" type="org.springboot.model.Student" >-->
<!--<id column="id" property="id" jdbcType="VARCHAR" />-->
<!--<result column="name" property="name" jdbcType="VARCHAR" />-->
<!--<result column="age" property="age" jdbcType="INTEGER" />-->
<!--<result column="gender" property="gender" jdbcType="VARCHAR"/>-->
<!--<result column="telephone" property="telephone" jdbcType="VARCHAR"/>-->
<!--</resultMap>--> <!--<select id="getStudentById" parameterType="java.lang.String" resultMap="BaseResultMap">-->
<!--select * from t_student where id = #{id}-->
<!--</select>--> <select id="getStudentById" parameterType="java.lang.String" resultType="org.springboot.model.Student">
select * from t_student where id = #{id}
</select> <insert id="addStudent" parameterType="org.springboot.model.Student">
insert into t_student (id, name, gender, age,telephone) values (#{id} ,#{name}, #{gender},#{age,jdbcType=INTEGER},#{telephone})
</insert> <!--字段可能为空的情况,需要指定数据类型-->
<!--<insert id="addStudent" parameterType="org.springboot.model.Student">-->
<!--insert into t_student (id, name, gender, age,telephone) values (#{id} ,#{name}, #{gender},#{age,jdbcType=INTEGER},#{telephone,jdbcType=CHAR})-->
<!--</insert>--> <delete id="deleteStudentById" parameterType="java.lang.String">
DELETE FROM t_student WHERE id = #{id}
</delete> <select id="getAllStudent" resultType="org.springboot.model.Student">
select * from t_student
</select> </mapper>
service:
package org.springboot.service; import org.springboot.mapper.StudentMapper;
import org.springboot.model.Student;
import org.springboot.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* @Auther:GongXingRui
* @Date:2018/12/24
* @Description:
**/
@Service
public class StudentService { @Autowired
private StudentMapper studentMapper; public Student getStudentDemo() {
Student student = new Student();
student.setId("1");
student.setName("小明");
student.setGender("男");
student.setAge(18);
student.setTelephone("137456678");
return student;
} public Student getStudentById(String id) {
return studentMapper.getStudentById(id);
} public List<Student> getAllStudent() {
return studentMapper.getAllStudent();
} public void addStudent(Student student) {
studentMapper.addStudent(student);
} public void deleteStudentById(String id) {
studentMapper.deleteStudentById(id);
} public boolean loginStudentcheck(String name, String id) {
Student student = studentMapper.getStudentById(id);
if (ObjectUtils.isNull(student)) {
return false;
} else if (student.getName().equals(name)) {
return true;
}
return false;
} }
controller
package org.springboot.controller; import com.sun.jmx.snmp.SnmpUnknownModelLcdException;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springboot.mapper.StudentMapper;
import org.springboot.model.Student;
import org.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import java.util.List; /**
* @Auther:GongXingRui
* @Date:2018/12/24
* @Description:
**/
@Controller
public class StudentController {
private Logger logger = LogManager.getLogger(StudentController.class);
@Autowired
StudentService studentService; @RequestMapping("/showStudentInfo")
public String showStudentInfo(Model model) {
logger.info("查询学生信息");
Student student = studentService.getStudentDemo();
logger.info(student);
model.addAttribute("student", student);
return "studentInfo.html";
} // 使用freemaker模板
@RequestMapping("/showStudentInfo2")
public String showStudentInfo2(Model model) {
logger.info("查询学生信息");
Student student = studentService.getStudentDemo();
logger.info(student);
model.addAttribute("student", student);
return "studentInfo2";
} @RequestMapping("/studentIndex")
public String studentIndex() {
logger.info("学生信息首页");
return "student/studentIndex";
} @RequestMapping("/getStudentById")
@ResponseBody
public String getStudentById(String id) {
logger.info("通过ID查询学生信息");
Student student = studentService.getStudentById(id);
if (null == student) {
String tip = "没有找到对应数据 -> id:" + id;
logger.info(tip);
return tip;
}
logger.info(student);
return student.toString();
} @RequestMapping("/getStudentById2")
public String getStudentById2(String id, Model model) {
logger.info("通过ID查询学生信息2");
Student student = studentService.getStudentById(id);
if (null == student) {
String tip = "没有找到对应数据 -> id:" + id;
logger.info(tip);
return null;
}
model.addAttribute("student", student);
logger.info(student);
return "student/studentInfo";
} @RequestMapping("/getAllStudent")
public ModelAndView getAllStudent(ModelAndView mv) {
logger.info("查询所有学生信息");
List<Student> students = studentService.getAllStudent();
mv.addObject("studentList", students);
mv.setViewName("student/allStudentInfo");
logger.info(students);
return mv;
} @RequestMapping("/addStudent")
@ResponseBody
public String addStudent(Student student) {
logger.info("新增学生信息");
try {
studentService.addStudent(student);
} catch (Exception e) {
e.printStackTrace();
return "新增学生信息发生异常!<br>" + e.toString();
}
logger.info(student.toString());
return "新增学生信息成功!<br>" + student.toString();
} @RequestMapping("/deleteStudentById")
@ResponseBody
public String deleteStudentById(String id) {
logger.info("通过ID删除学生信息");
try {
studentService.deleteStudentById(id);
} catch (Exception e) {
e.printStackTrace();
return "通过ID删除学生信息发生异常!<br>" + e.toString();
}
logger.info("通过ID删除学生信息成功! -> id:" + id);
return "通过ID删除学生信息成功! -> id:" + id;
} @RequestMapping("/loginStudentcheck")
public String loginStudentcheck(String name, String id, Model model) {
logger.info("正在登陆学生系统...");
logger.info("用户名:" + name + ", 密码:" + id);
boolean flag = studentService.loginStudentcheck(name, id);
if (flag) {
logger.info("登陆成功");
return "student/studentIndex";
}
model.addAttribute("info", "登陆失败!用户名或密码错误!");
logger.info("登陆失败!用户名或密码错误!");
return "student/error";
} @RequestMapping("/loginStudent")
public String loginStudent() {
logger.info("请求登陆学生信息页面");
return "student/loginStudent";
} }
程序入口:DemoApplication.java
package org.springboot; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("org.springboot.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }
工程目录:

SpringBoot之整合Mybatis范例的更多相关文章
- SpringBoot之整合Mybatis(增,改,删)
一,在上一篇文章SpringBoot之整合Mybatis中,我们使用spring boot整合了Mybatis,并演示了查询操作.接下来我们将完善这个示例,增加增,删,改的功能. 二,改动代码 1.修 ...
- SpringBoot系列-整合Mybatis(注解方式)
目录 一.常用注解说明 二.实战 三.测试 四.注意事项 上一篇文章<SpringBoot系列-整合Mybatis(XML配置方式)>介绍了XML配置方式整合的过程,本文介绍下Spring ...
- springboot(二)整合mybatis,多数据源和事务管理
-- 1.整合mybatis -- 2.整合多数据源 -- 3. 整合事务 代码地址:https://github.com/showkawa/springBoot_2017/tree/master/ ...
- SpringBoot系列-整合Mybatis(XML配置方式)
目录 一.什么是 MyBatis? 二.整合方式 三.实战 四.测试 本文介绍下SpringBoot整合Mybatis(XML配置方式)的过程. 一.什么是 MyBatis? MyBatis 是一款优 ...
- 【springboot】整合 MyBatis
转自:https://blog.csdn.net/cp026la/article/details/86493503 1. 简介: 目前,国内大部分公司都使用 MyBatis作为持久层框架.本章整合My ...
- SpringBoot (四) - 整合Mybatis,逆向工程,JPA
1.SpringBoot整合MyBatis 1.1 application.yml # 数据源配置 spring: datasource: driver-class-name: com.mysql.c ...
- SpringBoot之整合MyBatis
今天了解一下SpringBoot如何与我们最常用的ORM框架Mybatis整合. 一. 需要在pom.xml文件里加入mybatis的依赖 <dependency> <groupId ...
- 玩转SpringBoot之整合Mybatis拦截器对数据库水平分表
利用Mybatis拦截器对数据库水平分表 需求描述 当数据量比较多时,放在一个表中的时候会影响查询效率:或者数据的时效性只是当月有效的时候:这时我们就会涉及到数据库的分表操作了.当然,你也可以使用比较 ...
- springboot项目整合mybatis
记录创建springboot项目并配置mybatis中间件: 资源准备及版本说明 编程工具:IDEA JDK版本:1.8 Maven版本:Apache Maven 3.6.3 springboot版本 ...
随机推荐
- 错误Matplotlib is building the font cache using fc-list. This may take a moment.
这上面的错误是因为你环境中没有安装GUI工具,但是你在代码中又想要显示图片,即有下面的语句: plt.imshow(np.transpose(npimg, (, , ))) plt.show() 那么 ...
- 使用 ctypes 进行 Python 和 C 的混合编程
Python 和 C 的混合编程工具有很多,这里介绍 Python 标准库自带的 ctypes 模块的使用方法. 初识 Python 的 ctypes 要使用 C 函数,需要先将 C 编译成动态链接库 ...
- 初学Python——介绍一些内置方法
1.abs()求绝对值 a=abs(-10) print(a) # 输出:10 2.all() 用来检测列表元素是否全部为空.0.False print(all([0,5,4])) #当列表所有元素都 ...
- 简单的if多分支结构练习:用户录入 1-10的数字 , 1-7没奖品 , 8,9,10分别获得 3 2 1 等奖
package com.summer.cn; import java.util.Scanner; /** * @author Summer *简单的if多分支结构练习 *用户录入 1-10的数字 , ...
- 洛谷 P1706 全排列问题
题目链接 https://www.luogu.org/problemnew/show/P1706 题目描述 输出自然数1到n所有不重复的排列,即n的全排列,要求所产生的任一数字序列中不允许出现重复的数 ...
- React-理解高阶组件
高阶组件:定义一个函数,传入一个组件,返回另外一个组件,另外一个组件包裹了传入的组件. 分类:属性代理高阶组件,反向继承高阶组件. 作用:代码复用,渲染节时. 高阶函数例子: function hel ...
- 关于学习JAVA第二章的心得
这章主要讲了JAVA的变量,数据类型和运算符的使用方法及规则. 其实在大一的时候接触过一点C和C++的知识所以对变量,数据类型,运算符还是有一定了解的. 变量其实就是存储数据的空间.我们每次使用某一种 ...
- 开源组件ELK日志系统配置与管理
ELK日志系统介绍 开源实时日志分析ELK平台能够完美的解决我们上述的问题,ELK由ElasticSearch.Logstash和Kiabana三个开源工具组成.官方网站:https://www.el ...
- Item 21: 比起直接使用new优先使用std::make_unique和std::make_shared
本文翻译自modern effective C++,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 博客已经迁移到这里啦 让我们先从std::make_unique和std::make_s ...
- 如何用CSS3画出一个立体魔方?
前言 最近在写<动画点点系列>文章,上一期分享了< 手把手教你如何绘制一辆会跑车 >,本期给大家带来是结合CSS3画出来的一个立体3d魔方,结合了js让你随心所欲想怎么转,就怎 ...