Mybatis 的基本使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZQ741552720/article/details/79520757

mybatis的基本使用


mybatis一般可使用两种配置方式,一种代理方式,一种非代配置

  • 数据库表字段
    设计
  • 需要的jar
    这里写图片描述
  • 包结构
    这里写图片描述

  • 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>
    <!--
     properties:一般用来读取资源文件
    -->
    <properties resource="jdbc.properties" />
    <!--
      创建别名,在为实体创建别名后 在mapper文件中 使用parameterType是可直接写实体类名
      而不是全类名
    -->
    <typeAliases>
        <package name="com.bjlemon.mybatis.domian"/>
    </typeAliases>
    <environments default="mybatis_1">
        <environment id="mybatis_1">
            <!--有2种属性值-->
            <transactionManager type="JDBC"/>
            <!--有3种属性值-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

      <!--
        指定mapper文件的位置,mapper和packge标签两种方法
       -->
    <mappers>
        <mapper resource="com/bjlemon/mybatis/mapper/userMapper.xml"/>
    </mappers>
</configuration>
  • 实体类User.java
package com.bjlemon.mybatis.domian;

import java.io.Serializable;
import java.util.Date;
import java.util.Objects;

public class User implements Serializable{
    private Integer id;
    private String name;
    private  String password;
    private Float salary;
    private Date birthday;

    public String getPassword() {
        return password;
    }

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

    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 Float getSalary() {
        return salary;
    }

    public void setSalary(Float salary) {
        this.salary = salary;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(id, user.id) &&
                Objects.equals(name, user.name) &&
                Objects.equals(salary, user.salary) &&
                Objects.equals(birthday, user.birthday);
    }

    @Override
    public int hashCode() {

        return Objects.hash(id, name, salary, birthday);
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                ", birthday=" + birthday +
                '}';
    }
}

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="mybatis_in_action">
    <!--
        此处使用的为非代理模式,则namespce值为用户自定义,在需要使用相关SQL语句时,需要为namespace+SQL ID
        parameterType:参数类型
        resultType:结果类型
    -->
    <insert id="insert" parameterType="User">
        INSERT  INTO
             mybatis_user(user_name,user_password,user_salary,user_birthday)
         VALUE
               (#{name},#{password},#{salary},#{birthday})
    </insert>
    <select id="findAll" resultType="User">
        SELECT
            user_id id ,
            user_name name,
            user_password password ,
            user_salary salary ,
            user_birthday birthday
        FROM
            mybatis_user
    </select>
</mapper>

UserService接口

package com.bjlemon.mybatis.service;

import com.bjlemon.mybatis.domian.User;

import java.util.List;

public interface UserService {
    void addUser(User user);
    List<User> findAllUserList();
}

UserService实现类

package com.bjlemon.mybatis.service.impl;

import com.bjlemon.mybatis.domian.User;
import com.bjlemon.mybatis.service.UserService;
import com.bjlemon.mybatis.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class UerServiceImpl implements UserService{
    @Override
    public void addUser(User user) {
        SqlSession sqlSession = null;
        if (user == null) {
            throw new IllegalArgumentException("");
        }
        try{
            sqlSession = MybatisUtils.getSqlSession();
        /*
           如何mapper文件使用不是代理模式 则此处需要写成
           namespace+方法名
           使用的为代理模式时,则可以直接使用方法名
         */
            sqlSession.insert("mybatis_in_action.insert", user);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.clolseSqlSession();
        }

    }

    @Override
    public List<User> findAllUserList() {
        SqlSession sqlSession = null;
        List<User> userList = Collections.emptyList(); // 避免空指针异常

        try{
            sqlSession = MybatisUtils.getSqlSession();
            userList = sqlSession.selectList("mybatis_in_action.findAll");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.clolseSqlSession();
        }
            return  userList;
    }
}

mybatis的sqlSession的创建

  1. 得到SqlSessionFactoryBuilder
  2. 读取配置文件
  3. 由SqlSessionFactoryBuilder到SqlSessionFactory
  4. 由SqlSessionFactory得到SqlSession
package com.bjlemon.mybatis.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class MybatisUtils {
    private static  SqlSessionFactoryBuilder builder;
    private static SqlSessionFactory sqlSessionFactory;
    //使得sqlSession线程安全
    private  static  ThreadLocal<SqlSession> sqlSessionHolder = new ThreadLocal<>();
    static {
        try{
            builder = new SqlSessionFactoryBuilder();
            // 读取配置文件
           // InputStream in=MybatisUtils.class.getResourceAsStream("/mybatis.xml");
            InputStream resource = Resources.getResourceAsStream("mybatisConfig.xml");
            sqlSessionFactory = builder.build(resource);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 保证sqlSesssion线程安全
     * @return
     */
    public  static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionHolder.get();
        if (sqlSession == null){
            sqlSession = sqlSessionFactory.openSession();
            sqlSessionHolder.set(sqlSession);
        }
        return  sqlSession;
    }

    public  static  void clolseSqlSession(){
        SqlSession sqlSession = sqlSessionHolder.get();
        if (sqlSession != null){
            sqlSession.close();
            sqlSessionHolder.remove();
        }
    }
}

测试

package com.bjlemon.mybatis.service.impl;

import com.bjlemon.mybatis.domian.User;
import com.bjlemon.mybatis.service.UserService;
import org.junit.Before;
import org.junit.Test;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

public class UerServiceImplTest {
    private UserService userService;
    @Before
    public void setUp() throws Exception {
        this.userService = new UerServiceImpl();
    }

    @Test
    public void addUser() {
        User user = new User();
        user.setBirthday(new Date());
        user.setPassword("121312313123");
        user.setName("1231");
        user.setSalary(12.33F);
        this.userService.addUser(user);
    }

    @Test
    public  void testSelect(){
        List<User> list = this.userService.findAllUserList();
        for (User user: list){
            System.out.println(user);
        }
    }
}

PS: 仅日常笔记整理,有错误请指出,喷子绕路

展开阅读全文

没有更多推荐了,返回首页