淘先锋技术网

首页 1 2 3 4 5 6 7

MyBatis工程搭建

项目总体结构图:

在这里插入图片描述
首先需要建一个数据库,SQL如下:

/*
Navicat MySQL Data Transfer

Source Server         : 本地连接
Source Server Version : 80023
Source Host           : localhost:3306
Source Database       : mybatis_demo

Target Server Type    : MYSQL
Target Server Version : 80023
File Encoding         : 65001

Date: 2021-04-05 12:54:52
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `age` int DEFAULT NULL,
  `score` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'peter', '18', '100');
INSERT INTO `user` VALUES ('2', 'pedro', '24', '200');
INSERT INTO `user` VALUES ('3', 'jerry', '28', '500');
INSERT INTO `user` VALUES ('4', 'mike', '12', '300');
INSERT INTO `user` VALUES ('5', 'tom', '27', '1000');


配置好pom.xml,配置文件如下:

<dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.3.0-alpha5</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

使用JDBC 连接及操作数据库,实现代码如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCDemo {
    public static void main(String[] args) throws Exception {
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis_demo", "root", "ang76516"); 
        //3.获取Statement对象
        PreparedStatement preparedStatement = connection.prepareStatement("select * from user WHERE id = ?");
        preparedStatement.setInt(1, 1);
        //4.执行SQL语句返回结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        //5.遍历结果集
        while (resultSet.next()) {
            System.out.println("username: " + resultSet.getString("username"));
            System.out.println("age: " + resultSet.getString("age"));
        }
        //6.释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}

运行结果:在这里插入图片描述
总结:JDBC的缺点:代码多,效率不是太高!

使用通过引入MyBatis依赖

需要先配置一个核心文件,在resources下创建一个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"/>
            <!-- 数据源 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="ang76516"/>
            </dataSource>
        </environment>
    </environments>
    <!-- mapper配置 -->
    <mappers>
        <mapper class="mapper.UserMapper"/>
    </mappers>
</configuration>

StartWithXml.Java,代码实现如下:

import org.apache.ibatis.datasource.pooled.PooledDataSource;
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.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@SuppressWarnings({"SqlResolve", "SqlNoDataSourceInspection", "Duplicates"})
public class StartWithXml {

    public static void main(String[] args) throws SQLException, IOException {

        InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");

       /* // 准备jdbc事务类
        JdbcTransactionFactory jdbcTransactionFactory = new JdbcTransactionFactory();
        // 配置数据源
        PooledDataSource dataSource = new PooledDataSource(
                "com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false",
                "root",
                "root");
        // 配置环境,向环境中指定环境id、事务和数据源
        Environment environment = new Environment.Builder("development")
                .transactionFactory(jdbcTransactionFactory)
                .dataSource(dataSource).build();
        // 新建 MyBatis 配置类
        Configuration configuration = new Configuration(environment);

        */

        // 得到 SqlSessionFactory 核心类
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        // 开始一个 sql 会话
        SqlSession session = sqlSessionFactory.openSession();
        // 得到 sql 连接并运行 sql 语句
        PreparedStatement preStatement = session
                .getConnection()
                .prepareStatement("SELECT * FROM user WHERE id = ?");
        preStatement.setInt(1, 1);
        ResultSet result = preStatement.executeQuery();
        // 验证结果
        while (result.next()) {
            System.out.println("username: " + result.getString("username"));
            System.out.println("age: " + result.getString("age"));
        }
        // 关闭会话
        session.close();
    }
}

运行结果如下:

在这里插入图片描述

MyBatis实现Mapper配置并查询数据

根据项目结构图,我们先编辑User类,代码如下

public class User {
    private Integer id;
    private String username;
    private String age;
    private Integer score;
    // getter&setter方法

    public Integer getId(){
        return  id;
    }
    public  void setId(Integer id){
        this.id = id;

    }
    public String username(){
        return username;

    }
    public void  username(String username){
        this.username = username;
    }
    public String age(){
        return age;

    }
    public void  setGenderName(String age){
        this.age = age;

    }
    public  Integer score(){
        return  score;
    }
    public void score(Integer score){
        this.score=score;

    }
    // toString方法
    public  String toString(){
        return "User{"+
                "id="+id+
                ",name='"+username+'\''+
                ",genderName="+age+
                ",gender="+score+'}';
    }
}

UserMapper接口类,代码如下:

import entity.User;
import org.apache.ibatis.annotations.Select;

    public interface UserMapper {
    /**
     * 通过用户id查询用户名称
     *
     * @param id 用户id
     * @return 用户名称
     */
    @Select("SELECT username FROM user WHERE id = #{id}")
    String selectUsernameById(Integer id);
    /**
     * 通过用户id查询用户年龄
     *
     * @param id 用户id
     * @return 用户年龄
     */
    Integer selectUserAgeById(Integer id);

    /**
     * 通过用户id查询用户信息
     *
     * @param id
     * @return
     */
    User selectUserById(Integer id);

}

还需要配置一个核心文件,之前已配好mybatis-config.xml,还需要配置UserMapper.xml,创建在resources下的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">
<mapper namespace="mapper.UserMapper">
    <select id="selectUserAgeById" resultType="java.lang.Integer">SELECT age FROM user WHERE id = #{id}</select>



    <select id="selectUserById" resultMap="userMap">SELECT * FROM user WHERE id = #{id}</select>

    <resultMap id="userMap" type="entity.User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="age" column="age"/>
        <result property="score" column="score"/>
    </resultMap>
</mapper>


测试类UserTest.Java

import entity.User;
import mapper.UserMapper;
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;
import java.sql.SQLException;

@SuppressWarnings({"Duplicates"})
public class UserTest {
    public static void main(String[] args) throws IOException, SQLException {
        // 读取配置文件
        InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");
        // 得到 SqlSessionFactory 核心类
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        // 开始一个 sql 会话
        SqlSession session = sqlSessionFactory.openSession();
        // 得到 mapper
        UserMapper mapper = session.getMapper(UserMapper.class);
        // 调用注解的SQL
        String username = mapper.selectUsernameById(1);
        System.out.println("username: " + username);
        // 调用XML的SQL
        Integer age = mapper.selectUserAgeById(1);
        System.out.println("age: " + age);
        // 调用通过用户id查询用户信息的方法
        User user = mapper.selectUserById(1);
        System.out.println(user);
        // 关闭会话
        session.close();
    }
}

运行结果如下:

在这里插入图片描述