栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis框架快速入门

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MyBatis框架快速入门

内容列表:
快速开始一个MyBatis
基本CURD的操作
MyBatis内部对象分析
使用Dao对象

入门案例

搭建MyBatis开发环境,实现第一个案例。

使用MyBatis准备

下载MyBatis

https://github.com/mybatis/mybatis-3/releases

搭建MyBatis开发环境 创建mysql数据库和表

数据库名 ssm ;表名 student 。

创建数据库

CREATE DATAbase `ssm`CHARACTER SET utf8 COLLATE utf8_general_ci; 

创建数据表

CREATE TABLE `student` (
 `id` int(11) NOT NULL ,
 `name` varchar(255) DEFAULT NULL,
 `email` varchar(255) DEFAULT NULL,
 `age` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

手动插入一条数据,方便后续的查询操作

创建maven工程 创建一个空项目


检查设置环境


创建模块



设置JDK和语言级别

删除默认创建的App类文件

修改pom.xml文件



  4.0.0
  
  com.lln
  learnMybatis
  1.0

  
    UTF-8
    1.8
    1.8
  

  
  
    
    
      org.mybatis
      mybatis
      3.5.1
    

    
    
      mysql
      mysql-connector-java
      5.1.9
    

    
    
      junit
      junit
      4.11
      test
    
  

  
    
    
      
        src/main/java
        
          ***.xml
        
        false
      
    

    
    
      
        maven-compiler-plugin
        3.1
        
          1.8
          1.8
        
      
    

  

创建Student实体类
package com.lln.vo;

public class Student {
    //属性名和数据库表的列名保持一致
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    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 getEmail() {
        return email;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "学生实体的信息:{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", email='" + email + ''' +
                ", age=" + age +
                '}';
    }
}
编写 Dao 接口 StudentDao 类
package com.lln.dao;

import com.lln.vo.Student;

public interface StudentDao {

    //查询一个学生
    Student selectStudentById(Integer id);

}
编写 Dao 接口 Mapper 映射文件

创建mapper文件,写sql语句,文件名:StudentDao.xml
目前与StudentDao接口类在同一目录下





    
    标签中的id属性值
        //String sqlId = "com.lln.dao.StudentDao"+"."+"selectStudentById";
        String sqlId = "com.lln.dao.StudentDao.selectStudentById";
        //6.通过SqlSession的方法,执行sql语句
        Student student = session.selectOne(sqlId);
        //7.控制台输出
        System.out.println("使用mybatis根据id查询一个学生:"+student);
        //8.关闭 SqlSession,释放资源
        session.close();
    }
}

输出结果:

使用mybatis根据id查询一个学生:学生实体的信息:{id=1, name='张三', email='123@163.com', age=18}
初次使用占位符

修改sql语句





    
    标签中的id属性值
        //String sqlId = "com.lln.dao.StudentDao"+"."+"selectStudentById";
        String sqlId = "com.lln.dao.StudentDao.selectStudentById";
        //6.通过SqlSession的方法,执行sql语句
        //Student student = session.selectOne(sqlId);
        Student student = session.selectOne(sqlId,1);

        //7.控制台输出
        System.out.println("使用mybatis根据id查询一个学生:"+student);
        //8.关闭 SqlSession,释放资源
        session.close();
    }
}
配置日志功能

mybatis.xml主配置文件中添加setting设置




    
    
        
    
    
    
        
        
            
            
            
            
                
                
                
                
                
                
            
        
    

    
    
        
        
    

再次执行查询测试,输出结果:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1131316523.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@436e852b]
==>  Preparing: select id,name,email,age from student where id=? 
==> Parameters: 1(Integer)
<==    Columns: id, name, email, age
<==        Row: 1, 张三, 123@163.com, 18
<==      Total: 1
使用mybatis根据id查询一个学生:学生实体的信息:{id=1, name='张三', email='123@163.com', age=18}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@436e852b]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@436e852b]
Returned connection 1131316523 to pool.

Process finished with exit code 0

提交事务

1.自动提交:当sql语句执行完毕后,自动提交事务,数据库更新操作直接保存到数据库。

2.手动提交:在需要提交事务的位置,执行方法,提交事务或者回滚事务。

3.mybatis默认执行sql语句是手动提交事务,在insert,update,delete后需要提交事务

添加数据

接口类添加接口:

package com.lln.dao;

import com.lln.vo.Student;

public interface StudentDao {

    //查询一个学生
    Student selectStudentById(Integer id);

    //添加学生
    //返回值int:影响行数
    int insertStudent(Student student);

}

添加sql语句(mapper映射文件)





    
    标签中的id属性值
        //String sqlId = "com.lln.dao.StudentDao"+"."+"selectStudentById";
        String sqlId = "com.lln.dao.StudentDao.selectStudentById";
        //6.通过SqlSession的方法,执行sql语句
        //Student student = session.selectOne(sqlId);
        Student student = session.selectOne(sqlId,1);

        //7.控制台输出
        System.out.println("使用mybatis根据id查询一个学生:"+student);
        //8.关闭 SqlSession,释放资源
        session.close();
    }

    //测试mybatis执行sql添加语句
    @Test
    public void testInsertStudent() throws IOException {
        //调用mybatis某个对象的方法,执行mapper文件中的sql语句
        //mybatis核心类:SqlSessionFactory
        //1.定义mybatis 主配置文件的位置,从类路径开始的相对路径
        String config = "mybatis.xml";
        //2.读取主配置文件,使用mybatis框架中的Resources类
        InputStream inputStream = Resources.getResourceAsStream(config);
        //3.使用SqlSessionFactoryBuilder类创建 SqlSessionFactory 对象,目的是获取 SqlSession
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //4.获取 SqlSession 对象,SqlSession 能执行 sql 语句
        SqlSession session = factory.openSession();
        //5.指定要执行的sql语句中的id
        //sql的id = namespace+"."+ 
        
        select id,name,email,age
        from student
        where id=#{studentId}
        
    


    
    
    
        insert into student values(#{id},#{name},#{email},#{age})
    





修改测试类

package com.lln;


import com.lln.vo.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;


public class MybatisTest {
    //测试mybatis执行sql查询语句
    @Test
    public void testSelectStudentById() throws IOException {
        //调用mybatis某个对象的方法,执行mapper文件中的sql语句
        //mybatis核心类:SqlSessionFactory
        //1.定义mybatis 主配置文件的位置,从类路径开始的相对路径
        String config = "mybatis.xml";
        //2.读取主配置文件,使用mybatis框架中的Resources类
        InputStream inputStream = Resources.getResourceAsStream(config);
        //3.使用SqlSessionFactoryBuilder类创建 SqlSessionFactory 对象,目的是获取 SqlSession
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //4.获取 SqlSession 对象,SqlSession 能执行 sql 语句
        SqlSession session = factory.openSession();
        //5.指定要执行的sql语句中的id
        //sql的id = namespace+"."+ 标签中的id属性值
        String sqlId = "com.lln.dao.StudentDao.insertStudent";
        //6.通过SqlSession的方法,执行sql语句
        Student student = new Student();
        student.setId(3);
        student.setName("王五");
        student.setEmail("789@163.com");
        student.setAge(30);

        int rows = session.insert(sqlId,student);
        //mybatis默认执行sql语句是手动提交事务
        //在insert,update,delete后需要提交事务
        session.commit();

        //7.控制台输出
        System.out.println("使用mybatis添加一个学生,影响行数rows="+rows);
        //8.关闭 SqlSession,释放资源
        session.close();
    }
}

运行结果:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 205962452.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@c46bcd4]
==>  Preparing: insert into student values(?,?,?,?) 
==> Parameters: 3(Integer), 王五(String), 789@163.com(String), 30(Integer)
<==    Updates: 1
Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@c46bcd4]
使用mybatis添加一个学生,影响行数rows=1
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@c46bcd4]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@c46bcd4]
Returned connection 205962452 to pool.

更新数据库查看添加结果:添加成功!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/344976.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号