mybatis-plus has no spring framework

I am doing network programming course design, I plan to sew mybatis-plus into it, and then use springboot to sew mybatis-plus, and then I searched for a long time, and found the no-spring usage method of mybatis-plus on gitee: Official address
: https ://gitee.com/baomidou/mybatis-plus-samples/tree/master/mybatis-plus-sample-no-spring
General code address after civilianization:
https://github.com/like-wen/mybatis -plus-only.git
But the official use case uses h2 when the database connection is started, and my example has changed:
1. Changed to the commonly used mysql-connector-java
2. Added mapper.xml
mainly for this Several files:
insert image description here
test insert results:
insert image description here

Main code:

rely:

 <dependencies>
        <!-- 导入mybatis-plus相关依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!-- 引入lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>

        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.23</version>
        </dependency>

    </dependencies>

//User and the like are generated with the plug-in MybatisX, which can be used to directly generate
User

package org.example.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;

/**
 * 
 * @TableName user
 */
@TableName(value ="user")
@Data
public class User implements Serializable {
    
    
    /**
     * 
     */
    @TableId(type = IdType.AUTO)
    private Integer id;

    /**
     * 
     */
    private String name;

    /**
     * 
     */
    private String password;

    /**
     * 
     */
    private Date onlineTime;

    /**
     * 
     */
    private Date createTime;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;

    @Override
    public boolean equals(Object that) {
    
    
        if (this == that) {
    
    
            return true;
        }
        if (that == null) {
    
    
            return false;
        }
        if (getClass() != that.getClass()) {
    
    
            return false;
        }
        User other = (User) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
            && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword()))
            && (this.getOnlineTime() == null ? other.getOnlineTime() == null : this.getOnlineTime().equals(other.getOnlineTime()))
            && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()));
    }

    @Override
    public int hashCode() {
    
    
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
        result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode());
        result = prime * result + ((getOnlineTime() == null) ? 0 : getOnlineTime().hashCode());
        result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode());
        return result;
    }

    @Override
    public String toString() {
    
    
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", name=").append(name);
        sb.append(", password=").append(password);
        sb.append(", onlineTime=").append(onlineTime);
        sb.append(", createTime=").append(createTime);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

UserMapper

package org.example.mapper;

import org.example.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
* @author 李可文
* @description 针对表【user】的数据库操作Mapper
* @createDate 2022-12-02 20:29:17
* @Entity org.example.entity.User
*/
public interface UserMapper extends BaseMapper<User> {
    
    

}


NoSpring

package org.example;


import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.example.entity.User;
import org.example.mapper.UserMapper;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;


public class NoSpring {
    
    

    private static SqlSessionFactory sqlSessionFactory = initSqlSessionFactory();

    public static void main(String[] args) {
    
    
        //初始化
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
    
    
            //创建mapper对象
            UserMapper mapper = session.getMapper(UserMapper.class);
            //创建user对象,并赋值
            User user = new User();
            user.setPassword("123");
            user.setName("lkw");
            //插入
            mapper.insert(user);
            System.out.println("结果: " + mapper.selectById(user.getId()));
        }
    }

    //工厂方法
    public static SqlSessionFactory initSqlSessionFactory() {
    
    
        DataSource dataSource = dataSource();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("Production", transactionFactory, dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration(environment);
        //在这里添加Mapper
        configuration.addMapper(UserMapper.class);
        configuration.setLogImpl(StdOutImpl.class);
        return new MybatisSqlSessionFactoryBuilder().build(configuration);
    }

    //连接进行
    public static DataSource dataSource() {
    
    
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriverClass(com.mysql.jdbc.Driver.class);
        dataSource.setUrl("jdbc:mysql://localhost:3306/course?serverTimezone=GMT%2B8");
        dataSource.setUsername("root");
        dataSource.setPassword("148963");
        return dataSource;
    }

}

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="org.example.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="org.example.entity.User">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="name" column="name" jdbcType="VARCHAR"/>
            <result property="password" column="password" jdbcType="VARCHAR"/>
            <result property="onlineTime" column="online_time" jdbcType="TIMESTAMP"/>
            <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
    </resultMap>

    <sql id="Base_Column_List">
        id,name,password,
        online_time,create_time
    </sql>
</mapper>

sql

/*
 Navicat Premium Data Transfer

 Source Server         : mysql
 Source Server Type    : MySQL
 Source Server Version : 80029
 Source Host           : localhost:3306
 Source Schema         : course

 Target Server Type    : MySQL
 Target Server Version : 80029
 File Encoding         : 65001

 Date: 02/12/2022 22:05:01
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `online_time` datetime NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `create_time` datetime NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'wl', 'wl', '2022-11-09 21:56:23', '2022-11-09 21:56:03');
INSERT INTO `user` VALUES (2, 'gmh', 'gmh', '2022-11-09 21:56:26', '2022-11-09 21:56:08');
INSERT INTO `user` VALUES (3, 'lkw', 'lkw', '2022-11-09 21:56:28', '2022-11-09 21:56:11');
INSERT INTO `user` VALUES (4, 'xy', 'xy', '2022-11-09 21:56:32', '2022-11-09 21:56:14');
INSERT INTO `user` VALUES (6, 'lkw', NULL, NULL, NULL);
INSERT INTO `user` VALUES (7, 'lkw', '123', NULL, NULL);
INSERT INTO `user` VALUES (8, 'lkw', '123', NULL, NULL);

SET FOREIGN_KEY_CHECKS = 1;

おすすめ

転載: blog.csdn.net/m0_52070517/article/details/128155303