Preface
Today, let’s learn about SpringBoot integrating mybatis. There are generally two ways to integrate mybatis. One is based on annotation and the other is based on XML configuration. Today, let’s first learn about the annotation-based mybatis integration. I won't say much below, let's take a look at the detailed introduction
Because it is mybatis, it must be related to mybatis, and I use mysql, so it also needs to introduce mysql-related.
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency>
A User model is created here, which is convenient for comparison with the database table. Here, a database named mybatis is created in mysql, and a user table is created. At the same time, an enumeration class UserSexEnum is created.
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` int(11) DEFAULT NULL, `sex` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
package com.example.model;import java.io.Serializable;public class User implements Serializable{ @Override public String toString() { // TODO Auto-generated method stub return "User [id=" + Id + ", name=" + Name + ", age=" + Age + "]"; } public int getId() { return Id; } public void setId(int id) { Id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public int getAge() { return Age; } public void setAge(int age) { Age = age; } private int Id; private String Name; private int Age; private UserSexEnum Sex; public UserSexEnum getSex() { return Sex; } public void setSex(UserSexEnum sex) { Sex = sex; }} package com.example.model;public enum UserSexEnum { MAN, WOMAN}Here we need to compare the model with the SQL that operates the database. What comparison should we use? Then we need to create a mapper. There are additions, deletions, modifications and searches here.
package com.example.mapper;import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import com.example.model.*;;public interface UserMapper { @Select("SELECT * FROM user") @Results({ @Result(property = "Sex", column = "sex", javaType = UserSexEnum.class), @Result(property = "Name", column = "name") }) List<User> getAll(); @Select("SELECT * FROM user WHERE id = #{id}") @Results({ @Result(property = "Sex", column = "sex", javaType = UserSexEnum.class), @Result(property = "Name", column = "name") }) User getOne(int id); @Insert("INSERT INTO user(name,age,sex) VALUES(#{name}, #{age}, #{sex})") void insert(User user); @Update("UPDATE user SET name=#{userName},age=#{age} WHERE id =#{id}") void update(User user); @Delete("DELETE FROM user WHERE id =#{id}") void delete(int id);}The mapper is configured above, so how can the system know where the mapper is placed? So there is annotation @MapperScan.
package com.example.demo;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.example.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Here, UserController is created, one is to display all users, and the other is to add a new user and then display all users.
package com.example.demo;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.example.mapper.UserMapper;import com.example.model.User;import com.example.model.UserSexEnum;@Controller@RequestMapping("/user")public class UserController { @Autowired private UserMapper userMapper; @RequestMapping(value = "/alluser.do",method = RequestMethod.GET) public String getallusers(Model model) { List<User> users=userMapper.getAll(); model.addAttribute("users", users); return "userlist"; } @RequestMapping(value = "/insert.do",method = RequestMethod.GET) public String adduser(Model model) { User user=new User(); user.setName("cuiyw"); user.setAge(27); user.setSex(UserSexEnum.MAN); userMapper.insert(user); List<User> users=userMapper.getAll(); model.addAttribute("users", users); return "userlist"; }}The mapper and model are also set above. To interact with the database, you must configure the database address and other information. An error was reported when running here.nested exception is java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specific time zone value if you want to utilize time zone support. The next time zone is set in mysql: set global time_zone='+8:00';
spring.mvc.view.prefix=/view/spring.mvc.view.suffix=.jspmybatis.type-aliases-package=com.example.modelspring.datasource.driverClassName = com.mysql.cj.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/mybatisspring.datasource.username = rootspring.datasource.password = 123456
7. Create a page to display
Here we will still use jsp to display data according to the previous blog.
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body> <table> <tr><th>Name</th><th>Age</th><th>Gender</th></tr> <c:forEach items="${users}" var="item"> <tr><td>${item.name}</td><td>${item.age}</td><td>${item.sex}</td></tr> </c:forEach> </table></body></html>Here, first open http://localhost:8080/user/alluser.do in the browser, you can see the user list, and then enter http://localhost:8080/user/insert.do, and you will see that the list displays an additional line of data.
Using annotation-based integration of mybatis is easier and more convenient, but it has both advantages and disadvantages. It may be less convenient for multiple tables to be connected, and it may be better to use XML-based configuration.
Okay, the above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.