SpringBoot之整合Mybatis范例
依赖包:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <parent> 6 <groupId>org.springframework.boot</groupId> 7 <artifactId>spring-boot-starter-parent</artifactId> 8 <version>2.1.1.RELEASE</version> 9 <relativePath/> <!-- lookup parent from repository --> 10 </parent> 11 <groupId>org.springboot</groupId> 12 <artifactId>demo</artifactId> 13 <version>1.0.1-SNAPSHOT</version> 14 <name>boot_demo</name> 15 <description>Demo project for Spring Boot</description> 16 17 <properties> 18 <java.version>1.8</java.version> 19 <dom4j.version>1.6.1</dom4j.version> 20 </properties> 21 22 <dependencies> 23 <dependency> 24 <groupId>org.springframework.boot</groupId> 25 <artifactId>spring-boot-starter</artifactId> 26 </dependency> 27 28 <dependency> 29 <groupId>org.springframework.boot</groupId> 30 <artifactId>spring-boot-starter-test</artifactId> 31 <scope>test</scope> 32 </dependency> 33 <dependency> 34 <groupId>org.springframework.boot</groupId> 35 <artifactId>spring-boot-starter-web</artifactId> 36 </dependency> 37 38 <dependency> 39 <groupId>org.springframework.boot</groupId> 40 <artifactId>spring-boot-devtools</artifactId> 41 <optional>true</optional> 42 </dependency> 43 44 <!-- 引入freemarker包 --> 45 <dependency> 46 <groupId>org.springframework.boot</groupId> 47 <artifactId>spring-boot-starter-freemarker</artifactId> 48 </dependency> 49 50 <dependency> 51 <groupId>org.springframework.boot</groupId> 52 <artifactId>spring-boot-starter-thymeleaf</artifactId> 53 </dependency> 54 55 <dependency> 56 <groupId>org.springframework.boot</groupId> 57 <artifactId>spring-boot-starter-data-jpa</artifactId> 58 </dependency> 59 60 <dependency> 61 <groupId>mysql</groupId> 62 <artifactId>mysql-connector-java</artifactId> 63 <scope>runtime</scope> 64 </dependency> 65 66 <dependency> 67 <groupId>org.springframework.boot</groupId> 68 <artifactId>spring-boot-starter-jdbc</artifactId> 69 </dependency> 70 71 <dependency> 72 <groupId>org.mybatis.spring.boot</groupId> 73 <artifactId>mybatis-spring-boot-autoconfigure</artifactId> 74 <version>1.3.2</version> 75 </dependency> 76 77 <dependency> 78 <groupId>commons-io</groupId> 79 <artifactId>commons-io</artifactId> 80 <version>2.6</version> 81 </dependency> 82 83 <dependency> 84 <groupId>org.mybatis</groupId> 85 <artifactId>mybatis</artifactId> 86 <version>3.4.6</version> 87 </dependency> 88 89 <dependency> 90 <groupId>org.mybatis</groupId> 91 <artifactId>mybatis-spring</artifactId> 92 <version>1.3.2</version> 93 </dependency> 94 95 <!-- spring事务 --> 96 <dependency> 97 <groupId>org.springframework</groupId> 98 <artifactId>spring-tx</artifactId> 99 </dependency> 100 101 <dependency> 102 <groupId>dom4j</groupId> 103 <artifactId>dom4j</artifactId> 104 <version>${dom4j.version}</version> 105 </dependency> 106 </dependencies> 107 108 <build> 109 <plugins> 110 <plugin> 111 <groupId>org.springframework.boot</groupId> 112 <artifactId>spring-boot-maven-plugin</artifactId> 113 <configuration> 114 <fork>true</fork> 115 </configuration> 116 </plugin> 117 </plugins> 118 </build> 119 120 </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:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package org.springboot.model; 2 3 /** 4 * @Auther:GongXingRui 5 * @Date:2018/12/24 6 * @Description: 7 **/ 8 public class Student { 9 private String id; 10 private String name; 11 private String gender; 12 private int age; 13 private String telephone; 14 15 public Student() { 16 17 } 18 19 public Student(String id, String name, String gender) { 20 this.id = id; 21 this.name = name; 22 this.gender = gender; 23 } 24 25 public Student(String id, String name, String gender, int age, String telephone) { 26 this.id = id; 27 this.name = name; 28 this.gender = gender; 29 this.age = age; 30 this.telephone = telephone; 31 } 32 33 public String getId() { 34 return id; 35 } 36 37 public void setId(String id) { 38 this.id = id; 39 } 40 41 public String getName() { 42 return name; 43 } 44 45 public void setName(String name) { 46 this.name = name; 47 } 48 49 public String getGender() { 50 return gender; 51 } 52 53 public void setGender(String gender) { 54 this.gender = gender; 55 } 56 57 public int getAge() { 58 return age; 59 } 60 61 public void setAge(int age) { 62 this.age = age; 63 } 64 65 public String getTelephone() { 66 return telephone; 67 } 68 69 public void setTelephone(String telephone) { 70 this.telephone = telephone; 71 } 72 73 @Override 74 public String toString() { 75 return "Student{" + 76 "id='" + id + '\'' + 77 ", name='" + name + '\'' + 78 ", gender='" + gender + '\'' + 79 ", age=" + age + 80 ", telephone='" + telephone + '\'' + 81 '}'; 82 } 83 }
mapper接口
1 package org.springboot.mapper; 2 3 import org.apache.ibatis.annotations.Mapper; 4 import org.springboot.model.Student; 5 6 import java.util.List; 7 8 /** 9 * @Auther:GongXingRui 10 * @Date:2018/12/26 11 * @Description: 12 **/ 13 @Mapper 14 public interface StudentMapper { 15 Student getStudentById(String id); 16 17 List<Student> getAllStudent(); 18 19 void addStudent(Student student); 20 21 void deleteStudentById(String id); 22 23 }
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:
1 package org.springboot.service; 2 3 import org.springboot.mapper.StudentMapper; 4 import org.springboot.model.Student; 5 import org.springboot.utils.ObjectUtils; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 9 import java.util.List; 10 11 /** 12 * @Auther:GongXingRui 13 * @Date:2018/12/24 14 * @Description: 15 **/ 16 @Service 17 public class StudentService { 18 19 @Autowired 20 private StudentMapper studentMapper; 21 22 public Student getStudentDemo() { 23 Student student = new Student(); 24 student.setId("1"); 25 student.setName("小明"); 26 student.setGender("男"); 27 student.setAge(18); 28 student.setTelephone("137456678"); 29 return student; 30 } 31 32 public Student getStudentById(String id) { 33 return studentMapper.getStudentById(id); 34 } 35 36 public List<Student> getAllStudent() { 37 return studentMapper.getAllStudent(); 38 } 39 40 public void addStudent(Student student) { 41 studentMapper.addStudent(student); 42 } 43 44 public void deleteStudentById(String id) { 45 studentMapper.deleteStudentById(id); 46 } 47 48 public boolean loginStudentcheck(String name, String id) { 49 Student student = studentMapper.getStudentById(id); 50 if (ObjectUtils.isNull(student)) { 51 return false; 52 } else if (student.getName().equals(name)) { 53 return true; 54 } 55 return false; 56 } 57 58 }
controller
1 package org.springboot.controller; 2 3 import com.sun.jmx.snmp.SnmpUnknownModelLcdException; 4 import com.sun.org.apache.xpath.internal.operations.Mod; 5 import org.apache.logging.log4j.LogManager; 6 import org.apache.logging.log4j.Logger; 7 import org.springboot.mapper.StudentMapper; 8 import org.springboot.model.Student; 9 import org.springboot.service.StudentService; 10 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.stereotype.Controller; 12 import org.springframework.ui.Model; 13 import org.springframework.web.bind.annotation.RequestBody; 14 import org.springframework.web.bind.annotation.RequestMapping; 15 import org.springframework.web.bind.annotation.RequestParam; 16 import org.springframework.web.bind.annotation.ResponseBody; 17 import org.springframework.web.servlet.ModelAndView; 18 19 import java.util.List; 20 21 22 /** 23 * @Auther:GongXingRui 24 * @Date:2018/12/24 25 * @Description: 26 **/ 27 @Controller 28 public class StudentController { 29 private Logger logger = LogManager.getLogger(StudentController.class); 30 @Autowired 31 StudentService studentService; 32 33 @RequestMapping("/showStudentInfo") 34 public String showStudentInfo(Model model) { 35 logger.info("查询学生信息"); 36 Student student = studentService.getStudentDemo(); 37 logger.info(student); 38 model.addAttribute("student", student); 39 return "studentInfo.html"; 40 } 41 42 // 使用freemaker模板 43 @RequestMapping("/showStudentInfo2") 44 public String showStudentInfo2(Model model) { 45 logger.info("查询学生信息"); 46 Student student = studentService.getStudentDemo(); 47 logger.info(student); 48 model.addAttribute("student", student); 49 return "studentInfo2"; 50 } 51 52 @RequestMapping("/studentIndex") 53 public String studentIndex() { 54 logger.info("学生信息首页"); 55 return "student/studentIndex"; 56 } 57 58 @RequestMapping("/getStudentById") 59 @ResponseBody 60 public String getStudentById(String id) { 61 logger.info("通过ID查询学生信息"); 62 Student student = studentService.getStudentById(id); 63 if (null == student) { 64 String tip = "没有找到对应数据 -> id:" + id; 65 logger.info(tip); 66 return tip; 67 } 68 logger.info(student); 69 return student.toString(); 70 } 71 72 @RequestMapping("/getStudentById2") 73 public String getStudentById2(String id, Model model) { 74 logger.info("通过ID查询学生信息2"); 75 Student student = studentService.getStudentById(id); 76 if (null == student) { 77 String tip = "没有找到对应数据 -> id:" + id; 78 logger.info(tip); 79 return null; 80 } 81 model.addAttribute("student", student); 82 logger.info(student); 83 return "student/studentInfo"; 84 } 85 86 @RequestMapping("/getAllStudent") 87 public ModelAndView getAllStudent(ModelAndView mv) { 88 logger.info("查询所有学生信息"); 89 List<Student> students = studentService.getAllStudent(); 90 mv.addObject("studentList", students); 91 mv.setViewName("student/allStudentInfo"); 92 logger.info(students); 93 return mv; 94 } 95 96 @RequestMapping("/addStudent") 97 @ResponseBody 98 public String addStudent(Student student) { 99 logger.info("新增学生信息"); 100 try { 101 studentService.addStudent(student); 102 } catch (Exception e) { 103 e.printStackTrace(); 104 return "新增学生信息发生异常!<br>" + e.toString(); 105 } 106 logger.info(student.toString()); 107 return "新增学生信息成功!<br>" + student.toString(); 108 } 109 110 @RequestMapping("/deleteStudentById") 111 @ResponseBody 112 public String deleteStudentById(String id) { 113 logger.info("通过ID删除学生信息"); 114 try { 115 studentService.deleteStudentById(id); 116 } catch (Exception e) { 117 e.printStackTrace(); 118 return "通过ID删除学生信息发生异常!<br>" + e.toString(); 119 } 120 logger.info("通过ID删除学生信息成功! -> id:" + id); 121 return "通过ID删除学生信息成功! -> id:" + id; 122 } 123 124 @RequestMapping("/loginStudentcheck") 125 public String loginStudentcheck(String name, String id, Model model) { 126 logger.info("正在登陆学生系统..."); 127 logger.info("用户名:" + name + ", 密码:" + id); 128 boolean flag = studentService.loginStudentcheck(name, id); 129 if (flag) { 130 logger.info("登陆成功"); 131 return "student/studentIndex"; 132 } 133 model.addAttribute("info", "登陆失败!用户名或密码错误!"); 134 logger.info("登陆失败!用户名或密码错误!"); 135 return "student/error"; 136 } 137 138 @RequestMapping("/loginStudent") 139 public String loginStudent() { 140 logger.info("请求登陆学生信息页面"); 141 return "student/loginStudent"; 142 } 143 144 145 }
程序入口:DemoApplication.java
1 package org.springboot; 2 3 import org.mybatis.spring.annotation.MapperScan; 4 import org.springframework.boot.SpringApplication; 5 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 7 @SpringBootApplication 8 @MapperScan("org.springboot.mapper") 9 public class DemoApplication { 10 public static void main(String[] args) { 11 SpringApplication.run(DemoApplication.class, args); 12 } 13 14 }
工程目录: