Mybatis with Spring Boot example
MyBatis is one of the most commonly used open-source frameworks for implementing SQL databases access in Java applications.
MyBatis is a SQL Mapping framework with support for custom SQL, stored procedures and advanced mappings. SpringBoot doesn’t provide official support for MyBatis integration, but the MyBatis community built a SpringBoot starter for MyBatis.
You can read about the SpringBoot MyBatis https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ and you can explore the source code on GitHub https://github.com/mybatis/mybatis-spring-boot.
In this quick tutorial, we’ll present how to integrate MyBatis with Spring and Spring Boot.
1. dependency needed for mybatis :
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.3</version>
</dependency><dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2. Mapper using Annotation:
#mybatis using annotation and spring boot
MainClass:
@SpringBootApplication
@MapperScan(“com.example.demo.mapper”)
@MappedTypes({Students.class})
public class RoledemoApplication {
public static void main(String[] args) {
SpringApplication.run(RoledemoApplication.class, args);
}
}
**@MapperScan used to map directory in which you have mapper classes.
**@MappedTypes used to map modal classes.
ModalClass:
public class Student {
private Integer studId;
private String name;
private String email;
// setters and getters
}
MapperInterface:
@Mapper
public interface StudentMapper {@Select(“select * from Students”)
List<Student> findAllStudents();@Select(“select * from Students where studId=#{id}”)
Student findStudentById(Integer id);@Insert(“insert into Students(name,email) values(name=#{name},email=#{email})”)
void insertStudent(Student student);@Update(“update Students set name=#{student.name},email=#{student.email} where studId=#{id}”)
void updateStudent(Student student,int id);@Delete(“delete from Students where studId=#{id}”)
void deleteStudent(Interger id);}
ControllerClass:
@RestController
@RequestMapping(value = “/”, consumes = “application/json”, produces = “application/json”)
public class MainController{ @Autowired
StudentMapper studentMapper; @GetMapping(“/findAllStudents”)
public List<Students> findAllStudents(){
return studentMapper.findAllStudents();
} @PostMapping(“/insertStudent”)
public void insertStudent(@RequestBody Students students){
studentMapper.insertStudent(student);
} @PutMapping(“/updateStudent/{id}”)
public void updateStudent(@RequestBody Students students,@PathVariable(“id”) int id){
studentMapper.updateStudent(student,id);
} @DeleteMapping(“/deleteStudent/{id}”)
public void deleteStudent(@PathVariable(“id”) int id){
studentMapper.deleteStudent(id);
}}
3. Mapper using XML:
#mybatis using XML and spring boot
MainClass:
@SpringBootApplication
@MapperScan(“com.example.demo.mapper”)
public class RoledemoApplication {
public static void main(String[] args) {
SpringApplication.run(RoledemoApplication.class, args);
}
}
ModalClass:
public class Student {
private Integer studId;
private String name;
private String email;
// setters and getters
}
MapperInterface:
@Mapper
public interface StudentMapper{
List<Student> findAllStudents();
Student findStudentById(Integer id);
void insertStudent(Student student);
void updateStudent(Student student,int id);
void deleteStudent(Interger id);
}
ControllerClass:
@RestController
@RequestMapping(value = “/”, consumes = “application/json”, produces = “application/json”)
public class MainController{ @Autowired
StudentMapper studentMapper; @GetMapping(“/findAllStudents”)
public List<Students> findAllStudents(){
return studentMapper.findAllStudents();
} @PostMapping(“/insertStudent”)
public void insertStudent(@RequestBody Students students){
studentMapper.insertStudent(student);
} @PutMapping(“/updateStudent/{id}”)
public void updateStudent(@RequestBody Students students,@PathVariable(“id”) int id){
studentMapper.updateStudent(student,id);
} @DeleteMapping(“/deleteStudent/{id}”)
public void deleteStudent(@PathVariable(“id”) int id){
studentMapper.deleteStudent(id);
}
}
application.properties:
server.port = 8080
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/demo
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.example.demo.model
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
<typeAlias type="com.example.demo.model.Students" alias="Students" />
</typeAliases>
</configuration>
StudentsMapper.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="com.example.demo.mapper.StudentMapper">
<resultMap id="StudentResultMap" type="Students">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="email" property="email" jdbcType="VARCHAR"/>
</resultMap> <sql id="Base_Column_List">
id, name, email
</sql> <select id="findAllStudents" resultMap="StudentResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM Students
</select><insert id="insertStudent" parameterType="Students" resultMap="StudentResultMap">
INSERT INTO Students(name,email) VALUES(#{name},#{email})</insert><update id="updateStudent">
UPDATE
Students SET
<if test="student.name!=null">name=#{student.name},</if>
<if test="student.email!=null">email=#{student.email}</if>
WHERE studId=#{id}
</update><delete id="deleteStudent" parameterType="int">
DELETE FROM Students
WHERE studId =#{id}
</delete></mapper>