zoukankan      html  css  js  c++  java
  • mybatis的CRUD操作和占位符

    mybatis中增删改查

    增删改一般使用对应的标签来实现, 比如新增用<insert>标签, 删除用<delete>标签, 更新使用<update>标签, 查询使用<select>标签

    标签使用

    • id属性在增删改查的标签中一定会出现, 意义为这个sql的唯一标志, 使用mapper接口开发的使用这个id一般为mapper接口中的方法名, 不用mapper接口这个id名字可以任意, 最好见名知意.

    • resultType 属性出现在<select>标签中, 用来指定查询结果的返回类型, 一般为map或者bean(报名+类名)

    • parameterType属性在增删改查中都有可能出现, 用来指定传入参数的类型, 如果为基本类型或包装类型, 可以省略

    示例代码

    例如新增, mapper.xml可以这样写

    <insert id="insert06" parameterType="com.tedu.pojo.Emp">
        insert into emp value(null, #{name}, #{job}, #{salary});
    </insert>
    

    根据id删除指定员工

    <delete id="deleteById">
        delete from emp where id=#{id};
    </delete>
    

    根据名字修改指定员工信息

    <update id="update07">
        update emp set job = #{job}, salary = #{salary}
        where name = #{name};
    </update>
    

    查询指定id员工

    <select id="findById" resultType="com.tedu.pojo.Emp">
        select * from emp where id = #{id};
    </select>
    

    java代码中进行调用

    // 静态代码块用来获取SqlSession
    static SqlSession session = null;
    static {
        // 为session进行初始化
        try {
            // 1. 读取mybatis的核心配置文件[mybatis-config.xml]
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            // 2. 通过获取SqlSessionFactory工厂对象
            SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
            // 3. 后去SqlSession对象(打开与数据库的连接) true: 表示自动提交, 默认是false即手动提交
            session = fac.openSession(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 新增
    @Test
    public void testInsert02() {
        Map<String, Object> map = new HashMap();
        map.put("name", "张飞");
        map.put("job", "Java开发工程师");
        map.put("salary", 15000D);
        int rows = session.insert("EmpMapper.insert06", map);
        System.out.println("影响行数: " + rows);
    }
    
    // 删除
    @Test
    public void testdeleteById() {
        int id = 13;
        int rows = session.delete("EmpMapper.deleteById", id);
        System.out.println("影响行数: " + rows);
    }
    
    // 修改
    @Test
    public void testUpdate02() {
        // 将SQL语句中的参数封装到Emp对象中
        Emp emp = new Emp(null, "张飞", "架构师", 25000D);
        int rows = session.update("EmpMapper.update07", emp);
        System.out.println("影响行数: " + rows);
    }
    
    // 查询
    @Test
    public void testFindById() {
        Integer id = 1;
        // 根据namespace+id找到并执行SQL语句, 返回执行结果
        Emp emp = session.selectOne("EmpMapper.findById", id);
        System.out.println(emp);
    }
    

    mybatis中的占位符

    #{}:表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换,#{}可以有效防止sql注入。 #{}可以接收简单类型值或pojo属性值。 如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。

    ${}:表示拼接sql串,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, ${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。

    案例

    动态指定要显示的列

    mapper.xml

    <select id="findAll02" resultType="com.tedu.pojo.Emp" parameterType="string">
        select ${colName} from emp;
    </select>
    

    java代码(应用了上面的session`)

    @Test
    public void testFindAll02() {
        String colName = "id, name";
        Map<String, Object> map = new HashMap<>();
        map.put("colName", colName);
        List<Emp> list = session.selectList("EmpMapper.findAll02", map);
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }
    

    mybatis数据库字段和bean对象属性不一致问题

    再我们查询的时候, 有可能会出现bean中的字段名和表的属性不一致的情况, 在实际开发中, 实体类一旦定义好了, 一般不会再修改实体类, 所以mybatis也提供了对应的解决方案

    方案1: 驼峰命名转换

    例如我们数据库中是以下划线分割字母, 而bean中是以驼峰命名, 例如数据库字段student_name, student_id, bean中的字段studentName, studentId 这时候, 我们只需要 打开mybatis的开关即可

    再mybatis中加入设置标签

    <settings>
        <!-- mybatis开启驼峰命名转换开关 -->
    	<setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
    

    方案2: 使用resultMap结果集映射

    当命名不符合驼峰命名和下划线之间的转换时, 可以使用结果集映射

    <resultMap id ="UserInfoMap" type="com.example.mybaitsxml.dao.entity.User">
        <result column="name_" property="name"/>
        <result column="sex" property="sex"/>
        <result column="age" property="age"/>
        <result column="class_no" property="classNo"/>
    </resultMap>
    

    其中column代表的时数据库的列名或者查询时指定的别名,property的值为bean中的属性名

    方案3: 查询别名方式

    所谓的查询别名方式, 就是再sql的查询语句中指定别名, 别名和bean的属性名相同即可

    select 
    	username as name,
    	password as pwd
    from user;
    

    bean中的属性名和别名一致就可以 , 这样查询的数据就存到了bean中的name和pwd属性上

  • 相关阅读:
    volley框架使用
    Insert Interval
    candy(贪心)
    Best Time to Buy and Sell Stock
    Best Time to Buy and Sell Stock III
    distinct subsequences
    edit distance(编辑距离,两个字符串之间相似性的问题)
    trapping rain water
    word break II(单词切分)
    sudoku solver(数独)
  • 原文地址:https://www.cnblogs.com/zpKang/p/13176254.html
Copyright © 2011-2022 走看看