vulnerable! spring, which you can't learn, is integrated with MyBatis. The girl next door easily completed it and sent a login verification case!

Integration of spring and MyBatista in spring learning (1)

1. Integration of spring and MyBatista

1.1 integration process and ideas

1.1.1 Mybatis

As we all know, mybatis evolved from ibatis of Apache and is a persistence layer framework based on Java. Mybatis annotation 𞓜 xml file is used for configuration or original mapping.

Mybatis reference

1.1.2 thinking and process of mybatis and Spring integration

(1) Import related jar packages

1. Jars required by mybatis include:

  • ant-1.9.6.jar
  • ant-launcher-1.9.6.jar
  • asm-5.2.jar
  • cglib-3.2.5.jar
  • commons-logging-1.2.jar
  • javassist-3.22.0-CR2.jar
  • log4j-1.2.17.jar
  • log4j-api-2.3.jar
  • log4j-core-2.3.jar
  • mybatis-3.4.5.jar
  • ognl-3.1.15.jar
  • slf4j-api-1.7.25.jar
  • slf4j-log4j12-1.7.25.jar

2. jar package required by spring:

  • spring-bean.5.0.2.jar
  • spring-context-5.0.2.jar
  • spring-core-5.0.2.jar
  • spring-expression-5.0.2.jar
  • commons-logging-1.2.jar
  • aopalliance-1.0.jar
  • aspectjweaver-1.8.13.jar
  • spring-aop-5.0.2.jar
  • spring-aspects-5.0.2.jar
  • spring-jdbc-5.0.2.jar
  • spring-tx-5.0.2.jar

3. Middleware required for mybatis and Spring integration:

  • mybatis-spring-1.3.1.jar
  • mysql-connector-java-5.1.45-bin.jar
  • commons-dbcp2-2.2.0.jar
  • commons-pool2-2.5.0.jar

(2) Create persistent class

(3) Create sql mapping file

(4) Create Mybatis core profile

(5) Create data access layer interface

(6) Control layer

(7) Configure spring configuration file, configure data source, configure Mybatis factory, specify data source,

(8) Test class

1.2 integration case: login verification and registration

1.2.1 import relevant jar packages

The dependent jar packages of related projects have been packaged here

You can also click here to download relevant jar packages from the official website

1.2.2 project structure

1.2.3 create database and insert some data

CREATE DATABASE /*!32312 IF NOT EXISTS*/`testdata` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;

USE `testdata`;

/*Table structure for table `t_customer` */

DROP TABLE IF EXISTS `t_customer`;

CREATE TABLE `t_customer` (
  `ACCOUNT` int(10) unsigned NOT NULL,
  `CNAME` varchar(25) CHARACTER SET utf8mb4 DEFAULT NULL,

/*Data for the table `t_customer` */

insert  into `t_customer`(`ACCOUNT`,`PASSWORD`,`CNAME`) values 
(188207202,'123456','Four primary colors'),
(188207236,'123456','Zhang San'),
(188207237,'123456','Programmers who don't lose hair'),
(188207245,'123456','Lau Andy');

1.2.4 create com. In src directory xjh. loginByMybatis. Po package and add the persistence class myuser java.

package com.xjh.loginByMybatis.po;

public class MyUser {

    private Integer account;
    private String cname;
    private String password;

    public Integer getUid() {
        return account;

    public void setUid(Integer uid) {
        this.account = uid;

    public String getUname() {
        return cname;

    public void setUname(String uname) {
        this.cname = uname;

    public String getUpwd() {
        return password;

    public void setUpwd(String password) {
        this.password = password;

1.2.5 create com. In src directory xjh. Dao package and add the Sql mapping file usermapper xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="com.xjh.loginByMybatis.dao.userDao.UserDao">
    <!--according to uid Query a user-->
    <select id="findUserById" parameterType="Integer" resultType="com.xjh.loginByMybatis.po.MyUser">
        select * from T_CUSTOMER where ACCOUNT = #{account}
    <!--Add a user,{#uname} is mybatisindoor po. Attribute value of myuser -- >
    <insert id="addUser" parameterType="com.xjh.loginByMybatis.po.MyUser">
        insert into T_CUSTOMER (ACCOUNT,PASSWORD,CNAME) values(#{account},#{password},#{cname})

1.2.6 on COM xjh. Create the Mybatis configuration file in the Dao package, Mybatis config xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"
        <!--Location of mapping file-->
        <mapper resource="com/xjh/loginByMybatis/dao/UserMapper.xml"/>

1.2.7 on COM xjh. Dao package creates data access layer interface userdao java.

package com.xjh.loginByMybatis.dao.userDao;

import com.xjh.loginByMybatis.po.MyUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

public interface UserDao {
    MyUser findUserById(@Param(value = "account") Integer account);
    void addUser(MyUser user);

1.2.8 on COM xjh. Create the controller package under the loginbymbatis directory, and create the control class talkingwithoperator under the package java.

package com.xjh.loginByMybatis.controller;

import com.xjh.loginByMybatis.po.MyUser;
import org.springframework.stereotype.Controller;

import java.util.Scanner;

public class TalkingWithOperator {

    MyUser loginUser=new MyUser();
        try {
            new BufferedReader(new InputStreamReader(;
        } catch (IOException e) {
    int menu(){
        int key=0;
        System.out.println("===home page===");
        System.out.println("1.Sign in");
        System.out.println("3.sign out");
        while((key=(new Scanner(>3 || key<1){
            System.out.println("===>Beyond the selection range, please re select!");
        return key;
    private Object input(String tip){
        return (new Scanner(;

    MyUser login(){
        try {
            loginUser.setUid(Integer.parseInt(input("(1)account number:").toString().trim()));
            return loginUser;
        catch(Exception e){
            System.out.println("Wrong input! Please press any key to re-enter and press 0 to exit directly!");
            boolean exit_or_continue= ( (new Scanner( == 0 );
            return exit_or_continue ? null: login();

    MyUser register(String tip){
//        System.out.println(tip.length()<=0?"":"\n");
        if(tip!=null) {
            try {
                loginUser.setUid(Integer.parseInt(input("(1)account number:").toString()));
                loginUser.setUname(input("(2)full name:").toString().trim());
                String pwd = input("(4)Confirm password:").toString().trim();
                return pwd.equals(loginUser.getUpwd()) && pwd.matches("[0-9|a-zA-Z|_]{6,10}")
                        ? loginUser
                        : register("===>The password input before and after is inconsistent or does not conform to the password format (6-1 (alphanumeric or underlined)");
            } catch (Exception e) {
                System.out.println("Wrong input! Please press any key to re-enter and press 0 to exit directly!");
                boolean exit_or_continue = ((new Scanner( == 0);
                return exit_or_continue ? null : register("");
            System.out.println("====>Please press any key to re-enter and press 0 to exit directly!");
            boolean exit_or_continue = ((new Scanner( == 0);
            return exit_or_continue ? null : register("");

1.2.9 on COM xjh. loginByMybatis. Create the system data layer oriented control class talkingwithdb under the controller directory java.

package com.xjh.loginByMybatis.controller;

import com.xjh.loginByMybatis.dao.userDao.UserDao;
import com.xjh.loginByMybatis.po.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.Scanner;

public class TalkingWithDB {
    private UserDao userDao;
    private TalkingWithOperator two;

    public MyUser loginUser;
    public void star(TalkingWithOperator two){
        int item=0;
            switch (item){
                case 1:
                        System.out.println("===>Login status:");
                        System.out.println("          1."+loginUser.getUname());
                        System.out.println("          2."+(new Date()).toString());
                        System.out.print("    To log out, press any key:");
                        (new Scanner(;
                        for (int i=0;i<5;i++){
                            try {
                            } catch (InterruptedException e) {
                        try {
                        } catch (InterruptedException e) {
                case 2:register();break;
        System.out.println("see you late!");
   private void login(){
       MyUser user=two.login();
       MyUser item=userDao.findUserById(user.getUid());
       if(item!=null && user!=null  ){
                   "===>dear["+loginUser.getUname()+"]Welcome to login!":"===>Wrong account or password!");;
       if(loginUser==null && user==null){
           System.out.print((loginUser==null?"===>ID by["+user.getUid()+"]User does not exist!":"===>")+"To return to the main interface, press 0. To continue, press any key:");
           if (!(new Scanner("0")){
               System.out.printf("=>In that case, do you choose to log in with a different account or register an account?\n    [tip]To register, press 1. To change your account, press any key:");
               if(!(new Scanner("1")) login();
               else register();
   private void register(){
       MyUser user=two.register("");
       if(user!=null) {
          if( userDao.findUserById(user.getUid())!=null){
              System.out.printf("==>Account number is["+user.getUid()+"]User already exists!\n To re register, press 1 and press any key to return to the main menu:");
              if((new Scanner("1"))
              System.out.println("===>Registering, please wait");
              for(int i=0;i<5;i++){
                  try {Thread.sleep(500);}
                  catch (InterruptedException e) {e.printStackTrace();}
              System.out.printf("\n===>Account number is["+user.getUid()+"]User["+user.getUname()+"]Registration succeeded!");
              System.out.printf("\n==>To return to the main menu, press any key:");
                (new Scanner(;


1.2.10 create the configuration file ApplicationContext. In src directory xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <context:component-scan base-package="com.xjh.loginByMybatis.dao"/>
    <context:component-scan base-package="com.xjh.loginByMybatis.controller"/>
    <!--Configure data source-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/testData?characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value=""/>
        <property name="maxTotal" value="30"/>
        <property name="maxIdle" value="10"/>
        <property name="initialSize" value="5"/>
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    <tx:annotation-driven transaction-manager="txManager"/>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:com/xjh/loginByMybatis/dao/myBatis-config.xml"/>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xjh.loginByMybatis.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

1.2.11 write test classes on COM Create a text package in the loginbymbatis directory and add demotext java

package com.xjh.loginByMybatis.text;

import com.xjh.loginByMybatis.controller.TalkingWithDB;
import com.xjh.loginByMybatis.controller.TalkingWithOperator;
import org.springframework.context.ApplicationContext;

public class DemoText {

    public static class FistMyBatisTest {
        public static void main(String[] args) {
            ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
            TalkingWithOperator two=(TalkingWithOperator)applicationContext.getBean("talkingWithOperator");
            TalkingWithDB twDB=(TalkingWithDB)applicationContext.getBean("talkingWithDB");

1.3 summary

The first time I did this, I was very excited. I've done some before. I'm teaching in a book. I don't feel very exciting, but I don't feel very impulsive after finishing this. I heard that the sister next door has begun to integrate ssm again. It's exciting to think about it. Don't say it. I'll start looking for the sister next door again. Moda ~ I wish me success in chasing my sister!.

2. Prescription source code

2.1. Project extraction address:




Keywords: Java MySQL Mybatis Spring SSM

Added by DanDaBeginner on Thu, 17 Feb 2022 14:06:09 +0200