mybatis框架基础入门

mybatis框架入门

三层架构

软件开发常用的架构是三层架构,之所以流行是因为有着清晰的任务划分。一般包括以下三层:

  • 持久层:主要完成与数据库相关的操作,即对数据库的增删改查。 因为数据库访问的对象一般称为Data Access Object(简称DAO),所以有人把持久层叫做 DAO层。
  • 业务层:主要根据功能需求完成业务逻辑的定义和实现。 因为它主要是为上层提供服务的,所以有人把业务层叫做Service层或Business层。
  • 表现层:主要完成与最终软件使用用户的交互,需要有交互界面(UI)。
    因此,有人把表现层称之为web层或View层。 三层架构之间调用关系为:表现层调用业务层,业务层调用持久层。 各层之间必然要进行数据交互,我们一般使用java实体对象来传递数据。

三层数据

Mybatis 概述

mybatis是一个针对jdbc进行封装,一个优秀的持久层基于orm对象关系映射框架。它支持定制化 SQL存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
名词解释:
持久层:就是指JDBC操作,把数据持久化到数据库中去;
orm对象关系映射:object(对象)、relational(关系)mapping(映射)就比如:数据库中的表一条记录对应java类中的一个对象,表中列名(字段名)对应Java实体类中的属性,这就是orm对象关系映射。
高级映射:同时查询多个表数据,并自动映射到类上。
定制SQL:自己写sql语句,是和hibernate框架做对比的,hibernate框架不需要自己写sql语句灵活性低。
存储过程:一级缓存,二级缓存

简单使用mybatis

mybatis学习官网

步骤一:创建项目
步骤二:导入jar包

commons-dbcp-1.4.jar
commons-io-1.4.jar
commons-logging-1.2.jar
commons-pool-1.5.4.jar
hamcrest-2.2.jar
junit-4.12.jar
hamcrest-core-2.1.jar
mybatis-3.4.6.jar
mysql-connector-java-5.1.48.jar

步骤三:创建实体类

import java.io.Serializable;

public class Student implements Serializable {
    private String id;
    private String name;
    private Integer age;
    //实现setXXX和getXXX方法
}

步骤四:在resources中创建mybatis-config.xml文件
在官网中找到这里复制到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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybaits"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/StudentMapper.xml"/>
        <mapper resource="mapper/StudentMapper2.xml"/>
    </mappers>
</configuration>

步骤五:在resouces文件夹下创建sql映射问件
比如我先在resouces文件夹下先创建了一个mapper文件夹,再创建的StudentMapper.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">
<!--sql mapper映射文件-->
<!--namespace:命名空间 唯一的,不能重复并且要求接口的全名(包名.类名)保持一致-->
<mapper namespace="mapper.UserMapper">
    <!--id:在当前命名空间中唯一 面向接口开发 要求和sql mapper文件中的sql的id保持一致
        resultType:返回的对象类型 包名.类名
        #{id}:命名参数占位符 通过传入参数给id赋值
     -->
    <!--通过id查询单个对象-->
    <select id="selectStudent" resultType="com.lanou.pojo.Student">
      select * from student where id = #{id}
    </select>
    <!--查询所有对象   List<Student> -->
    <select id="selectAll" resultType="com.lanou.pojo.Student">
      select * from student;
    </select>
    <!--新增student对象 传入参数Student stu-->
    <insert id="saveStudent" parameterType="com.lanou.pojo.Student">
        insert into student(id,name,age) values (#{id},#{name},#{age});
    </insert>
    <!--修改学生对象 Student stu 通过id修改密码-->
    <update id="updateStudent" parameterType="com.lanou.pojo.Student">
        update student set age=#{age} where id = #{id};
    </update>
    <!--删除id是A0007的数据-->
    <delete id="deleteStudent">
        delete from student where id = #{id};
    </delete>
</mapper>

步骤六:测试是否可以对数据库表中的student表进行增删改查


import com.lanou.pojo.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.Before;

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


public class Test {
    SqlSessionFactory sqlSessionFactory =null;
    public static void main(String[] args) throws IOException {
        //定义mybatis核心配置文件
        String resource = "mybatis-config.xml";
        //将配置文件转换为输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //通过输入流生成会话工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            //执行查询
            Student student = session.selectOne("mapper.UserMapper.selectStudent","A0002");
            System.out.println(student.toString());
        }
    }
@Before
public void before() throws IOException {
    //定义mybatis核心配置文件
    String resource = "mybatis-config.xml";
    //将配置文件转换为输入流
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //通过输入流生成会话工厂
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}

@org.junit.Test
public void selectAll() {
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
        //执行查询
        List<Student> stuList = sqlSession.selectList("mapper.UserMapper.selectAll");
        System.out.println(stuList.toString());
    }
}
    /*
     使用mybatis sqlsession dml
        insert update delete 操作 不会自动提交事务
     * */
@org.junit.Test
public void insertStudent(){
        try(SqlSession sqlSession = sqlSessionFactory.openSession()){
            //执行插入
            Student stu = new Student("A0007","cxj",22);
            int num = sqlSession.insert("mapper.UserMapper.saveStudent",stu);
            System.out.println(num);
            //提交事务
            sqlSession.commit();
        }
}
@org.junit.Test
public void updateStudent(){
    try(SqlSession sqlSession = sqlSessionFactory.openSession()){
        //执行修改
        Student stu = sqlSession.selectOne("mapper.UserMapper.selectStudent","A0002");
        stu.setAge(15);
        sqlSession.update("mapper.UserMapper.updateStudent",stu);
        //手动提交事务
        sqlSession.commit();

    }
}
@org.junit.Test
public void delectStudent(){
    try(SqlSession sqlSession = sqlSessionFactory.openSession()){
        //执行删除
        int num = sqlSession.delete("mapper.UserMapper.deleteStudent","A0007");
        System.out.println(num);
        sqlSession.commit();
    }
}
}

测试运行成功
在这里插入图片描述
我踩过的坑,要注意的点:

在测试执行语句时:命名空间.sql语句的id;
单元测试一定要导入junit.jar包,在方法上一定要加@Test
如果说什么没有找到xxx在核心配置文件中注册,一定要检查是否是引错sql映射文件了没

mybatis面向接口的开发

步骤一:在项目中创建一个dao接口
接口的命名跟sql映射文件命名尽量一样。
创建一个StudentMapper接口


import com.lanou.pojo.Student;

import java.util.List;

public interface StudentMapper {
    //查询所有学生信息
    public List<Student> selectAll();
    //查询单个学生信息
    public Student selectStudent(String id);
    //修改某个学生信息
    public int updateStudent(Student stu);
    //添加一个学生信息
    public int insertStudent(Student stu);
    //删除某个学生信息
    public int deleteStudent(String id);
}

创建一个sql映射xml文件如StudentMapper.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.lanou.mapper.StudentMapper">
    <!--通过id查询单个对象-->
    <select id="selectStudent" resultType="com.lanou.pojo.Student">
      select * from student where id = #{id}
    </select>
    <!--查询所有对象   List<Student> -->
    <select id="selectAll" resultType="com.lanou.pojo.Student">
      select * from student;
    </select>
    <!--新增student对象 传入参数Student stu-->
    <insert id="saveStudent" parameterType="com.lanou.pojo.Student">
        insert into student(id,name,age) values (#{id},#{name},#{age});
    </insert>
    <!--修改学生对象 Student stu 通过id修改密码-->
    <update id="updateStudent" parameterType="com.lanou.pojo.Student">
        update student set age=#{age} where id = #{id};
    </update>
    <!--删除id是A0007的数据-->
    <delete id="deleteStudent">
        delete from student where id = #{id};
    </delete>
</mapper>

测试:



import com.lanou.mapper.StudentMapper;
import com.lanou.pojo.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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class TestMapper {
    SqlSessionFactory sqlSessionFactory = null;
    @Before
    public void before() throws IOException {
        //定义mybatis核心配置文件
        String resource = "mybatis-config.xml";
        //将配置文件转换为输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //通过输入流生成会话工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
    @Test
    public void selectStu(){
        try(SqlSession sqlSession = sqlSessionFactory.openSession()){
            //获取对应的StudentMapper接口
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student student = studentMapper.selectStudent("A0004");
            System.out.println(student.toString());
            studentMapper.selectAll();
        }
    }
    @Test

    public void deleteStu(){
        try(SqlSession sqlSession = sqlSessionFactory.openSession()){
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            int num = studentMapper.deleteStudent("A0001");
            System.out.println(num);
            sqlSession.commit();
        }
    }


    @Test
    public void updateStu(){
        try(SqlSession sqlSession = sqlSessionFactory.openSession()){
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student stu = new Student();
            stu.setId("A0005");
            stu.setAge(25);
            studentMapper.updateStudent(stu);
            sqlSession.commit();
        }
    }
    @Test
    public void saveStu(){
        try(SqlSession sqlSession = sqlSessionFactory.openSession()){
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student stu = new Student("A0009","xxx",10);
            studentMapper.insertStudent(stu);
            sqlSession.commit();

        }
    }


}

注意:

面向接口开发中:接口的包名.接口名 =(对应) sql映射文件的命名空间。
接口中的方法 =(对应)sql映射文件中的sql语句的id;
增删改一定要提交事务:sqlSession.commit();不然数据库中没有数据
写语句的时候查询用查询标签,删除用删除标签,修改用修改标签,添加用添加标签。

项目的结构
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值