[JAVA] Spring + MyBatis connection setting method

What is MyBatis

A framework that indirectly accesses DB from Java by mapping SQL and Java objects. As a feature, by declaratively defining SQL in configuration files and annotations, Being able to hide the existence of SQL itself from business logic written in Java.

The Mapper interface hides SQL, and MyBatis links the methods of the Mapper interface with SQL. Therefore, from Java business logic, you can execute the linked SQL just by calling the Mapper interface.

Prerequisites

・ Eclipse 2018-09 (4.9.0) ・ Windows 10 ・ H2 -There are two ways to specify SQL in MyBatis: "mapping file" and "annotation". This time, we will use a "mapping file".

Initial setting

pom.xml


        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.4.0</version>
		</dependency>

MybatisTestApplication.java


@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.mybatis.test.domain")
public class MybatisTestApplication {

	//Spring Boot startup method
	public static void main(String[] args) {
		SpringApplication.run(MybatisTestApplication.class, args);
	}

	//Bean definition data source ①
	@Bean
	public DataSource dataSource() {
		return new EmbeddedDatabaseBuilder()
				.setType(EmbeddedDatabaseType.H2)
				.addDefaultScripts()
				.build();
	}

	//Bean definition PlatformTransactionManager②
	@Bean
	public PlatformTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource());
	}

	//Bean definition SqlSessionFactoryBean ③
	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() {
		SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
		sessionFactoryBean.setDataSource(dataSource());
		return sessionFactoryBean;
	}

** ① Data source ** Define a bean for the data source.

②PlatformTransactionManager Define a transaction manager bean.

③SqlSessionFactoryBean SqlSessionFactory is generated using SqlSessionFactoryBean. If you set the data source and issue SQL in the processing of MyBatis, from the data source specified here The connection is acquired.

DB access using MyBatis

-Creating a Mapper interface -Creating a mapping file

MyBatisMapper.java


package com.mybatis.test.domain;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

//By adding this annotation, it will be recognized as a Mapper interface by the program.
@Mapper
public interface MyBatisMapper {

	//For testing SELECT
	public PlayerEntity selectTest(String id);

	//For testing INSERT
	public void insertTest(@Param("id")String id, @Param("name")String name, @Param("age")String age);

	//For testing UPDATE
	public void updateTest(@Param("id")String id, @Param("name")String name);

	//For testing DELETE
	public void deleteTest(String id);
}

MyBatisMapper.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.mybatis.test.domain.MyBatisMapper">
	<!--id attribute is the method name defined in the Mapper interface-->
	<!--The parameterType attribute is the method argument class-->
	<!--resultType attribute is a class that maps search results-->
  	<select id="selectTest" parameterType="string" resultType="com.mybatis.test.domain.PlayerEntity">
  	  SELECT
  	   id,name,age
   	  FROM
   	   player
   	  WHERE
   	   id=#{id}
  	</select>

  	<insert id="insertTest" parameterType="string" >
  	  INSERT INTO
  	   player (id, name, age)
  	  VALUES
  	   (#{id}, #{name}, #{age})
  	</insert>

  	<update id="updateTest" parameterType="string">
  	 UPDATE
  	  player
  	 SET
  	  name=#{name}
  	 WHERE
  	  id=#{id}
  	</update>

  	<delete id="deleteTest" parameterType="string">
  	 DELETE FROM player WHERE id=#{id}
  	</delete>
</mapper>

** XML is in the same location as the folder where the Mapper interface is placed in src / main / resources. Place them with the same name! ** ** By doing this, MyBatis will automatically read the mapping file. **

Use of Mapper object

-Service class ・ Controller class ・ Entity class

Service


package com.mybatis.test.domain;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MyBatisService {

	@Autowired
	MyBatisMapper mapper;

	@Autowired
	PlayerRepository playerRepository;

	//Call the Mapper method that performs SELECT
	@Transactional
	public PlayerEntity selectTest(String id) {
		return mapper.selectTest(id);
	}

	//Call the Mapper method that performs INSERT
	@Transactional
	public void insertTest(String id, String name, String age) {
		mapper.insertTest(id, name, age);
	}

	//Call the Mapper method that performs UPDATE
	@Transactional
	public void updateTest(String id, String name) {
		mapper.updateTest(id, name);
	}

	//Call the Mapper method to do DELETE
	@Transactional
	public void deleteTest(String id) {
		mapper.deleteTest(id);
	}

Controller


package com.mybatis.test.domain;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MybatisController {

	@Autowired
	MyBatisService myBatisService;

	@GetMapping()
	public String index(Model model) {

		PlayerEntity playerService = new PlayerEntity();
		playerService = myBatisService.selectTest("004");
		model.addAttribute("play", playerService);
		myBatisService.insertTest("010", "XXXX", "65");
		myBatisService.updateTest("004", "SSSSSS");
		myBatisService.deleteTest("001");
		return "index";
	}
Omitted below

Entity


package com.mybatis.test.domain;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class PlayerEntity {

	@Id
	private String id;

	private String name;
	private String age;
getter,setter omitted

At the end

Next, I would like to make JOIN and SQL statements more complicated and play around with them.

Recommended Posts

Spring + MyBatis connection setting method
Spring + MyBatis connection setting method <table join>
JAVA DB connection method
Spring MyBatis @MapperScan Multiple
Spring RedisTemplate Config Timeout setting
Spring RestTemplate Config Timeout setting
Spring Security Usage memo Method security
Error in Spring database connection
Spring Boot External setting priority
Spring Boot DB connection pool
Spring boot controller method memo
Spring Boot + PostgreSQL error resolution method
I tried using Spring + Mybatis + DbUnit
[Java] Proxy setting method when starting Java
Implementation method for multi-data source with Spring boot (Mybatis and Spring Data JPA)