search
HomeJavajavaTutorialDetailed explanation of the code example of springboot integrating mybatis

This article mainly introduces the example code of springboot integrating mybatis. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

Please refer to the previous chapter for how to configure the web project with springboot, and integrate mybatis on this basis.

Add mybatis dependencies in the pom file:

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

Add mysql driver:

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
  </dependency>

Add druid and fastjson dependencies, use Alibaba druid connection pool

  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.0.28</version>
  </dependency>
  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.30</version>
  </dependency>

Configure the data source in application.yml:

spring:
  datasource:
    name: test
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: 111111
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select &#39;x&#39;
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20

Set the mapper and model scan paths of mybatis:

mybatis:
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: com.yingxinhuitong.demo.model
#更多配置请参见:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

Next we create new userMapper.xml, UserEntity and UserDao:

UserEntity.class

package com.yingxinhuitong.demo.model;

/**
 * Created by jack on 2017/4/20.
 */
public class UserEntity {
 private Long id;
 private String username;
 private String password;

 public Long getId() {
  return id;
 }

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

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }
}

UserDao

package com.yingxinhuitong.demo.dao;

import com.yingxinhuitong.demo.model.UserEntity;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * Created by jack on 2017/4/20.
 */
@Mapper
public interface UserDao {
 List<UserEntity> searchAll();
}

UserMapper.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.yingxinhuitong.demo.dao.UserDao" >
 <!-- 字段与实体的映射 -->
 <resultMap id="BaseResultMap" type="com.yingxinhuitong.demo.model.UserEntity">
  <id column="id" property="id" jdbcType="BIGINT" />
  <result column="username" property="username" jdbcType="VARCHAR" />
  <result column="password" property="password" jdbcType="VARCHAR" />
 </resultMap>
 <!-- 根据条件查询,全部 -->
 <select id="searchAll" resultMap="BaseResultMap">
  select * from tab_user
 </select>

</mapper>

Create a controller, inject it into UserDao, and test whether you can query the data:

@RestController
public class TestController {

 @Resource
 UserDao userDao;

 @RequestMapping("/getusers")
 public String test() {
  List<UserEntity> users = userDao.searchAll();
  String usersJson = JSON.toJSONString(users);
  return usersJson;
 }
}

Run Application.class, access: localhost:9000/demo/getusers after successful startup, the output content is as follows:

The code is as follows:

[{"id": 1,"password":"000000","username":"test"},{"id":2,"password":"111111","username":"test1"},{"id":3, "password":"222222","username":"test2"}]

At this point, springboot has completed the integration of mybatis.

The above is the detailed content of Detailed explanation of the code example of springboot integrating mybatis. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor