首页 > 其他分享 >mybatis增删改查的一些学习代码

mybatis增删改查的一些学习代码

时间:2022-10-27 15:38:18浏览次数:82  
标签:String 改查 UserMapper SqlSession 增删 sqlSession user mybatis

1.UserMapper.xml

<?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">
<!--namespace:名称空间-->
<!--找到接口类UserMapper.java-->
<mapper namespace="com.xxxx.mapper.UserMapper">

    <select id="selectAll" resultType="com.xxxx.entity.User">
        select * from tb_user
    </select>
    <select id="selectByUid" resultType="com.xxxx.entity.User">
        select * from tb_user
                 where uid= #{uid};
    </select>
<!--  条件查询  -->
    <select id="selectBytiaojian" resultType="com.xxxx.entity.User">
        select * from tb_user
                where uname like #{uname};
    </select>
    <insert id="add" useGeneratedKeys="true" keyProperty="uid">
        insert into tb_user (uname,upwd,uage)
        values (#{uname},#{upwd},#{uage});
    </insert>

    <update id="update1">
        update tb_user set
                uname=#{uname},
                upwd=#{upwd},
                uage=#{uage}
        where uid=#{uid};
    </update>
    <update id="update2">
        update tb_user
        <set>
            <if test="uname != null and uname!=''">
                uname=#{uname},
            </if>
            <if test="upwd !=null and upwd!=''">
                upwd=#{upwd},
            </if>
            <if test="uage !=null">
                uage=#{uage}
            </if>
        </set>
         where uid=#{uid};
    </update>

    <delete id="deleteByUid">
        delete from tb_user where uid=#{uid};
    </delete>
<!--注意:mybatis会将数组参数封装成一个Map集合
    默认:array=数组
    如果想修改:可以使用@Param注解,就可以使用uids了
-->
    <delete id="deleteByUids">
        delete from tb_user where uid
        in
            <foreach collection="uids" item="uid" separator="," open="(" close=")">
                #{uid}
            </foreach>

    </delete>



    <select id="selectBytiaojian2" resultType="com.xxxx.entity.User">
        select * from tb_user
            where uname=#{arg0}
            and upwd=#{param2}
    </select>

</mapper>

2.UserMapper.java

package com.xxxx.mapper;

import com.xxxx.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {
    public List<User> selectAll();

    public User selectByUid(int uid);


    public User selectBytiaojian(String uname);

    public void add(User user);

    //返回修改的行数
    public int update1(User user);

    public void update2(User user);

    public void deleteByUid(int id);
    public void deleteByUids(@Param("uids") int[] uids);

    /**
     * 多个参数:封装成Map集合
     * map.put("arg0",参数值1)
     * map.put("param1",参数值1)
     * map.put("arg1",参数值2)
     * map.put("param2",参数值2)
     */
    //不写注解的情况
    public User selectBytiaojian2(String uname,String upwd);

}

3.MyTeat.java

package com.xxxx.test;

import com.xxxx.entity.User;
import com.xxxx.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.util.List;

public class MyTest {
//    @Test为啥不行
    public void testselectAll() throws IOException {
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.执行sql  前面一长串是命名空间+id(在UserMapper.xml里面可以找到)
//        List<User> users=sqlSession.selectList("com.xxxx.mapper.UserMapper.selectAll");

        //获取UserMapper接口的代理对象(这个过程是由mybatis内部实现的)
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
        List<User> users=userMapper.selectAll();

        System.out.println(users);
        //4.释放资源
        sqlSession.close();
    }

//    @Test为啥不行
    public void testselectByUid() throws IOException {
        //接收参数
        int id=2;
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.执行sql  前面一长串是命名空间+id(在UserMapper.xml里面可以找到)
//        List<User> users=sqlSession.selectList("com.xxxx.mapper.UserMapper.selectAll");

        //获取UserMapper接口的代理对象(这个过程是由mybatis内部实现的)
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);


        User user = userMapper.selectByUid(id);
        System.out.println(user.getUid()+"  "+user.getUname()+"  "+user.getUpwd()+"  "+ user.getUage());

        //4.释放资源
        sqlSession.close();

    }
    public void testselectBytiaojian() throws IOException {
        String uname1 = "mi";
//        注意:模糊查询需要在两端加%%
        String uname2 ="%"+uname1+"%";
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.执行sql  前面一长串是命名空间+id(在UserMapper.xml里面可以找到)
//        List<User> users=sqlSession.selectList("com.xxxx.mapper.UserMapper.selectAll");

        //获取UserMapper接口的代理对象(这个过程是由mybatis内部实现的)
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);

//模糊查询
        User user = userMapper.selectBytiaojian(uname2);
        System.out.println(user.getUid()+"  "+user.getUname()+"  "+user.getUpwd()+"  "+ user.getUage());

        //4.释放资源
        sqlSession.close();
    }

    public void testadd() throws IOException {
//        int uid=4;
        String uname="hi";
        String upwd="666666";
        int uage=50;
        User user=new User();
        user.setUname(uname);
        user.setUpwd(upwd);
        user.setUage(uage);

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.执行sql  前面一长串是命名空间+id(在UserMapper.xml里面可以找到)
//        List<User> users=sqlSession.selectList("com.xxxx.mapper.UserMapper.selectAll");

        //获取UserMapper接口的代理对象(这个过程是由mybatis内部实现的)
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);

        userMapper.add(user);
        int uid=user.getUid();
        System.out.println(uid);
        //删除后要手动提交事物
        sqlSession.commit();
        //如果不想的话可以在第2步的时候,写成这样,就会自动提交事物了
//        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.释放资源
        sqlSession.close();
    }
    public void testupdate1() throws IOException {
        int uid=7;
        String uname="hxixixi";
        String upwd="223344";
        int uage=4;
        User user=new User();
        user.setUid(uid);
        user.setUname(uname);
        user.setUpwd(upwd);
        user.setUage(uage);

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.执行sql  前面一长串是命名空间+id(在UserMapper.xml里面可以找到)
//        List<User> users=sqlSession.selectList("com.xxxx.mapper.UserMapper.selectAll");

        //获取UserMapper接口的代理对象(这个过程是由mybatis内部实现的)
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);

        int count=userMapper.update1(user);
        System.out.println(count);
        //删除后要手动提交事物
        sqlSession.commit();
        //如果不想的话可以在第2步的时候,写成这样,就会自动提交事物了
//        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.释放资源
        sqlSession.close();
    }

    public void testupdate2() throws IOException {
        int uid=7;
        String uname="hxixixi";
        String upwd="223344";
        int uage=99;
        User user=new User();
        user.setUid(uid);
        user.setUname(uname);
//        user.setUpwd(upwd);
        user.setUage(uage);

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.执行sql  前面一长串是命名空间+id(在UserMapper.xml里面可以找到)
//        List<User> users=sqlSession.selectList("com.xxxx.mapper.UserMapper.selectAll");

        //获取UserMapper接口的代理对象(这个过程是由mybatis内部实现的)
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);

        userMapper.update2(user);

        //删除后要手动提交事物
        sqlSession.commit();
        //如果不想的话可以在第2步的时候,写成这样,就会自动提交事物了
//        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.释放资源
        sqlSession.close();
    }

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

        int[] uids={3,6};
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //3.执行sql  前面一长串是命名空间+id(在UserMapper.xml里面可以找到)
//        List<User> users=sqlSession.selectList("com.xxxx.mapper.UserMapper.selectAll");

        //获取UserMapper接口的代理对象(这个过程是由mybatis内部实现的)
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);

        userMapper.deleteByUids(uids);

        //删除后要手动提交事物
        sqlSession.commit();
        //如果不想的话可以在第2步的时候,写成这样,就会自动提交事物了
//        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.释放资源
        sqlSession.close();
    }
}

4.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>
<!--propertie 标签中的配置可以供整个文件使用,任何位置都可以引入其中的配置值-->
    <properties resource="mysql.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        <mapper resource="com/xxxx/mapper/UserMapper.xml"/>-->
        <!--   mapper代理方式:扫描包     -->
        <package name="com.xxxx.mapper"/>
    </mappers>
</configuration>

5.mysql.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/course?serverTimezone=UTC&useSSL=false&characterEncoding=UTF-8
username=root
password=123456

 

标签:String,改查,UserMapper,SqlSession,增删,sqlSession,user,mybatis
From: https://www.cnblogs.com/hmy22466/p/16832373.html

相关文章

  • MyBatis详细代码来啦!
    家人们,改代码改到现在真的绝了,终于是改出来了,但是对于某些判断性的小问题还没写,细节性满满的增删改查终于实现啦!目录结构各个文件的代码://User.javapackageorg.examp......
  • Mybatis常见知识点
    Mybatis常见知识点${}和#{}有什么区别${}是简单的字符串替换,属于静态文本替换,并且并不是在预处理的时候进行替换,实在编译的时候进行替换,可能会存在sql注入的风险。替换......
  • 今天独立尝试了增删改查,重点练习了修改语句
    效果还可以  查询语句出了点小问题   修改用到了4个jsp文件跳转其中session.setAttribute()语句的使用,刚开始由于理解上面的混乱,没有成功修改,后来才发现问题......
  • 发现mybatisplus#Wrapper的一个坑
    什么坑?看如下demo代码:publicvoidgetOne(){LambdaQueryWrapper<SbhPlatOrder>wrappers=newLambdaQueryWrapper<>();wrappers.eq(SbhPlatOrd......
  • Springboot和mybatis-plus支持多数据源(多数据库)
    1、pom添加依赖<dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.1</version></de......
  • 利用MVC三层架构做一个案例(利用MyBatis实现增删改查)
    查询所有利用昨天学习到的MyBatis知识,再加上servlet页面的跳转,demo1.jspUserMapper.java(接口)servletDemo.javaMyBatisDemo.java(位于service层)index.jsp显......
  • MyBatis学习笔记之Mapper文件的foreach标签详解
    0x00概述MyBatis的Mapper文件的foreach标签用来迭代用户传递过来的Lise或者Array,让后根据迭代来拼凑或者批量处理数据。如:使用foreach来拼接in子语句。 在学习MyBatis......
  • springboot mybatis-plus dao层调用异常 Invalid bound statement (not found)
    记录一次打包事故。  和同事共同开发项目。开发时访问都是ok。打包后再访问一直报org.apache.ibatis.binding.BindingException:Invalidboundstatement(notfound......
  • springboot使用mybatis连接oracle简单使用
    建表createtablepublic_memo(idsvarchar2(32)notnull,titlevarchar2(255)notnull,contentsclobnotnull,addressvarchar(255)notnull,......
  • mybatis 分析
     jdbcjdbc主要作用是获取数据源,获得查询结果。存在的问题是需要手写sql,对结果集处理麻烦,mybatis主要解决这个两个问题//1.加载类,并注册驱动器(Driver会注册到Driver......