mybatis使用

Mybatis 的使用

首先需要用到的sql文件

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', 'xiaoming', '43');
INSERT INTO `student` VALUES ('2', 'tom', '20');
INSERT INTO `student` VALUES ('3', 'lilei', '90');
INSERT INTO `student` VALUES ('4', 'haha', '10');

注:sql文件直接运行查询,然后刷新一下表就可以啦

mybatis使用_第1张图片

 

 

新建项目

 mybatis使用_第2张图片

 

 

 mybatis使用_第3张图片

 

 

 mybatis使用_第4张图片

 

mybatis使用_第5张图片

 

 

 

 1.创建文件夹

mybatis使用_第6张图片

 

mybatis使用_第7张图片

 

 

 这4个可以全选

mybatis使用_第8张图片

 

 

 

 

mybatis使用_第9张图片

 

 

 1.先写mybatis-conf.xml文件

mybatis使用_第10张图片

 

 

 

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>
    
    
    <environments default="development">

        
        <environment id="development">

            
            <transactionManager type="jdbc"/>

            
            <dataSource type="pooled">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/util?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource>
        environment>


    environments>
    <mappers>
        
        <mapper resource="mapper/stuMapper.xml"/>

    mappers>


configuration>

2.DBTools 工具类

package util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class DBTools {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            Reader reader = Resources.getResourceAsReader("config/mybatis-conf.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

3.实体类

package entity;

public class Stu {
    private int id;
    private String name;
    private int age;

    public Stu(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Stu() {
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Stu{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code

4.mapper 映射文件,这里与下面的接口相对应

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="dao.StuMapper">

    <resultMap id="stuBean" type="entity.Stu">
        <id property="id" column="id">id>
        <result property="name" column="name">result>
        <result property="age" column="age">result>
    resultMap>
    <select id="queryUserByName"  resultType="entity.Stu">
        select * from student where name=#{name}
    select>
    <select id="queryAll" resultMap="stuBean">
      select * from student
    select>

    <insert id="insertUser" parameterType="entity.Stu">
      insert into student values(#{id},#{name},#{age})
    insert>

    <delete id="deleteUserByName" parameterType="string">
        delete from student where name=#{name}
    delete>

    <update id="updateUserById" >
        update student set name=#{name},set age=#{age} where id=#{id}
    update>

mapper>

5.映射的接口,,用来后边的调用

package dao;

import entity.Stu;

import java.util.List;

public interface StuMapper {
    Stu queryUserByName (String name);

    List queryAll();

    int insertUser(Stu userBean);

    int deleteUserByName(String name);

    int updateUserById(Stu userBean,int id);
}

6.最后一个测试类,也就是调用到之前写的映射文件对应的接口

import dao.StuMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import util.DBTools;

public class Ke {
    public static void main(String[] args) {
        //1.创建sqlsessionFactory 这个是mybatis的一个对象,这个实现类可以进行增删查改以及事务操作等.
        SqlSessionFactory sqlSessionFactory = DBTools.getSqlSessionFactory();
        //2.创建SqlSession
        SqlSession session = sqlSessionFactory.openSession();
        //3.session 中创建相应的接口代理类,即mapper对象
        StuMapper userBeanMapper = session.getMapper(StuMapper.class);
        //查询操作
        System.out.println(userBeanMapper.queryAll());
        //下面的注释了,有增删
       /* try {
            //删除操作
            System.out.println(userBeanMapper.deleteUserByName("tom"));
            //新建一个对象
            Stu u1 = new Stu();
            u1.setAge(28);
            u1.setName("king");
            u1.setId(3);
            //添加操作
            System.out.println(userBeanMapper.insertUser(u1));
            session.commit();//一定要提交,不然所有增删改操作不会生效的
            System.out.println(userBeanMapper.queryAll());
        }catch (Exception e){
            session.rollback();//回滚
        }*/
    }
}

好了,到此就可以运行了。

下面讲一下这几个配置文件之间的关联

mybatis使用_第11张图片

 

 懂了吧

 

你可能感兴趣的:(mybatis使用)