Mybatis Prepared Statement 一小时迅速入门Mybatis之Prepared Statement与符号的使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Mybatis Prepared Statement 一小时迅速入门Mybatis之Prepared Statement与符号的使用

grace.free   2021-09-14 我要评论
想了解一小时迅速入门Mybatis之Prepared Statement与符号的使用的相关内容吗,grace.free在本文为您仔细讲解Mybatis Prepared Statement的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Mybatis,Prepared,Statement,Java,Mybatis,下面大家一起来学习吧。

引入Mysql的Jar包以及表结构前几篇已经有了这里就不赘述了

一、用一用 PreparedStatement

import java.math.BigDecimal;
import java.sql.*;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程
 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作
 * @create 2021-08-25 21:26
 */
public class TestMain {
    public static void main(String[] args) throws Exception {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet result = null;
        try {
            // 1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2. 打开连接 url 、 用户名、 密码
            conn = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/test?useSSL=false",
                    "root",
                    "123456");
            // 3. 创建Statenebt
            stmt = conn.prepareStatement("select * from test where name = ?");
            // 4. 设置参数 注意啦,参数下标是从1开始的 不是0哦
            stmt.setString(1, "小强");
            // 5. 执行查询
            result = stmt.executeQuery();
            // 6. 输出数据库获取的结果
            while (result.next()){
                // 根据列名称获取值
                String name = result.getString("name");
                BigDecimal salary = result.getBigDecimal("salary");
                System.out.println(name+" 的工资是:"+salary);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            // 关闭资源
            try{
                if(result!=null) {
                    result.close();
                }
            }catch(SQLException se2){
                System.err.println("关闭result异常");
            }
            try{
                if(stmt!=null) {
                    stmt.close();
                }
            }catch(SQLException se2){
                System.err.println("关闭stmt异常");
            }
            try{
                if(conn!=null) {
                    conn.close();
                }
            }catch(SQLException se){
                System.err.println("关闭conn异常");
            }
        }

    }
}

二、用一用 Statement

import java.math.BigDecimal;
import java.sql.*;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程
 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作
 */
public class TestMain02 {
    public static void main(String[] args) throws Exception {
        Connection conn = null;
        Statement stmt = null;
        ResultSet result = null;
        try {
            // 1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2. 打开连接 url 、 用户名、 密码
            conn = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/test?useSSL=false",
                    "root",
                    "123456");
            // 3. 创建Statenebt
            stmt = conn.createStatement();
            // 4. 执行查询
            result = stmt.executeQuery("select * from test where name = '小强'");
            // 5. 输出数据库获取的结果
            while (result.next()){
                // 根据列名称获取值
                String name = result.getString("name");
                BigDecimal salary = result.getBigDecimal("salary");
                System.out.println(name+" 的工资是:"+salary);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            // 关闭资源
            try{
                if(result!=null) {
                    result.close();
                }
            }catch(SQLException se2){
                System.err.println("关闭result异常");
            }
            try{
                if(stmt!=null) {
                    stmt.close();
                }
            }catch(SQLException se2){
                System.err.println("关闭stmt异常");
            }
            try{
                if(conn!=null) {
                    conn.close();
                }
            }catch(SQLException se){
                System.err.println("关闭conn异常");
            }
        }

    }
}

三、Mybatis #{} ${} 的使用

#{}使用

// #{}  根据名称查询数据
List<TestEntity> listByName01(String name);
<!--#{} 查询数据-->
<select id="listByName01" resultType="testentity">
    select * from test where name = #{name}
</select>
import dao.TestMapper;
import entity.TestEntity;
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.InputStream;
import java.util.List;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程
 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作
 */
public class TestMain03 {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper
            TestMapper mapper = session.getMapper(TestMapper.class);
            // 1.#{}
            List<TestEntity> res = mapper.listByName01("小强");
            // 这个执行的sql : select * from test where name = '小强 '
            System.out.println("第一次查询条数:"+res.size());
            List<TestEntity> res02 = mapper.listByName01("小强  or 1=1");
            // 这个执行的sql: select * from test where name = '小强  or 1=1'
            System.out.println("第二次查询条数:"+res02.size());
        }
    }
}

${}使用

// ${}  根据名称查询数据
List<TestEntity> listByName02(@Param("name") String name);
<!--${} 查询数据-->
<select id="listByName02" resultType="testentity">
    select * from test where name = ${name}
</select>
import dao.TestMapper;
import entity.TestEntity;
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.InputStream;
import java.util.List;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程
 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作
 */
public class TestMain04 {
    public static void main(String[] args) throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 通过sesson获取Mapper 这个Mapper会编程Mybatis的代理Mapper
            TestMapper mapper = session.getMapper(TestMapper.class);
            // 1.${} 这里还得自己加个单引号 要不然sql就不对了
            List<TestEntity> res = mapper.listByName02("'小强'");
            // 执行的sql: select * from test where name = '小强'
            System.out.println("第一次:"+res.size());
            List<TestEntity> res02 = mapper.listByName02("'小强 ' or 1=1 ");
            // 执行的sql(可怕哦): select * from test where name = '小强 ' or 1=1
            System.out.println("第二次:"+res02.size());
        }
    }
}

#{} 使用的是PrepareStatment 用的是 ‘?' 占位符 不会被SQL注入 不管你输出什么都会给你用单引号包起来

类似这种:

public class TestMain05 {
    public static void main(String[] args)   {
        String sql = "select * from test where name = '?' ";
        String name = "小强";
        sql = sql.replace("?", name);
        System.out.println(sql);
        // select * from test where name = '小强' 
    }
}

${}他就相当于是普通的拼接 你传入什么就原封不动的给你放到Sql后边

类似这种:

public class TestMain06 {
    public static void main(String[] args)   {
        String sql = "select * from test where name = ?";
        String name = "'小强'";
        sql = sql.replace("?", name);
        System.out.println(sql);
    }
}

四、ResultMap ResultType的区别

resultType使用方式我们已经用过很多次了,这里先下一个resultMap的使用方式

<resultMap id="testResultMap" type="testentity">
    <id property="id" column="id" javaType="long" jdbcType="BIGINT"/>
    <result property="name" column="name" javaType="string" jdbcType="VARCHAR"/>
    <result property="age" column="name" javaType="int" jdbcType="INTEGER"/>
    <result property="salary" column="name" javaType="decimal" jdbcType="DECIMAL"/>
 </resultMap>

 <select id="testResultMap" resultMap="testResultMap">
    select * from test
 </select>

resultType、resultMap功能类似,都是返回对象信息,但是resultMap要更强大一些,可以实现自定义。

我们一般项目中数据库都是下划线比如course_date 但是实体类中都是用courseDate 所以大部分时候都需要进行名称匹配都会用到resultMap 或者 sql写别名

sql别名方式:

<select id="list" resultType="testentity">
    select
    id as id
    name as name
    age as age
    course_date as courseDate
    from test
</select>

id&result

他俩都是将一列值映射到一个简单的数据类型(String、int、double、Date等)的属性或字段。

他俩唯一的不同是:id元素对应的属性会被标记为对象的标识符,在比较对象实例的时候使用。这样可以提升整体的性能,尤其是进行缓存和嵌套结果映射的时候。

他俩都有一些属性:

属性 描述
property 映射到列结果的字段或属性
column 数据库中的列名,或者是列的别名。一般情况下,这和传递给 resultSet.getString(columnName) 方法的参数一样。
就是数据库列名
javaType 一个 Java 类的全限定名,或一个类型别名 如果你映射到一个 JavaBean,MyBatis 通常可以推断类型。然而,如果你映射到的是 HashMap,那么你应该明确地指定 javaType 来保证行为与期望的相一致。
jdbcType 这就是数据库对应的类型,非必须的
typeHandler 结果处理器,就是把结果再处理一次返回 后边几篇写一下自定义typeHandler

在中文官网上找了个例子:

<!-- 非常复杂的结果映射 -->
<resultMap id="detailedBlogResultMap" type="Blog">
  <constructor>
    <idArg column="blog_id" javaType="int"/>
    <arg  column="name" javaType="varchar"></arg>
  </constructor>
  <result property="title" column="blog_title"/>
  <association property="author" javaType="Author">
    <id property="id" column="author_id"/>
    <result property="username" column="author_username"/>
    <result property="password" column="author_password"/>
    <result property="email" column="author_email"/>
    <result property="bio" column="author_bio"/>
    <result property="favouriteSection" column="author_favourite_section"/>
  </association>
  <collection property="posts" ofType="Post">
    <id property="id" column="post_id"/>
    <result property="subject" column="post_subject"/>
    <association property="author" javaType="Author"/>
    <collection property="comments" ofType="Comment">
      <id property="id" column="comment_id"/>
    </collection>
    <collection property="tags" ofType="Tag" >
      <id property="id" column="tag_id"/>
    </collection>
    <discriminator javaType="int" column="draft">
      <case value="1" resultType="DraftPost"/>
    </discriminator>
  </collection>
</resultMap>

constructor: 用于实例化类时,注入结果到构造方法中

​ idArg:这个就是主键ID

​ arg:这个就是普通字段

association: 一个复杂类型的关联 对象里字段是对象

collection:一个复杂的类型关联 对象里字段是集合

discriminator: 使用结果值来确认使用哪个resultMap

下集预告:

写一个复杂点的返回结果resultMap案例

动态SQL 常用标签

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们