Java教程

【Mybatis】(一)第一个Mybatis程序

本文主要是介绍【Mybatis】(一)第一个Mybatis程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、新建mysql数据库

//新建数据库
CREATE DATABASE mybatis;

//使用该数据库
USE mybatis;

//建表
CREATE TABLE users
( id INT(20) NOT NULL PRIMARY KEY,
 pname VARCHAR(30) DEFAULT NULL,
  pwd VARCHAR(30) DEFAULT NULL 
)ENGINE=INNODB DEFAULT CHARSET=utf8; 

//插入操作
 INSERT INTO users 
 VALUES(1,'杰伦','123'),
 (2,'俊杰','321'),
 (3,'宝强','222')



在这里插入图片描述
数据库搭建完成。

二、新建项目

1、新建普通maven项目
2、删除src目录
3、导入maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- 父工程-->
    <groupId>org.example</groupId>
    <artifactId>MybatisStudy</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!-- 导入依赖-->
    <dependencies>
        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>

三、创建一个模块

1.新建一个Module

在这里插入图片描述
2、新建核心配置文件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"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis>useSSL=true%amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>

            </dataSource>
        </environment>
    </environments>
</configuration>

3、编写mybatis工具类

package com.zsm.utils;

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 SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //使用mybatis获取sqlsessionfactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //既然有了sqlsessionfactory  顾名思义 我们就可以从中获得sqlsession的实例了
    //sqlsession完全包含了面向数据库执行sql命令所需的所有方法
    public static SqlSession getSqlSession(){
      return  sqlSessionFactory.openSession();
    }
}

4、编写代码
在这里插入图片描述

  • 实体类
//users.java
package com.zsm.pojo;

public class users {
    private int id;
    private String pname;
    private String pwd;

    public users() {
    }

    public users(int id, String pname, String pwd) {
        this.id = id;
        this.pname = pname;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

  • Dao接口
//UserDao.java
package com.zsm.dao;

import java.util.List;
import com.zsm.pojo.users;
public interface UsersDao {
    List<users> getUsersList();
}

  • 接口实现类
    (由原来impl转化成mapper配置文件)
<!-- UsersMapper-->
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace=绑定一个对应的Dao/Mapper接口 -->
<mapper namespace="com.zsm.dao.UsersDao">
    <!-- select查询语句 -->
    <select id="getUsersList" resultType="com.zsm.pojo.users">
        select  * from users

    </select>
</mapper>

5、测试

注意点
   <!-- 每一个mapper.xml都需要在mybatis核心配置文件mybatis-config.xml中注册-->
   <mappers>
       <mapper resource="com/zsm/dao/UsersMapper"/>
   </mappers>

package com.zsm.dao;

import com.zsm.pojo.Users;
import com.zsm.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;


import java.util.List;

public class UsersDaoTest {
    @Test
    public void Test(){

        //1、获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //2、(方式一)getmapper 执行sql
        UsersDao usersDao =  sqlSession.getMapper(UsersDao.class);
        List<Users> usersList =  usersDao.getUsersList();

        for (Users users : usersList) {
            System.out.println(users);
        }

        //关闭session
        sqlSession.close();
    }


}

这篇关于【Mybatis】(一)第一个Mybatis程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!