MyBatis入门(简单的增删改查)

1.ORM介绍

ORM(Object Relational Mapping):对象关系映射

指的是持久化数据和实体对象的映射模式,为了解决面向对象与关系型数据库的互补匹配的现象技术。

2.MyBatis介绍

2.1 MyBatis是一个优秀的基于java的持久层框架,它内部封装了JDBC,使开发者只需要关注SQL语句本身,而不需要花费精力去处理加载驱动、创建连接、创建执行者等复杂操作。

2.2 MyBatis通过xml或者注解的方式将要执行的的各种Statement配置起来,并通过java对象和Statement中SQL的动态参数进行映射生成最终要指行的SQL语句。

2.3 最后MyBatis框架执行完SQL并将结果映射为java对象并返回,采用ORM思想解决了实体和数据库映射的问题,对JDBC进行了封装,屏蔽了JDBC API底层访问细节,是我们不用与JDBC API打交道,就可以完成对数据库的持久化操作。

MyBatis官网mybatis – MyBatis 3 | 简介

2.1.MyBatis入门程序

1.首先我们可以在数据库中创建一张表  

2.导入java包

在项目文件中创建一个lib目录导入jar包

3.在bean层中创建一个Student类

package com.itheima.bean;

public class Student {
    private int id;
    private String name;
    private String sex;

    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 String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Student(int id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

 4.在src下创建映射配置文件StudebtMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
                   <!--  名称空间  -->
<mapper namespace="StudentMapper">
    <!--  id的属性就代表唯一的标识        将查询到的数据封装到Student对象中-->
    <select id="selectAll" resultType="com.itheima.bean.Student">
    <!--  sql语句:查询所有  -->
       select *from student
    </select>
</mapper>

5.在src下创建核心配置文件MyBatisConfig.mxl

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="mysql">
        <environment id="mysql">
    			<!--采用JDBC为默认的事物 -->
            <transactionManager type="JDBC"/>
    			<!--POOLE代表数据库链接池 -->
            <dataSource type="POOLED">
    			<!--连接数据库操作 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/gcprogect?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
</environments>
    <mappers>
        <mapper resource="StudebtMapper.xml"/>
    </mappers>
</configuration>

6.dao层中的测试类StudentTest01

package com.itheima.dao;

import com.itheima.bean.Student;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentTest01 {
    // junit 4.12
    //查询所有
    @Test
    public void selectAll() throws IOException {
    //1.加载核心配置文件
        InputStream is =  Resources.getResourceAsStream("MyBatisConfig.xml");
    //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    //3.通过SqlSession工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
    //4.执行映射配置文件的sql语句,并接收结果            名称空间.id
        List<Student> ls = sqlSession.selectList("StudentMapper.selectAll");
    //5.处理结果
        for (Student student:ls) {
            System.out.println(student);
        }
    //6.关闭资源
        sqlSession.close();
        is.close();
    }
}

输出结果为:

2.2.MyBatis查询功能的使用

2.2.1通过id进行查询

映射文件代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="StudentMapper">
<!--    -->
                                         
    <select id="selectByid" resultType="com.itheima.bean.Student" parameterType="java.lang.Integer">
        select * from student where id = #{id}
    </select>
</mapper>

测试代码

public class StudentTest01 {
    //根据id进行查询
    @Test
    public void selectByid() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.执行映射配置文件的sql语句,并接收结果  根据id进行查询
        List<Student> students = sqlSession.selectList("StudentMapper.selectByid", 1);
        System.out.println(students);
        resourceAsStream.close();
        sqlSession.close();
    }

2.2.2添加功能

映射文件代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="StudentMapper">
<!--    -->
    
    <insert id="inserStu" parameterType="com.itheima.bean.Student">
        insert into student values (#{id},#{name},#{sex})
    </insert>
</mapper>

测试代码

public class StudentTest01 {
    //添加操作
    @Test
    public void inserStu() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //使用此种方式为自动提交
        //SqlSession sqlSession = sqlSessionFactory.openSession(true);
        Student stu = new Student(5,"王桑","男");
        int ls = sqlSession.insert("StudentMapper.inserStu",stu);
        //提交事物
        sqlSession.commit();
        System.out.println(ls);
        resourceAsStream.close();
        sqlSession.close();

    }
}

2.2.3修改操作

映射文件代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="StudentMapper">

    <update id="Update" parameterType="com.itheima.bean.Student">
        update student set name=#{name},sex=#{sex} where id=#{id}
    </update>
   
</mapper>

测试代码

 public class StudentTest01 {
     @Test
    public void Update() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
         SqlSession sqlSession = sqlSessionFactory.openSession();
        Student stu = new Student(5,"涛子","男");
        int ls = sqlSession.insert("StudentMapper.Update",stu);
        //提交事物
        sqlSession.commit();
        System.out.println(ls);
        resourceAsStream.close();
        sqlSession.close();
    }
  }

2.2.4删除操作

映射文件代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="StudentMapper">

    <delete id="Delete" parameterType="java.lang.Integer">
        delete from student where id = #{id}
    </delete>
</mapper>

测试代码

public class StudentTest01 {
    //删除操作
    @Test
    public void Delete() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        int ls = sqlSession.delete("StudentMapper.Delete",5);
        //提交事物
        sqlSession.commit();
        System.out.println(ls);
        resourceAsStream.close();
        sqlSession.close();
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值