伤不起!你学不会的spring与MyBatis整合,隔壁妹子轻松完成了还送了一个登录验证案例!

Posted 四原色

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了伤不起!你学不会的spring与MyBatis整合,隔壁妹子轻松完成了还送了一个登录验证案例!相关的知识,希望对你有一定的参考价值。

spring学习之 spring与MyBatista整合(一)

1.spring与MyBatista整合

1.1整合过程及其思路

1.1.1 Mybatis

总所周知,mybatis是Apache的ibatis演化而来的,是基于Java的持久层框架。mybatis注解||xml文件用于配置或原始映射。

Mybatis参考资料

1.1.2 Mybatis与Spring整合的思路过程

(1)导入相关jar包

1.Mybatis所需的jar包括:

  • 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.Spring所需要的jar包:

  • 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.Mybatis与Spring整合所需中间件:

  • 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)创建持久化类

(3)创建sql映射文件

(4)创建Mybatis核心配置文件

(5)创建数据访问层接口

(6)控制层

(7)配置spring配置文件,配置数据源,配置Mybatis工厂,指定数据源,

(8)测试类

1.2整合案例:登录验证和注册

1.2.1 导入相关jar包

这里已经打包好了相关项目依赖jar包

也可以点击此处去官网下载相关jar包

1.2.2项目结构

1.2.3创建数据库并插入一些数据

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,
  `PASSWORD` varchar(25) CHARACTER SET utf8mb4 DEFAULT NULL,
  `CNAME` varchar(25) CHARACTER SET utf8mb4 DEFAULT NULL,
  PRIMARY KEY (`ACCOUNT`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `t_customer` */

insert  into `t_customer`(`ACCOUNT`,`PASSWORD`,`CNAME`) values 
(188207201,'123456',NULL),
(188207202,'123456','四原色'),
(188207236,'123456','张三'),
(188207237,'123456','不掉发的程序员'),
(188207245,'123456','刘德华');

1.2.4 在src目录下创建com.xjh.loginByMybatis.po包,并添加持久化类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 在src目录下创建com.xjh.dao包,并添加Sql映射文件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.xjh.loginByMybatis.dao.userDao.UserDao">
    <!--根据uid查询一个用户-->
    <select id="findUserById" parameterType="Integer" resultType="com.xjh.loginByMybatis.po.MyUser">
        select * from T_CUSTOMER where ACCOUNT = #{account}
    </select>
    <!--添加一个用户,{#uname}为myBatisInDoor.po.MyUser的属性值-->
    <insert id="addUser" parameterType="com.xjh.loginByMybatis.po.MyUser">
        insert into T_CUSTOMER (ACCOUNT,PASSWORD,CNAME) values(#{account},#{password},#{cname})
    </insert>
</mapper>

1.2.6 在com.xjh.dao 包中创建Mybatis配置文件,myBatis-config.xml。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <!--映射文件的位置-->
        <mapper resource="com/xjh/loginByMybatis/dao/UserMapper.xml"/>
    </mappers>
</configuration>

1.2.7 在com.xjh.dao 包创建数据访问层接口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;

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

1.2.8 在com.xjh.loginByMybatis目录下创建controller包,并在该包下创建用户与系统交互的控制类TalkingWithOperator.java。


package com.xjh.loginByMybatis.controller;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

@Controller("talkingWithOperator")
public class TalkingWithOperator {

    MyUser loginUser=new MyUser();
    TalkingWithOperator(){
        System.out.print("===Welcome===");
        try {
            new BufferedReader(new InputStreamReader(System.in)).readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    int menu(){
        int key=0;
        System.out.println("===首页===");
        System.out.println("1.登录");
        System.out.println("2.注册");
        System.out.println("3.退出");
        System.out.println("==========");
        while((key=(new Scanner(System.in).nextInt()))>3 || key<1){
            System.out.println("===>超出选择范围,请重新选择!");
        }
        return key;
    }
    private Object input(String tip){
        System.out.print(tip);
        return (new Scanner(System.in)).nextLine();
    }

    MyUser login(){
        try {
            loginUser.setUid(Integer.parseInt(input("(1)账号:").toString().trim()));
            loginUser.setUpwd(input("(2)密码:").toString());
            return loginUser;
        }
        catch(Exception e){
            System.out.println("输入有误!重新输入请按任意键,直接退出请按0!");
            boolean exit_or_continue= ( (new Scanner(System.in).nextInt()) == 0 );
            return exit_or_continue ? null: login();
        }
    }

    MyUser register(String tip){
        System.out.printf(tip);
//        System.out.println(tip.length()<=0?"":"\\n");
        if(tip!=null) {
            try {
                loginUser.setUid(Integer.parseInt(input("(1)账号:").toString()));
                loginUser.setUname(input("(2)姓名:").toString().trim());
                System.out.println("-----------------------------------");
                loginUser.setUpwd(input("(3)密码:").toString().trim());
                String pwd = input("(4)确认密码:").toString().trim();
                return pwd.equals(loginUser.getUpwd()) && pwd.matches("[0-9|a-zA-Z|_]{6,10}")
                        ? loginUser
                        : register("===>前后密码输入不一致或不符合密码规定格式(6-1位字母数字或下划线)");
            } catch (Exception e) {
                System.out.println("输入有误!重新输入请按任意键,直接退出请按0!");
                boolean exit_or_continue = ((new Scanner(System.in).nextInt()) == 0);
                return exit_or_continue ? null : register("");
            }
        }
        else{
            System.out.println("====>重新输入请按任意键,直接退出请按0!");
            boolean exit_or_continue = ((new Scanner(System.in).nextInt()) == 0);
            return exit_or_continue ? null : register("");
        }
    }
}

1.2.9 在com.xjh.loginByMybatis.controller目录下创建系统面向数据层的控制类TalkingWithDB.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;

@Controller("talkingWithDB")
public class TalkingWithDB {
    @Qualifier("userDao")
    @Autowired
    private UserDao userDao;
    @Autowired
    private TalkingWithOperator two;

    public MyUser loginUser;
    TalkingWithDB(){}
    public void star(TalkingWithOperator two){
        int item=0;
        while((item=two.menu())!=3){
            switch (item){
                case 1:
                    login();
                    if(loginUser!=null){
                        System.out.println("===>登录状态:");
                        System.out.println("          1."+loginUser.getUname());
                        System.out.println("          2."+(new Date()).toString());
                        System.out.print("    退出登录请按任意键:");
                        (new Scanner(System.in)).nextLine();
                        for (int i=0;i<5;i++){
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.print(".");
                        }
                        System.out.printf("\\n===>用户:"+loginUser.getUname()+"已退出!");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        loginUser=null;
                    }
                    break;
                case 2:register();break;
            }
        }
        System.out.println("see you late!");
    }
   private void login(){
       System.out.println("----------LOGIN----------");
        loginUser=null;
       MyUser user=two.login();
       MyUser item=userDao.findUserById(user.getUid());
       if(item!=null && user!=null  ){
           loginUser=(user.getUpwd().equals(userDao.findUserById(user.getUid()).getUpwd())?
                   userDao.findUserById(user.getUid()):
                   null);
           System.out.println(loginUser!=null?
                   "===>亲爱的["+loginUser.getUname()+"]欢迎登录!":"===>账号或密码输入错误!");;
       }
       if(loginUser==null && user==null){
           System.out.print((loginUser==null?"===>ID为["+user.getUid()+"]的用户不存在!":"===>")+"返回主界面请按0,继续请按任意键:");
           if (!(new Scanner(System.in)).next().equals("0")){
               System.out.printf("=>既然如此,请问你选择换账号登录还是注册一个账号呢?\\n    [tip]注册请按1,换账号请按任意键:");
               if(!(new Scanner(System.in)).next().equals("1")) login();
               else register();
           }
       }
   }
   private void register(){
       System.out.println("----------REGISTER----------");
       MyUser user=two.register("");
       if(user!=null) {
          if( userDao.findUserById(user.getUid())!=null){
              System.out.printf("==>账号为["+user.getUid()+"]的用户已存在!\\n重新注册请按1,任意键返回主菜单:");
              if((new Scanner(System.in)).nextLine().trim().equals("1"))
                  register();
          }
           else{
              userDao.addUser(user);
              System.out.println("===>正在注册,请稍后");
              for(int i=0;i<5;i++){
                  System.out.print(".");
                  try {Thread.sleep(500);}
                  catch (InterruptedException e) {e.printStackTrace();}
              }
              System.out.printf("\\n===>账号为["+user.getUid()+"]的用户["+user.getUname()+"]注册成功!");
              System.out.printf("\\n==>返回主菜单请按任意键:");
                (new Scanner(System.in)).nextLine();

          }
       }
   }
}

1.2.10 在src目录下创建配置文件applicationContext.xml。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd">
    <context:component-scan base-package="com.xjh.loginByMybatis.dao"/>
    <context:component-scan base-package="com.xjh.loginByMybatis.controller"/>
    <!--配置数据源-->
    <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>
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <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>

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

1.2.11 编写测试类,在com.loginByMybatis目录下创建text包,并添加DemoText.java

package com.xjh.loginByMybatis.text;

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

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");
            twDB.star(two);
        }
    }
}

1.3总结

第一次做这种,就是很兴奋的样子。之前也做过一些,就是在做书上教的,感觉不是很刺激,但是做完这个又感觉不是特别冲动,听说隔壁妹子已经又开始整合ssm了,想想就刺激,不说了,赶紧又要开始追寻隔壁妹子的一天了,么么哒~大家祝我追妹成功!。

2.开方源代码

2.1. 项目提取地址:https://download.csdn.net/download/qq_44140450/18309097

 

 

 

以上是关于伤不起!你学不会的spring与MyBatis整合,隔壁妹子轻松完成了还送了一个登录验证案例!的主要内容,如果未能解决你的问题,请参考以下文章

Redis之实战篇(与Mybatis整合)

Spring整合Junit

Mybatis与Spring的整合

mybatis与spring整合

Spring与MyBatis整合

Mybatis 与 spring 整合