• mybatis学习3-入门案例,注解方式


    与mapper.xml方式配置的不同有:没有了UserMapper.xml文件

    mybatis注解方式底层的实现是反射。

    1.前期mysql准备

    CREATE DATABASE mybatis;

    use mybatis;
    CREATE TABLE user(
    id int PRIMARY KEY auto_increment,
    name VARCHAR(30) DEFAULT NULL,
    pwd VARCHAR(30) DEFAULT NULL
    )ENGINE = INNODB DEFAULT CHAR SET utf8

    2.实体类

    public class User {
        private int id;
        private String name;
        private String pwd;
        ....
    }

    3.UserMapper接口

    public interface UserMapper {
        @Select("select * from user;")
        List<User> getUserList();
        @Select("select * from user where id = #{id}")
        User getUserById(int id);
        @Insert("insert into user (name,pwd) values(#{name},#{pwd})")
        int addUser(User user);
        @Update("update user set name = #{name},pwd=#{pwd} where id = #{id }")
        int updateUser(User user);
        @Delete(" delete from user where id = #{id}")
        int deleteUser(int id);
    }

    4.工具类

    public class MybatisUtil {
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            try {
                //第一步,获取mqlSessionFactory对象
                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();
        }
    }

    5.核心配置文件

    <?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>
        <!--配置别名-->
        <typeAliases>
            <package name="com.cong.pojo"/>
        </typeAliases>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?
                    useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <!--每一个mapper.xml文件都需要在mybatis核心配置文件中注册-->
        <mappers>
            <!--常用的方式,每添加一个mapper文件就注册一个-->
            <!--<mapper resource="com/cong/mapper/UserMapper.xml"></mapper>-->
            <!--下面两个的容易出错,接口和mapper.xml文件必须同名且在同一包下-->
            <mapper class="com.cong.mapper.UserMapper"/>
            <!--<package name="com.cong.mapper"></package>-->
        </mappers>
    </configuration>

    6.测试类

    package com.cong.mapper;
    
    import com.cong.pojo.User;
    import com.cong.utils.MybatisUtil;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    public class UserMapperTest {
        @Test
        public void getUserList(){
            //1.获得sqlsession对象
            SqlSession sqlSession= MybatisUtil.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<User> list = userMapper.getUserList();
            for (User user : list) {
                System.out.println(user.toString());
            }
            sqlSession.close();
        }
        @Test
        public void getById(){
            //1.获得sqlsession对象
            SqlSession sqlSession= MybatisUtil.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.getUserById(3);
            System.out.println(user.toString());
            sqlSession.close();
        }
        @Test
        public void save(){
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = new User();
            user.setName("彩虹");
            user.setPwd("182184");
            int res = userMapper.addUser(user);
            if(res>0){
                System.out.println("插入成功");
            }
            sqlSession.commit();
            sqlSession.close();
        }
        @Test
        public void updateUser(){
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = new User();
            user.setName("红红");
            user.setPwd("182184");
            user.setId(3);
            userMapper.updateUser(user);
            sqlSession.commit();
            sqlSession.close();
        }
        @Test
        public void deleteUser(){
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            userMapper.deleteUser(9);
            sqlSession.commit();
            sqlSession.close();
        }
    }

    爱生活,爱码字

    我是匆匆、我曾喂自己半年酒。

    好好生活吧,有缘或许相见。

  • 相关阅读:
    Oracle的导入导出
    Android利用数据库传送数据
    Android相对布局实例
    git拉取github项目
    kafka支持认证SASL_PLAINTEXT
    fluentd插件开发
    解决go依赖包安装问题
    ES/Kibana支持search-guard认证
    logkit docker运行和代码下载
    CentOS安装指定git版本
  • 原文地址:https://www.cnblogs.com/ccoonngg/p/11253235.html
Copyright © 2020-2023  润新知