Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Mybatis for Spring Boot data access

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the example analysis of Mybatis for Spring Boot data access, which is very detailed and has certain reference value. Friends who are interested must finish it!

First, what is MyBatis's excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping, avoiding almost all JDBC code and manually setting parameters and getting the result set can use simple XML or annotations for configuration and native Map to map the interface and Java's POJOs (Plain Old Java Objects, ordinary Java objects) into record databases, data sources, database connection pooling, JDBC, JDBC implementations in the database?

The bridge between JDBC:Java and relational database is a specification, not an implementation. Different types of databases need to have their own JDBC implementation

Data source: including database connection pool, connection pool management. The common ones are C3P0, HikariDataSoiurce, Druid and so on.

Connection pool: create some database connections in advance, put them in the connection pool, take it from the connection pool when you use it, and put it back into the connection pool after use.

Connection pool management: create database connections, manage database connections

JDBC implementation: MySQL JDBC implementation, Oracle JDBC implementation and other implementations

MyBatis encapsulates JDBC

Second, integrate MyBatis

We create the spring-boot-07-data-mybatis project based on the previously created project spring-boot-06-data-druid

1) introduce MyBatis dependency

Org.mybatis.spring.boot

Mybatis-spring-boot-starter

2.1.1

2) introduce other dependencies

Org.springframework.boot

Spring-boot-starter-web

Mysql

Mysql-connector-java

Runtime

Io.springfox

Springfox-swagger2

2.9.2

Io.springfox

Springfox-swagger-ui

2.9.2

Com.alibaba

Druid

1.1.21

3) dependence graph

Third, use MyBatis1. Prepare the script DROP TABLE IF EXISTS `department` to create the department table

CREATE TABLE `department` (

`id`int (11) NOT NULL AUTO_INCREMENT

`department_ name` varchar (255) DEFAULT NULL

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;2.application.yml automatically executes the script initialization-mode: always

Schema:

-classpath:department.sql

After executing once, comment initialization-mode

# initialization-mode: always3. Create the department entity class package com.jackson0714.springboot.entity

Public class Department {private Long id; private String departmentName

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

Public Long getId () {return id;}

Public void setDepartmentName (String departmentName) {this.departmentName = departmentName;}

Public String getDepartmentName () {return departmentName;}} 4. Create a Mapper mapping class and annotate the SQL on the method

Add, delete, change and search, everything you need is here:

@ Mapperpublic interface DepartmentMapper {

Select ("select * from department") List getAllDepartment ()

@ Select ("select * from department where id=# {id}") Department getDepartmentById (Long id)

@ Delete ("delete from department where id=# {id}") int deleteDepartment (Long id)

@ Insert ("insert into department (department_name) values (# {departmentName})") int createDepartment (String departmentName)

Update ("update department set department_name=# {departmentName} where id=# {id}") int updateDepartmentById (Long id, String departmentName);} 5. Create a MyBatis configuration class

Add custom configuration: if the field name of the table is in underscore format, change to hump naming format

@ org.springframework.context.annotation.Configurationpublic class MyBatisConfig {@ Bean public ConfigurationCustomizer configurationCustomizer () {return new ConfigurationCustomizer () {@ Override public void customize (Configuration configuration) {/ / if the field name of the table is in underscore format, change to hump naming format configuration.setMapUnderscoreToCamelCase (true);}};}} 6. Create DepartmentController

@ Api (value = "DepartmentController", description = "department controller") @ RequestMapping ("/ v1/client") @ RestControllerpublic class DepartmentController {

@ Autowired DepartmentMapper departmentMapper

@ ApiOperation (value = "1. Query all departments") @ GetMapping ("/ dept/getAllDepartment") public List getAllDepartment () {return departmentMapper.getAllDepartment ();}

@ ApiOperation (value = "2. Query a department according to id") @ ApiImplicitParams ({@ ApiImplicitParam (name = "id", value = "department to be queried")}) @ GetMapping ("/ dept/ {id}") public Department getDepartmentById (@ PathVariable Long id) {return departmentMapper.getDepartmentById (id);}

@ ApiOperation (value = "3. New department") @ ApiImplicitParams ({@ ApiImplicitParam (name = "name", value = "department name") @ PostMapping ("/ dept/create") public int createDepartment (@ RequestParam String name) {return departmentMapper.createDepartment (name);}

@ ApiOperation (value = "4. Delete departments according to id") @ ApiImplicitParams ({@ ApiImplicitParam (name = "id", value = "departments to be deleted")}) @ PostMapping ("/ dept/delete") public int deleteDepartment (@ RequestParam Long id) {return departmentMapper.deleteDepartment (id);}

@ ApiOperation (value = "5. Update department name according to id ") @ ApiImplicitParams ({@ ApiImplicitParam (name =" id ", value =" department id to be updated "), @ ApiImplicitParam (name =" name ", value =" department name to be updated ")}) @ PostMapping (" / dept/update ") public int updateDepartmentById (@ RequestParam Long id, @ RequestParam String name) {return departmentMapper.updateDepartmentById (id, name);}}

Use Swagger to test

Fourth, use MyBatis1. File structure

two。 Script SET FOREIGN_KEY_CHECKS=0 to create the user table

-Table structure for user---DROP TABLE IF EXISTS `user` CREATE TABLE `user` (`user_ id` int (11) NOT NULL AUTO_INCREMENT COMMENT 'primary key ID', `user_ name` varchar' user name', `password` varchar 'COLLATE utf8mb4_bin NOT NULL, `salt` varchar' COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'random salt', `nickName` varchar 'COLLATE utf8mb4_bin NOT NULL COMMENT' user name', `phone`varchar (20) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'mobile phone number' `avatar` varchar (255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'avatar`, `avatar` varchar (32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT' Mini Program OpenId', `lock_ 'char (1) COLLATE utf8mb4_bin DEFAULT' 0' COMMENT'0-normal 9-Lock', `Lock 'char (1) COLLATE utf8mb4_bin DEFAULT' 0' COMMENT'0-normal 1-Delete', `update_ time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'creation time', `update_ time`timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time', PRIMARY KEY (`user_ id`), KEY `user_wx_ openid` (`mini_ openId`), KEY `user_idx1_ username` (`user_ name`) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT=' user table' 3. Insert a piece of User data

INSERT INTO user (user_name, password, nick_name, phone) values ("jackson0714", "123", "Wukong chat Architecture", "123456") 4. Create the User entity class package com.jackson0714.springboot.entity

Import lombok.Data

Import java.sql.Timestamp

@ Datapublic class User {

Private Long userId; private String userName; private String password; private String salt; private String nickName; private String phone; private String avatar; private String miniOpenId; private String openId; private Boolean lockFlag; private Boolean delFlag; private Timestamp createTime; private Timestamp updateTime;}

Need to install the Lombok plug-in

Need to introduce Lombok dependency

Org.projectlombok

Lombok

1.18.12

Provided

5. Create a UserMapper interface / / @ Mapper or MapperScan that calls the User method to assemble the interface scan into the assembly container

Public interface UserMapper {

User getUserById (Long userId)

} 6. Create a mapping file between interface methods and SQL scripts

SELECT * FROM user WHERE user_id=# {userId}

7. Create the UserController file @ Api (value = "UserController", description = "user controller") @ RequestMapping ("/ v1/client") @ RestControllerpublic class UserController {

@ Autowired UserMapper userMapper

@ ApiOperation (value = "1. Query a user according to id") @ ApiImplicitParams ({@ ApiImplicitParam (name = "user to be queried", value = "user to be queried")}) @ GetMapping ("/ emp/ {userId}") public User getUser (@ PathVariable ("userId") Long userId) {return userMapper.getUserById (userId);}} 8. Add the MapperScan annotation @ MapperScan (value = "com.jackson0714.springboot.mapper") @ SpringBootApplicationpublic class Springboot07DataMybatisApplication {public static void main (String [] args) {SpringApplication.run (Springboot07DataMybatisApplication.class, args);}} 9. Test on Swagger

10. View Druid Monitoring

Code download:

Https://github.com/Jackson0714/study-spring-boot.git

The above is all the contents of the article "sample Analysis of Mybatis for Spring Boot data access". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report