Mybatis--(1)使用IDEA快速搭建Mybatis

使用IDEA快速搭建Mybatis

创建mysql数据库

在数据库中创建表student
数据库

创建maven工程

在IDEA,点New Project选择Maven,勾选Create from archetype

选择maven-archetype-quickstart这个模板

模板

修改pom.xml

在pom.xml文件中添加junit单元测试框架,和mybatis依赖及mysql驱动

<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>8.0.26</version>
  </dependency>

</dependencies>

加入maven插件

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory><!--所在的目录-->
      <includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
      <filtering>false</filtering>
    </resource>
  </resources>
  <plugins>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
  </plugins>
</build>

创建实体类

创建包com.ltltl.domain

在其中创建实体类Student

其中的属性名和数据库的列名一样

并创建set,get方法和重写toString方法

package com.ltlrl.domain;

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 +
                '}';
    }
}

编写接口

创建com.ltlrl.dao包,创建接口StudentDao

package com.ltlrl.dao;

import com.ltlrl.domain.Student;

import java.util.List;

//接口操作student
public interface StudentDao {
    //查询student表的所有的数据
    public List<Student>selectStudents();
}

编写映射文件

在com.ltlrl.dao包,创建StudentDao.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">
<!--
 namespace:必须有值,自定义的唯一字符串
 推荐使用:dao 接口的全限定名称
-->
<mapper namespace="StudentDao">
    <!--
    <select>: 查询数据, 标签中必须是 select 语句
    id: sql 语句的自定义名称,推荐使用 dao 接口中方法名称,
    使用名称表示要执行的 sql 语句
    resultType: 查询语句的返回结果数据类型,使用全限定类名
    -->
    <select id="selectStudents" resultType="Student">
        <!--要执行的 sql 语句-->
        select name,id,email,age from student
    </select>
    
</mapper>

创建主配置文件

在项目 src/main 下创建 resources 目录,其中设置 resources 目录为 resources root

创建主配置文件mybatis.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>
    <!--settings控制mybatis全局行为-->
    <settings>
        <!--设置mybatis输出日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--配置 mybatis 环境-->
    <environments default="mysql">
        <!--id:数据源的名称-->
        <environment id="mysql">
            <!--配置事务类型:使用 JDBC 事务(使用 Connection 的提交和回滚)-->
            <transactionManager type="JDBC"/>
            <!--数据源 dataSource:创建数据库 Connection 对象
            type: POOLED 使用数据库的连接池
            -->
            <dataSource type="POOLED">
                <!--连接数据库的四个要素-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="URL"/>
                <property name="username" value="账号"/>
                <property name="password" value="密码"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--告诉 mybatis 要执行的 sql 语句的位置-->
        <mapper resource="com/ltlrl/dao/StudentDao.xml"/>
    </mappers>
</configuration>

创建测试类

在src/test/java/com/ltlrl/ 创建 MyBatisTest.java 文件

public class TestMyBatis {
    @Test
    public void testmain()throws IOException {
        //1.mybatis 主配置文件
        String config="mybatis.xml";
        //2.读取配置文件
        InputStream in = Resources.getResourceAsStream(config);
        //3.创建 SqlSessionFactory 对象,目的是获取 SqlSession 
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory factory= builder.build(in);
        //4.获取 SqlSession,SqlSession 能执行 sql 语句
        SqlSession sqlSession=factory.openSession(true);
        //5.执行 SqlSession 的 selectList()
        String sqlId="com.ltlrl.dao.StudentDao.selectStudents";
        List<Student> studentList = session.selectList("sqlId");
        //6.循环输出查询结果 
        studentList.forEach( student -> System.out.println(student));
        //7.关闭 SqlSession,释放资源
        sqlSession.close();
    }
}

版权声明:本文为m0_49654761原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。