SpringBoot之整合Mybatis范例

2022-10-19,,,

依赖包:

 <?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范例.doc》

下载本文的Word格式文档,以方便收藏与打印。