• Mybatis的使用及增删改查


    1 导入依赖

    <!--建立meavn项目在pom.xml文件中导入依赖并配置资源加载-->
    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.13.2</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.6</version>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.22</version>
        </dependency>
        <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.18</version>
          <scope>provided</scope>
        </dependency>
      </dependencies>
    
     <build>
        <resources>
          <resource>
            <directory>src/main/resources</directory>
            <includes>
              <include>**/*.properties</include>
              <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
          </resource>
          <resource>
            <directory>src/main/java</directory>
            <includes>
              <include>**/*.properties</include>
              <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
          </resource>
        </resources>
    
    

    2 编写Mybatis核心文件

    <!-- resources目录下创建mybatis-config核心配置文件-->
    <?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?serverTimezone=PRC"/>
                    <property name="username" value="dbone"/>
                    <property name="password" value="dbone"/>
                </dataSource>
            </environment>
        </environments>
    
        <!--  每一个Mapper.xml都需要在Mybatis核心配置文件中注册!  -->
        <mappers>
            <mapper resource="com/lyc/mapper/UserMapper.xml"/>
        </mappers>
    </configuration>
    

    3 编写工厂类

    //com.lyc.utis目录下编写MybatisUtis类
    package com.lyc.utils;
    
    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;
    
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
        static{
            try {
                //获取SqlSessionFactory对象
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        //既然有了 SqlSessionFactory,
        // 顾名思义,我们可以从中获得 SqlSession 的实例。
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
    
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    

    4 编写实体类

    //在com.lyc.pojo中编写实体类(与数据库的表相对应)
    package com.lyc.pojp;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
        private int id;
        private String name;
        private String pwd;
    }
    

    5 编写接口

    //在com.lyc.mapper中编写接口UserMapper文件(一个接口对应一个.xml文件)
    package com.lyc.mapper;
    
    import com.lyc.pojp.User;
    
    import java.util.List;
    
    public interface UserMapper {
        //查询全部用户
        List<User> getUserList();
    
        //根据ID查询用户
        User getUserByID(int id);
    
        //增加一个用户
        int addUser(User user);
    
        //修改用户
        int updateUser(User user);
    
        //删除用户
        int deleteUser(int id);
    }
    

    6 编写与接口对应的.xml文件

    <!-- 在com.lyc.mapper目录中编写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绑定一个对应的/Dao/Mapper接口-->
    <mapper namespace="com.lyc.mapper.UserMapper">
    <!--select 查询语句-->
        <select id="getUserList" resultType="com.lyc.pojp.User">
            select * from mybatis.user
        </select>
        <select id="getUserByID" resultType="com.lyc.pojp.User" parameterType="int">
            select * from  mybatis.user where id = #{id}
        </select>
        <insert id="addUser" parameterType="com.lyc.pojp.User">
            insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd})
        </insert>
        <update id="updateUser" parameterType="com.lyc.pojp.User">
    update mybatis.user set name=#{name},pwd=#{pwd}  where id =#{id}
        </update>
        <delete id="deleteUser" parameterType="int">
            delete from mybatis.user where id = #{id}
        </delete>
    </mapper>
    

    7 编写测试类

    //编写测试类进行测试(src/test/java/com.lyc.mapper/UserMapperTest)
    package com.lyc.mapper;
    
    import com.lyc.pojp.User;
    import com.lyc.utils.MybatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    public class UserMapperTest {
        @Test
        public void test(){
            //第一步:获取SqlSession对象
            SqlSession sqlSession = MybatisUtils.getSqlSession();
    
    
            //执行SQL
            //方法1
            UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
            List<User> userlist = usermapper.getUserList();
    
            //方法2(不推荐)
    //        List<User> userlist = sqlSession.selectList("com.lyc.mapper.UserMapper.getUserList");
            for(User user : userlist){
                System.out.println(user);
            }
    
    
            //关闭SqlSession
            sqlSession.close();
        }
        @Test
        public void getUserById(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUserByID(1);
            System.out.println(user);
            sqlSession.close();
        }
        @Test
        public void adduser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int res = mapper.addUser(new User(4, "jack", "123456"));
            if (res>0){
                System.out.println("插入成功!");
            }
            sqlSession.commit();
            sqlSession.close();
    
        }
        @Test
        public void updateUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            int res = userMapper.updateUser(new User(4, "james", "456123"));
            if (res>0){
            System.out.println("修改成功!");
            }
            sqlSession.commit();
            sqlSession.close();
        }
        @Test
        public void deleteUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int res = mapper.deleteUser(4);
            if (res>0){
                System.out.println("删除成功!");
            }
            sqlSession.commit();
            sqlSession.close();
        }
    }
    
  • 相关阅读:
    C#面试题
    C# 安装部署
    Ribbon菜单栏布局和调整大小
    Dev GridControl使用小结
    C#多线程学习(一) 多线程的相关概念
    PDF转换成图片——11种方案
    C#多线程学习(二) 如何操纵一个线程
    C# 截屏方式
    dev中gridview控件
    (转载) 如何降低project压缩文件的大小? (Quartus II)
  • 原文地址:https://www.cnblogs.com/liuyunche/p/14636774.html
Copyright © 2020-2023  润新知