Mybatis入门

Mbatis

简介

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。

入门

使用 Maven 来构建项目,需将下面的依赖代码置于 pom.xml 文件中,如果不使用Maven则需要下载mybatis的jar包

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。

String resource = "org/mybatis/example/mybatis-config.xml";
//可以使用任意流
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

在使用SqlSessionFactory之前我们需要创建一个mybatis-context.xml用来配置相关信息

    
   
 <!--//默认选中development指向的环境,我们可以写多个环境,比如test测试时环境,在使用时只需要更改default即可--> 
  <environments default="development">
    <environment id="development">
        
        <!-- mybatis的事务管理器,默认为JDBC,还有一个为MANAGED-->
      <transactionManager type="JDBC"/>
        
        <!--dataSource 连接池的类型可以配置成其内置类型之一,如 UNPOOLED,POOLED,JNDI。其中UNPOOLED会在每次访问数据库时建立一个新的连接,POOLED只会创建一个连接,操作完成之后会将连接放回连接池  -->
      <dataSource type="POOLED">
          
         <!--以下为连接数据库时需要的参数,如果在environment的起始位置导入了配置文件,则可以使用¥{}获取参数值,否则需要将参数直接写入 -->
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
       <!--mapper映射,在创建一个新的StudentMapper(StudentDao)时,需要为其注册一个mapper -->
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

获取SqlSession对象

try (SqlSession session = sqlSessionFactory.openSession()) {
  StudentMapper mapper = session.getMapper(StudentMapper.class);
}

映射的 SQL 语句

我们需要写一个xml文件用来配置我们的sql映射,名字最好与我们的接口相同

<?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">
​
<!--namespace 命名空间,这里需要使用我们数据持久层StudentMapper的全限命名,即包命+接口名 -->
<mapper namespace="com.dream.dao.StudentMapper">
    <!-- -->
    <!--这里是我们的sql语句,select,update,insert,delete,其中id需要和我们StudentMapper中对应的方法同年,为了能使我们前面创建StudentMapper对象可以直接调用selectUser方法 -->
    
  <select id="selectStudent" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
​
​
 <!-- 注意:
    全限定名(比如 “com.dream.dao.StudentMapper)将被直接用于查找及使用。
    短名称(比如 “selectAllThings”)如果全局唯一也可以作为一个单独的引用。 如果不唯一,有两个或两个以上的相同名称(比如 “com.foo.selectAllThings” 和 “com.bar.selectAllThings”),那么使用时就会产生“短名称不唯一”的错误,这种情况下就必须使用全限定名。-->
 

一个简单的mybatis项目

mybatis-context.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>
    
    <!--这里是引入外部配置文件-->
    <properties resource="db.properties"/>
    <environments default="development">
<!---->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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>
    <mappers>
        <mapper resource="com/li/dao/StudentMapper.xml"/>
    </mappers>
</configuration>

db,properties

driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/studyserverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=true
username = root
password = 123456

由于在我们的业务中我们频繁的创建SqlSession对象,为了避免代码的冗余,我们将其封装成工具类

package com.li.mybatisutils;
​
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.IOException;
import java.io.InputStream;
​
public class MybatisUtils {
    private static InputStream inputStream = null;
    private static SqlSessionFactory factory = null;
    static {
        String resource = "mybatis-config.xml";
​
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        factory = new SqlSessionFactoryBuilder().build(inputStream);
​
    }
    public static SqlSession getSqlSession(){
        return  factory.openSession();
    }
}

pojo实体类

package com.li.pojo;

public class Student {
    String sno;
    String sname;
    int sage;
    String ssex;

    public Student() {
    }

    public Student(String sno, String sname, int sage, String ssex) {
        this.sno = sno;
        this.sname = sname;
        this.sage = sage;
        this.ssex = ssex;
    }

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public int getSage() {
        return sage;
    }

    public void setSage(int sage) {
        this.sage = sage;
    }

    public String getSsex() {
        return ssex;
    }

    public void setSsex(String ssex) {
        this.ssex = ssex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sno='" + sno + '\'' +
                ", sname='" + sname + '\'' +
                ", sage=" + sage +
                ", ssex='" + ssex + '\'' +
                '}';
    }
}

UserMapper接口

package com.li.dao;

import com.li.pojo.Student;

import java.util.List;

public interface StudentMapper {
    List<Student> getStudent();

}

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="com.li.dao.StudentMapper">

<!--查询学生-->
    <select id="getStudent" resultType="com.li.pojo.Student">
        select * from student
    </select>

</mapper>

测试

package com.li.dao;

import com.li.mybatisutils.MybatisUtils;
import com.li.pojo.Student;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

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

public class StudentTest {
    @Test
    public void test() throws IOException {
        
        //获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        调用getStudent方法
        List<Student> list = mapper.getStudent();
        for (Student student : list) {
            System.out.println(student);
        }
        sqlSession.close();
    }
}

结果

在上面的项目中如果StudentMapper.xml在resource资源文件中,程序可以正常运行,否则会报错,这是应为mybatis默认只会去扫描resourse资源文件中的配置文件,这时我们需要在pom.xml文件中配置使得mabatis可以去扫描其他地方的配置文件

<!--    Maven项目的资源配置文件是默认放在resources文件夹下的,放在其他地方的配置文件不能被导出-->
<!--    所以我们需要手动在pom.xml文件中进行配置资源的路径-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值