Mybatis入门

1、创建测试表

2、创建maven项目

3、修改pom文件 
        引入依赖 mybatis  mysql驱动 测试代码 junit
        <build>中加入资源插件
复制代码
<!--依赖列表-->
<dependencies>
    <!--单元测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <!--mybatis依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.1</version>
    </dependency>

    <!--mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.49</version>
    </dependency>
</dependencies>

<build>
    <!--资源插件  处理src/main/java目录下的xml文件-->
    <resources>
        <resource>
            <!--所在目录-->
            <directory>src/main/java</directory>
            <!--包括目录下的properties,xml文件会被扫描-->
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>

    <plugins>
        <plugin>
            <!--编译插件使用版本-->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>
pom文件
复制代码

4、创建实体类 student 定义属性

复制代码
package com.pojo;

/**
* @author lbon
* @create 2022-04-13 21:49
*/
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 "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}
student类
复制代码

5、创建Dao接口  定义操作数据库方法

复制代码
package com.dao;

import com.pojo.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;


/**
* @author lbon
* @create 2022-04-13 21:51
*/
public interface StudentDao {
    /**
     * 获取学生列表
     * @return
     */
    List<Student> getStudentList();


    /**
     * 新增学生
     * @param student
     * @return
     */
    Boolean insertStudent(@Param("student") Student student);
}
Dao接口
复制代码
6、创建xml文件(mapper文件) 书写sql语句
            mybatis推荐将sql语句和java代码相分离
            mapper文件:定义和dao接口在同一目录 一个表对应一个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">


<!--<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 约束文件
            约束文件作用:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
        mapper是根标签
            namespace 命名空间 必须有值 不能为空 唯一值
                推荐使用Dao接口的全限定名称
                作用:参与识别sql语句的作用
        在mapper中可以写 <insert> <update> <delete> <select> 等标签
-->
<mapper namespace="com.dao.StudentDao">
    <!--若果传给mybatis的对象 使用#{属性名}获取此属性的值
        mybatis执行此属性  对应get 操作
    -->
    <insert id="insertStudent">
        insert into student values(#{id},#{name},#{email},#{age})
    </insert>
    <!--id 标识执行sql语句的唯一标识,是一个自定义字符串  推荐使用dao接口中的方法名称
        resultType 告诉mybatis执行sql语句 把数据赋值给哪个类型的java对象
        resultType的使用对象的全路径
    -->
    <select id="getStudentList" resultType="com.pojo.Student">
        select *
        from student
    </select>
</mapper>
mapper文件
复制代码
7、创建mybatis的主配置文件(xml文件) 一个项目仅一个 放在resources下
        1)定义创建连接实例的数据源对象DateSource对象
        2)指定其他mapper的位置
复制代码
<?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>
    <!--设置日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--配置数据源:创建Connect对象-->
            <dataSource type="POOLED">
                <!--驱动内容-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--数据库地址-->
                <!--html字符实体不能直接使用会被误认为标签  需要换成对应的代替符号-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb?useUnicode=true&amp;characterEncodeing=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--指定其他mapper文件位置
        为了找到文件中的可执行sql语句
    -->
    <mappers>
        <!--使用mapper的resource 指定mapper文件的路径  从target/classes路径开始的
            注意:Resource="mapper文件的路径,使用/分割路径
            一个 mapper resource指定一个mapper文件"
        -->
        <mapper resource="com/dao/StudentDao.xml"/>
    </mappers>

</configuration>
mybatis主配置文件
复制代码
8、创建测试内容
        main方法 或单元测试Junit
复制代码
import com.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.Test;

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

/**
* @author lbon
* @create 2022-04-14 15:06
*/
public class MyTest {

    @Test
    public void testSelectStudentList() {
        //调用mybatis读取学生信息
        //mybatis核心类 SqlSessionFactory
        //定义mybatis主配置文件位置,从类路径开始的相对路径
        String resource = "mybatis.xml";
        try {
            //读取配置文件 使用mybatis中Resources类
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //创建SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //指定要执行的sql语句id  namespace+"."+ mapper语句标签id  通过sqlSession方法获取sql语句
            List<Student> objects = sqlSession.selectList("com.dao.StudentDao.getStudentList", Student.class);
            for (Student s : objects) {
                System.out.println(s.toString());
            }
            //关闭sqlSession对象
            sqlSession.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
测试方法
复制代码

 

posted @   lbon  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示