zoukankan      html  css  js  c++  java
  • 11mybatis映射文件

    映射文件

    映射文件主要写主要写增删改查操作,将sql语句和JavaBean类关联在一起。

    配置文件为:

    <?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="userMapper">
        <!--各种操作--->
    </mapper>
    

    查询

    映射文件

    • resultType指定返回值类型
    <select id="findAll" resultType="com.domain.User">
    	select * from user
    </select>
    

    测试代码

    List<User> userList = sqlSession.selectList("userMapper.findAll");
    System.out.println(userList);
    

    插入

    映射文件

    • parameterType指定参数类型
    • #{}中的参数是User中的属性
    <insert id="insert" parameterType="com.domain.User">
        insert into user values(#{id},#{username},#{password})
    </insert>
    

    测试代码

    插入操作在mybatis中需要用到事务,mybatis插入更新操作默认不提交事务,需要手动写提交代码。

    User user = new User();
    user.setUsername("John");
    user.setPassword("John");
    sqlSession.insert("userMapper.insert", user);
    sqlSession.commit(); // 提交事务
    
    List<User> userList = sqlSession.selectList("userMapper.findAll");
    System.out.println(userList);
    

    修改

    映射文件

    <update id="update" parameterType="com.domain.User">
        update user set username=#{username}, password=#{password} where id=#{id}
    </update>
    

    测试代码

    插入修改等操作在mybatis中需要用到事务,mybatis插入更新操作默认不提交事务,需要手动写提交代码

    User user = new User();
    user.setUsername("John Snow");
    user.setPassword("123456");
    user.setId(3);
    sqlSession.update("userMapper.update", user);
    sqlSession.commit();
    

    删除

    映射文件

    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>
    

    测试代码

    插入修改等操作在mybatis中需要用到事务,mybatis插入更新操作默认不提交事务,需要手动写提交代码

    sqlSession.delete("userMapper.delete", 3);
    sqlSession.commit();
    
  • 相关阅读:
    GCD
    hexo 部署 githubPage 部署不了的问题
    vim 常见操作
    linux 常见目录的作用
    cd 简化命令
    linux 系统运行级别
    APNIC IP 库
    linux 安装ssh
    linux
    Android知识点总结
  • 原文地址:https://www.cnblogs.com/mingriyingying/p/13639559.html
Copyright © 2011-2022 走看看