Friday, March 10, 2023

How to use MyBatis in Spring Boot application in Java? Example Tutorial

Hello guys, In this tutorial, we will discuss how to create a spring boot project with MyBatis. First, you need to have a better understanding of what is MyBatis and its use-cases. MyBatis is a SQL mapping framework with support for custom SQL, stored procedures, and advanced mapping. Although Spring Boot does not officially support MyBatis, the MyBatis community has created a Spring Boot startup for MyBatis.This is the most commonly used open-source framework for implementing SQL databases access in java applications.

According to MyBatis documentation, we can define it as, 

MyBatis is a first-class persistence framework with support for custom SQL, stored procedures, and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces, and Java POJOs (Plain Old Java Objects) to database records.


How to use Spring Boot and  MyBatis in Java

Here are the step by step guide to use MyBatis library in Spring Boot application for database interaction using Java programming langague 


1. Add MyBatis Starter Dependency

You need to create a spring boot project with this dependency in order to use the MyBatis in your project. To start using MyBatis, we have to include two main dependencies, MyBatis and MyBatis-Spring. 

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
Apart from that, we will need basic spring dependencies.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.8</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.8</version>
</dependency>
In this example, we use the H2 database, so you need to add the following dependencies to your project pom.xml file.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.8</version>
</dependency>

The use of MyBatis is essentially the same as JdbcTemplate, starting with the basic information for configuring the database in application.properties.

# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/CustomerData
db.username: root
db.password: admin

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: org

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true



2. Defining the model

Let's start by creating a simple POJO that is used in this article.

package com.student.crudapp.model;

import javax.persistence.*;

@Entity
@Table(name = "STUDENT")
public class Student {

@Column(name = "id")
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

@NotBlank(message = "Name is mandatory")
@Column(name = "name")
private String name;

@NotBlank(message = "Email is mandatory")
@Column(name = "email")
private String email;

@NotBlank(message = "Grade is mandatory")
@Column(name = "grade")
private String grade;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getGrade() {
return grade;
}

public void setGrade(String grade) {
this.grade = grade;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", grade='" + grade + '\'' +
'}';
}
}

When creating a persistent pojo class, @Entity is utilized. You will have a comparable table in the database for this Java class. @Column is used to link annotated attributes to their respective table columns.
So in here, we can add an equivalent SQL schema.sql file as below.
CREATE TABLE student(
id integer identity NOT NULL ,
name varchar(100) NOT NULL,
email varchar(100) NOT NULL,
grade varchar(100),
CONSTRAINT pk_student_id PRIMARY KEY(id)
);

Then let's add some data to our created table. In here, we use the data.sql file which is in the classpath f of the spring boot application to add some data. 
INSERT INTO student(name,email,grade) values ('Test1','test1@gmail.com', 6);
INSERT INTO student(name,email,grade) values ('Test2','test2@gmail.com', 8);
INSERT INTO student(name,email,grade) values ('Test3','test3@gmail.com', 10);
INSERT INTO student(name,email,grade) values ('Test4','test4@gmail.com', 12);

3. Annotation based configuration

Spring makes it easier to set up MyBatis. Only javax.sql.Datasource, org.apache.ibatis.session.SqlSessionFactory, and at least one mapper are required.


@Configuration
@MapperScan("org.mybatis.spring.mapper.MapperFactoryBean")
public class PersistenceConfig {

@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.addScript("data.sql")
.build();
}

@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
return factoryBean.getObject();
}
}

We also applied a @MapperScan annotation from MyBatis-Spring that scans defined packages and automatically picks up interfaces using any of the mapper annotations, such as @Select or @Delete.

Using @MapperScan also ensures that any mapper provided is automatically registered as a Bean and can be utilized with the @Autowired annotation afterwards.
After completion of configuration, we can use MyBatis to create a Mapper to use, for example, StudentMapper can use directly as follows.

public interface StudentMapper {
@Select("select * from student")
List<Student> getAllStudents();

@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "n"),
@Result(property = "email", column = "e"),
@Result(property = "grade", column = "g")
})
@Select("select email as e,name as n,grade as g,id as id from student where id=#{id}")
Student getStudentById(Long id);

@Select("select * from student where email like concat('%',#{email},'%')")
List<Student> getStudentsByName(String email);

@Insert({"insert into student(email,name,grade) values(#{email},#{name})"})
@SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)
Integer addStudent(Student student);

@Update("update student set email=#{email},name=#{name}, grade=#{grade} where id=#{id}")
Integer updateStudentById(Student student);

@Delete("delete from student where id=#{id}")
Integer deleteStudentById(Integer id);
}

This is a fully annotated way to write SQL, not an XML file. The @Select, @Insert, @Update, and @Delete annotations correspond to the XML select, insert, update, and delete tags, respectively, whereas the @Results annotation is equivalent to the XML ResultMap mapping file.

@SelectKey annotation which is used here is used to implement the primary key backfill function. that is, when the data is successfully inserted, the successfully inserted data-id is assigned to the user object's id property.

4. Test our application

We can test the application using the following command.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = PersistenceConfig.class)
public class StudentMapperIntegrationTest {

@Autowired
StudentMapper studentMapper;

@Test
public void whenRecordsInDatabase_shouldReturnArticleWithGivenId() {
Student student = studentMapper.getStudent(1L);

assertThat(student).isNotNull();
assertThat(student.getId()).isEqualTo(1L);
assertThat(student.getName()).isEqualTo("Test");
assertThat(student.getEmail()).isEqualTo("Test@gmail.com");
assertThat(student.getGrade()).isEqualTo("6");
}
}
In the above example, we've used MyBatis to retrieve the only record we inserted previously in our data.sql file.

5. Run the application 

To keep things simple we will make the Application class implement CommandLineRunner and implement a run method to test JDBC methods.

@SpringBootApplication
public class Application implements CommandLineRunner {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
private StudentRepository studentRepository;

@Override
public void run(String... args) throws Exception {

logger.info("Student id 001 -> {}", studentRepository.findById(001));

logger.info("Update 002 -> {}", studentRepository.update(new Student(001, "studentupdate", "studentupdate@gmail.com", "8")));

studentRepository.deleteById(001);

logger.info("All stuednts -> {}", studentRepository.findAll());
}

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}



6. XML Based Configuration  

To use MyBatis with Spring, we'll require Datasource, SqlSessionFactory, and at least one mapper, as previously stated.

<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="schema.sql"/>
<jdbc:script location="data.sql"/>
</jdbc:embedded-database>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.student.crudapp.mybatis.StudentMapper " />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
In this example, we used the custom XML file to configure the spring-jdbc. To testing our application, we can use the context configuration, which we can do by applying the annotation.

So let's have a look at what are the advantages and disadvantages of using MyBatis on Spring boot project.

7. Advantages of MyBatis

1. Easy to maintain and manage, no need to find these statements in Java code using tag instead of logic code Ensure that the names are the same. 

2. The mapping relationship can be automatically mapped or not configured after the mapping relationship is configured.

3. The automatic mapping can also be completed by configuring column name = field name 

4. Close to JDBC, more flexible Mybatis is a persistence layer framework, which also belongs to ORM mapping 
4. Easy to learn 

5. Provide XML tags to support writing dynamic SQL

8. Disadvantages of MyBatis

1. The workload of writing SQL statements is relatively large, and there are certain requirements on the ability of developers to write SQL. 

2. SQL statements depend on the database, which leads to the lack of portability of the database, and the database cannot be replaced casually.

MyBatis is a DAO layer solution that focuses on SQL and is sufficiently adaptable. MyBatis is the ideal solution for projects with high-performance requirements or with more changeable requirements, such as Web applications. 

That's all about how to use Spring Boot and MyBatis in Java. So in this tutorial, we have used a simple application to demonstrate the Spring boot and MyBatis. Hope you understand the things going with using MyBatis along with Spring Boot. See you in the next tutorial. Until then bye!

Other Java and Spring Tutorial you may like
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Spring Data JPA Repository Example in Java (JpaReposistory example)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • 13 Spring Boot Actuator Interview questions (boot questions)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • Top 7  Courses to learn Microservices in Java (courses)
  • How to use @Bean in Spring framework (Example)
  • 5 Spring Cloud annotations Java programmer should learn (cloud)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • 10 Spring MVC annotations Java developer should know (annotations)
  • How to update an entity using Spring Data JPA? (example)
  • 20 Spring Boot Interview Questions with answers (questions)
  • What is @Conditional annotation in Spring? (conditional example)
  • How Spring MVC works internally? (answer)
  • Spring Data JPA @Query Example (query example)
  • How to fix No property type found in Spring Data JPA? [Solution]
  • @SpringBootApplication vs. @EnableAutoConfiguration? (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Difference between @Component@Service, and @Controller in Spring (answer)

Thanks for reading this article so far. If you find this full-stack Spring Boot and MyBatis tutorial and example, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you are a Spring Boot beginner and want to learn the Spring Boot framework from scratch and look for some of the best online resources, you can also check out these best Spring Boot courses for Java developersThis list contains free Udemy and Pluralsight courses to learn Spring Boot from scratch.  

No comments:

Post a Comment