欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring框架和Mybatis框架工作原理

程序员文章站 2022-07-13 21:11:29
...

        Spring框架是一个轻量级的容器,用于管理业务相关对象的。核心功能主要为IOC,AOP,MVC。

  • IOC:控制反转,将对象的创建过程交给容器,让容器管理对象的生命周期如创建,初始化,销毁等。
  • AOP:面向切面编程,对关注点进行模块化,通过对某一功能点进行编程,在AOP的实现过程中,有静态代理和动态代理两种方式。
  • MVC:Spring MVC,Spring提供的基于mvc模式设计的web框架

        Mybatis框架不完全是一个ORM框架,是一个基于Java的持久层框架,Mybatis框架需要程序员自己编写Sql语句,不过mybatis可以通过注解或XML方式灵活配置要运行的Sql语句,并将Java对象和Sql语句映射生成最终执行的Sql,最后将sql执行的结果再映射生成Java对象。

        这次我们通过一个案例,且用注解方式来深刻了解一下这两个框架的工作原理:

  • 首先创建pojo包的User类
package pojo;

import org.springframework.stereotype.Component;

@Component("user")
public class User {

    private Integer id;
    private String name;
    private String password;
    private Integer age;
    private String email;
    private String telephone;

    public User() {
    }

    public User(Integer id, String name, String password, Integer age, String email, String telephone) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.age = age;
        this.email = email;
        this.telephone = telephone;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", telephone='" + telephone + '\'' +
                '}';
    }
}

  • 创建mapper包的UserMapper类
package mapper;

import java.util.List;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import pojo.User;

@Repository("userMapper")
@Mapper
public interface UserMapper {

    @Select("select * from user where email = #{email} and password = #{password}")
    User login(@Param("email")String email,@Param("password")String password);

    @Select("select * from User")
    List<User> queryList();

    @Select("select * from User where id = #{id}")
    User queryById(Integer id);

    @Update("update User set name = #{name} ,password = #{password},age = #{age},email = #{email} where id = #{id}")
    boolean updateByPrimaryKey(User bean);

    @Insert("insert into User (name,password,age,email,telephone) values(#{name},#{password},#{age},#{email},#{telephone})")
    User add(User bean);
}

  • 创建service包的UserService类
package service;

import org.apache.ibatis.annotations.Param;
import pojo.User;
import java.util.List;

public interface UserService {

    List<User> queryList();

    User queryById(Integer id);

    boolean updateByPrimaryKey(User bean);

    User login(@Param("email")String email,@Param("password")String password);

    User add(User bean);
}

  • 创建service.impl包的UserServiceImpl类
package service.impl;

import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.User;
import service.UserService;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> queryList() {
        return userMapper.queryList();
    }

    @Override
    public User queryById(Integer id) {
        return userMapper.queryById(id);
    }

    @Override
    public boolean updateByPrimaryKey(User bean) {
        return userMapper.updateByPrimaryKey(bean);
    }

    @Override
    public User login(String email, String password) {
        return userMapper.login(email, password);
    }

    @Override
    public User add(User bean) {
        return userMapper.add(bean);
    }
}
  • jdbc.properties
driver=com.mysql.cj.jdbc.Driver<!--mysql 8.0以上版本才需要加cj-->
url=jdbc:mysql://localhost:port/DatabaseName?serverTimezone=UTC
user=用户
password=密码
  • 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:mybatis="http://mybatis.org/schema/mybatis-spring"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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://mybatis.org/schema/mybatis-spring
                           http://mybatis.org/schema/mybatis-spring.xsd
                           http://www.springframework.org/schema/aop
                           https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 支持注解 -->
    <context:annotation-config/>

    <context:component-scan base-package="controller"/>

    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 数据库信息 -->
    <bean  id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="${driver}"/>

        <property name="url" value="${url}"/>

        <property name="username" value="root"/>

        <property name="password" value="${password}"/>

    </bean>
    
    <aop:config>

        <aop:pointcut id="pcUuser" expression="execution(* cn.edu.lingnan.service.impl.*.*(..))"/>

    </aop:config>

    <!-- define the SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />

        <property name="configLocation" value="mybatis-config.xml" />

    </bean>

    <mybatis:scan base-package="mapper"/>

</beans>
  • 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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>

    <typeAliases>
        <package name="pojo"/>
    </typeAliases>

    <mappers>
        <package name="mapper"/>
    </mappers>
</configuration>
  • 创建测试类AppTest类
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.User;
import service.UserService;
import java.util.List;

public class AppTest {
    @Test
    public void test1(){

            ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

            UserService userService = ctx.getBean("userService", UserService.class);

            List<User> bean = userService.queryList();

            System.out.println(bean);
    }
}

相关标签: Sping框架