Spring整合Mybatis附加實現案例

前言

本文圍繞Spring整合Mybatis,實現用戶的登陸驗證java

1、環境搭建

1.使用環境

JDK 11
MySQL 8
Maven 3.6.3

2.pom.xml配置(所需依賴,資源導入)

<dependencies>
       <!--單元測試-->
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.12</version>
       </dependency>
       <!--包含 spring 核心包-->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-webmvc</artifactId>
           <version>5.2.8.RELEASE</version>
       </dependency>
       <!--c3p0-->
       <dependency>
           <groupId>com.mchange</groupId>
           <artifactId>c3p0</artifactId>
           <version>0.9.5.5</version>
       </dependency>
       <!--mysql驅動-->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.19</version>
       </dependency>
       <!--mybatis-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.2</version>
       </dependency>
       <!-- mybatis與spring整合的jar包-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis-spring</artifactId>
           <version>2.0.3</version>
       </dependency>
       <!--日誌-->
       <dependency>
           <groupId>log4j</groupId>
           <artifactId>log4j</artifactId>
           <version>1.2.17</version>
       </dependency>
       <!--aop-->
       <dependency>
           <groupId>org.aspectj</groupId>
           <artifactId>aspectjweaver</artifactId>
           <version>1.8.9</version>
       </dependency>
       <!--jdk11以上版本javax.annotation.Resource不存在,須要手動引入後才能使用@Resource註解-->
       <dependency>
           <groupId>javax.annotation</groupId>
           <artifactId>javax.annotation-api</artifactId>
           <version>1.2</version>
       </dependency>
       <!--spring-jdbc-->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-jdbc</artifactId>
           <version>5.2.8.RELEASE</version>
       </dependency>
       <!--lombok-->
       <dependency>
           <groupId>org.projectlombok</groupId>
           <artifactId>lombok</artifactId>
           <version>1.18.10</version>
       </dependency>
   </dependencies>

   <build>
       <!--資源導入問題-->
       <resources>
           <resource>
               <directory>src/main/resources</directory>
           </resource>
           <resource>
               <directory>src/main/java</directory>
               <includes>
                   <include>**/*.xml</include>
                   <include>**/*.properties</include>
                   <include>**/*.tld</include>
               </includes>
               <filtering>false</filtering>
           </resource>
       </resources>
   </build>

3.properties文件

db.properties
注:MySQL 8 須要添加時區設置mysql

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
jdbc.username=root
jdbc.password=125803

log4j.propertiesweb

#將等級爲DEBUG的日誌信息輸出到console和file這兩個目的地,console和file的定義在下面的代碼
log4j.rootLogger=DEBUG,console,file
#控制檯輸出的相關設置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件輸出的相關設置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/test.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日誌輸出級別
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

t_user表結構
spring

4.spring配置(含aop,tx配置)

<?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:aop="http://www.springframework.org/schema/aop"
       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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--自動裝配,掃描包的範圍-->
    <context:component-scan base-package="com.wang"/>
    <!--加載properties配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--aop-->
    <aop:aspectj-autoproxy/>
    <!--配置c3p0數據源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--配置事務管理器-->
    <bean id="txManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--設置事務加強-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--aop切面-->
    <aop:config>
        <aop:pointcut id="servicePointcut" expression="execution(* com.wang.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/>
    </aop:config>
    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/wang/dao/*.xml"/>
    </bean>
    <!--配置掃描器-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--掃描全部映射接口類-->
        <property name="basePackage" value="com.wang.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

5.mybatis配置

<?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>
    <!--log4j,駝峯命名轉換-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--定義別名-->
    <typeAliases>
        <package name="com.wang.pojo"/>
    </typeAliases>
</configuration>

6.測試

(1).實體類(pojo)sql

import lombok.Data;
@Data
public class User {
    private int userId;
    private String userName;
    private String userPassword;
}

(2).持久層(dao)express

import com.wang.pojo.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
    @Select("select user_name as userName,user_password as userPassword from mybatis.t_user")
    List<User> getUserList();
}

(3).業務層(service)apache

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserService {
    @Resource
    private UserMapper mapper;
    public List<User> getUserList(){
        return mapper.getUserList();
    }
}

(4).控制層(controller)api

import javax.annotation.Resource;
import java.util.List;
@Controller
public class UserController {
    @Resource
    private UserService service;
    public List<User> getUserList(){
        return service.getUserList();
    }
}

(5).運行測試mybatis

public class Start {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = (UserController) context.getBean("userController");
        List<User> userList = userController.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

(6).測試結果:可以查詢並輸出,說明整合完成
mvc

2、使用Spring,Mybatis實現用戶登陸驗證

1.持久層(dao)

功能說明:
  查詢用戶使用用戶名是否存在,密碼是否正確
userMapper

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
    User queryUserByName(@Param("userName") String name);
}

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.wang.dao.UserMapper">
    <sql id="query-user">
        <if test="userName != null">
            user_name = #{userName}
        </if>
    </sql>
    <select id="queryUserByName" resultType="user">
        select * from mybatis.t_user
        <where>
            <include refid="query-user"></include>
        </where>
    </select>
</mapper>

2.新建實體類

該實體類將最後的結果輸出顯示給用戶

import lombok.Data;

@Data
public class ResultCode {
    private int code;
    private String msg;
}

3.業務層(service)

功能說明:
  1.獲取用戶輸入的用戶名和密碼
  2.判斷輸入是否爲空
  3.判斷輸入用戶名是否存在
  3.若用戶存在,判斷密碼是否正確
  3.若用戶存在,密碼正確,登陸成功!

import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class UserService {
    @Resource
    private UserMapper mapper;
    public ResultCode login(String name, String pwd){
        ResultCode res = new ResultCode();
        User user = mapper.queryUserByName(name);
        if (name == "" || pwd == ""){
            res.setCode(500);
            res.setMsg("用戶名或密碼爲空,請從新輸入!");
            return res;
        }
        if (user == null){
            res.setCode(500);
            res.setMsg("用戶不存在!");
            return res;
        }
        if (!pwd.equals(user.getUserPassword())){
            res.setCode(500);
            res.setMsg("密碼錯誤!");
            return res;
        }
        res.setCode(200);
        res.setMsg("登陸成功!");
        return res;
    }
}

4.控制層(controller)

功能介紹
  調用業務層功能

import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
@Controller
public class UserController {
    @Resource
    private UserService service;
    public ResultCode login(String name, String pwd){
        return service.login(name, pwd);
    }
}

5.登陸測試

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Start {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = (UserController) context.getBean("userController");
        ResultCode res = userController.login("admin", "123456");
        System.out.println(res);
    }
}

總結

道阻且長,行則將至!
相關文章
相關標籤/搜索