Friday, May 3, 2024
HomeJavaEasy methods to use MyBatis in Spring Boot software in Java? Instance...

Easy methods to use MyBatis in Spring Boot software in Java? Instance Tutorial


Hiya guys, On this tutorial, we are going to talk about learn how to create a spring boot mission with MyBatis. First, it’s essential have a greater understanding of what’s MyBatis and its use-cases. MyBatis is a SQL mapping framework with assist for customized SQL, saved procedures, and superior mapping. Though Spring Boot doesn’t formally assist MyBatis, the MyBatis neighborhood has created a Spring Boot startup for MyBatis.That is probably the most generally used open-source framework for implementing SQL databases entry in java purposes.

Based on MyBatis documentation, we will outline it as, 

MyBatis is a first-class persistence framework with assist for customized SQL, saved procedures, and superior mappings. MyBatis eliminates virtually the entire JDBC code and handbook setting of parameters and retrieval of outcomes. MyBatis can use easy XML or Annotations for configuration and map primitives, Map interfaces, and Java POJOs (Plain Outdated Java Objects) to database data.

Easy methods to use Spring Boot and  MyBatis in Java

Listed below are the step-by-step information to make use of MyBatis library in Spring Boot software for database interplay utilizing Java programming langague 

1. Add MyBatis Starter Dependency

It is advisable create a spring boot mission with this dependency with a view to use the MyBatis in your mission. To start out utilizing MyBatis, now we have to incorporate two essential dependencies, MyBatis and MyBatis-Spring. 

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

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<model>2.0.2</model>
</dependency>

Aside from that, we are going to want primary spring dependencies.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<model>5.3.8</model>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<model>5.3.8</model>
</dependency>

On this instance, we use the H2 database, so it's essential add the next dependencies to your mission pom.xml file.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<model>1.4.199</model>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<model>5.3.8</model>
</dependency>

The usage of MyBatis is actually the identical as JdbcTemplate, beginning with the essential data for configuring the database in software.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 mannequin

Let’s begin by making a easy POJO that’s used on this article.

package deal com.pupil.crudapp.mannequin;

import javax.persistence.*;

@Entity
@Desk(title = "STUDENT")
public class Scholar {

@Column(title = "id")
@Id
@GeneratedValue(technique=GenerationType.AUTO)
non-public int id;

@NotBlank(message = "Identify is necessary")
@Column(title = "title")
non-public String title;

@NotBlank(message = "E mail is necessary")
@Column(title = "e-mail")
non-public String e-mail;

@NotBlank(message = "Grade is necessary")
@Column(title = "grade")
non-public String grade;

public int getId() {
return id;
}

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

public String getName() {
return title;
}

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

public String getEmail() {
return e-mail;
}

public void setEmail(String e-mail) {
this.e-mail = e-mail;
}

public String getGrade() {
return grade;
}

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

@Override
public String toString() {
return "Scholar{" +
"id=" + id +
", title="" + title + "'' +
", e-mail="" + e-mail + "'' +
", grade="" + grade + "'' +
'}';
}
}


When making a persistent pojo class, @Entity is utilized. You'll have a comparable desk within the database for this Java class. @Column is used to hyperlink annotated attributes to their respective desk columns.
So in right here, we will add an equal SQL schema.sql file as under.
CREATE TABLE pupil(
id integer identification NOT NULL ,
title varchar(100) NOT NULL,
e-mail varchar(100) NOT NULL,
grade varchar(100),
CONSTRAINT pk_student_id PRIMARY KEY(id)
);

Then let's add some knowledge to our created desk. In right here, we use the info.sql file which is within the classpath f of the spring boot software so as to add some knowledge. 
INSERT INTO pupil(title,e-mail,grade) values ('Test1','test1@gmail.com', 6);
INSERT INTO pupil(title,e-mail,grade) values ('Test2','test2@gmail.com', 8);
INSERT INTO pupil(title,e-mail,grade) values ('Test3','test3@gmail.com', 10);
INSERT INTO pupil(title,e-mail,grade) values ('Test4','test4@gmail.com', 12);

3. Annotation primarily based configuration

Spring makes it simpler to arrange MyBatis. Solely javax.sql.Datasource, org.apache.ibatis.session.SqlSessionFactory, and at the very 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("knowledge.sql")
.construct();
}

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


We additionally utilized a @MapperScan annotation from MyBatis-Spring that scans outlined packages and routinely picks up interfaces utilizing any of the mapper annotations, reminiscent of @Choose or @Delete.

Utilizing @MapperScan additionally ensures that any mapper supplied is routinely registered as a Bean and may be utilized with the @Autowired annotation afterwards.

After completion of configuration, we will use MyBatis to create a Mapper to make use of, for instance, StudentMapper can use immediately as follows.

public interface StudentMapper {
@Choose("choose * from pupil")
Record<Scholar> getAllStudents();

@Outcomes({
@End result(property = "id", column = "id"),
@End result(property = "title", column = "n"),
@End result(property = "e-mail", column = "e"),
@End result(property = "grade", column = "g")
})
@Choose("choose e-mail as e,title as n,grade as g,id as id from pupil the place id=#{id}")
Scholar getStudentById(Lengthy id);

@Choose("choose * from pupil the place e-mail like concat('%',#{e-mail},'%')")
Record<Scholar> getStudentsByName(String e-mail);

@Insert({"insert into pupil(e-mail,title,grade) values(#{e-mail},#{title})"})
@SelectKey(assertion = "choose last_insert_id()", keyProperty = "id", earlier than = false, resultType = Integer.class)
Integer addStudent(Scholar pupil);

@Replace("replace pupil set e-mail=#{e-mail},title=#{title}, grade=#{grade} the place id=#{id}")
Integer updateStudentById(Scholar pupil);

@Delete("delete from pupil the place id=#{id}")
Integer deleteStudentById(Integer id);
}


This can be a totally annotated method to write SQL, not an XML file. The @Choose, @Insert, @Replace, and @Delete annotations correspond to the XML choose, insert, replace, and delete tags, respectively, whereas the @Outcomes annotation is equal to the XML ResultMap mapping file.

@SelectKey annotation which is used right here is used to implement the first key backfill operate. that’s, when the info is efficiently inserted, the efficiently inserted data-id is assigned to the person object’s id property.

4. Check our software

We will take a look at the appliance utilizing the next command.

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

@Autowired
StudentMapper studentMapper;

@Check
public void whenRecordsInDatabase_shouldReturnArticleWithGivenId() {
Scholar pupil = studentMapper.getStudent(1L);

assertThat(pupil).isNotNull();
assertThat(pupil.getId()).isEqualTo(1L);
assertThat(pupil.getName()).isEqualTo("Check");
assertThat(pupil.getEmail()).isEqualTo("Check@gmail.com");
assertThat(pupil.getGrade()).isEqualTo("6");
}
}

Within the above instance, we have used MyBatis to retrieve the one report we inserted beforehand in our knowledge.sql file.

5. Run the appliance 

To maintain issues easy we are going to make the Software class implement CommandLineRunner and implement a run technique to check JDBC strategies.

@SpringBootApplication
public class Software implements CommandLineRunner {

non-public Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
non-public StudentRepository studentRepository;

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

logger.information("Scholar id 001 -> {}", studentRepository.findById(001));

logger.information("Replace 002 -> {}", studentRepository.replace(new Scholar(001, "studentupdate", "studentupdate@gmail.com", "8")));

studentRepository.deleteById(001);

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

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

6. XML Based mostly Configuration  

To make use of MyBatis with Spring, we’ll require Datasource, SqlSessionFactory, and at the very least one mapper, as beforehand acknowledged.

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

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

<bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property title="mapperInterface" worth="com.pupil.crudapp.mybatis.StudentMapper " />
<property title="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

On this instance, we used the customized XML file to configure the spring-jdbc. To testing our software, we will use the context configuration, which we will do by making use of the annotation.

So let's take a look at what are the benefits and drawbacks of utilizing MyBatis on Spring boot mission.

7. Benefits of MyBatis

1. Straightforward to take care of and handle, no want to seek out these statements in Java code utilizing tag as a substitute of logic code Be sure that the names are the identical. 

2. The mapping relationship may be routinely mapped or not configured after the mapping relationship is configured.

3. The automated mapping may also be accomplished by configuring column title = discipline title 

4. Near JDBC, extra versatile Mybatis is a persistence layer framework, which additionally belongs to ORM mapping 

4. Straightforward to study 

5. Present XML tags to assist writing dynamic SQL

8. Disadvantages of MyBatis

1. The workload of writing SQL statements is comparatively massive, and there are particular necessities on the flexibility of builders to write down SQL. 

2. SQL statements depend upon the database, which ends up in the dearth of portability of the database, and the database can’t be changed casually.

MyBatis is a DAO layer resolution that focuses on SQL and is sufficiently adaptable. MyBatis is the perfect resolution for initiatives with high-performance necessities or with extra changeable necessities, reminiscent of Net purposes. 

That is all about learn how to use Spring Boot and MyBatis in Java. So on this tutorial, now we have used a easy software to reveal the Spring boot and MyBatis. Hope you perceive the issues going with utilizing MyBatis together with Spring Boot. See you within the subsequent tutorial. Till then bye!


Different Java and Spring Tutorial you could like
  • 10 Superior Spring Boot Programs for Java builders (programs)
  • Spring Knowledge JPA Repository Instance in Java (JpaReposistory instance)
  • 20+ Spring MVC Interview Questions for Programmers (reply)
  • 13 Spring Boot Actuator Interview questions (boot questions)
  • Distinction between @Autowired and @Inject in Spring? (reply)
  • High 5 Frameworks Java Developer Ought to Know (frameworks)
  • Distinction between @RequestParam and @PathVariable in Spring (reply)
  • High 7  Programs to study Microservices in Java (programs)
  • Easy methods to use @Bean in Spring framework (Instance)
  • 5 Spring Cloud annotations Java programmer ought to study (cloud)
  • High 5 Programs to Be taught and Grasp Spring Cloud (programs)
  • 5 Programs to Be taught Spring Safety for Java programmers (programs)
  • 10 Spring MVC annotations Java developer ought to know (annotations)
  • Easy methods to replace an entity utilizing Spring Knowledge JPA? (instance)
  • 20 Spring Boot Interview Questions with solutions (questions)
  • What's @Conditional annotation in Spring? (conditional instance)
  • How Spring MVC works internally? (reply)
  • Spring Knowledge JPA @Question Instance (question instance)
  • Easy methods to repair No property sort present in Spring Knowledge JPA? [Solution]
  • @SpringBootApplication vs. @EnableAutoConfiguration? (reply)
  • 15 Spring Boot Interview Questions for Java Builders (questions)
  • Distinction between @Element@Service, and @Controller in Spring (reply)
Thanks for studying this text up to now. In case you discover this full-stack Spring Boot and MyBatis tutorial and instance, then please share it with your mates and colleagues. When you have any questions or suggestions, then please drop a notice.

P. S. - In case you are a Spring Boot newbie and wish to study the Spring Boot framework from scratch and search for among the finest on-line sources, you too can take a look at these finest Spring Boot programs for Java buildersThis listing comprises free Udemy and Pluralsight programs to study Spring Boot from scratch.  



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments