MyBatis框架学习之增删改查

一、MyBatis jar包

下载mybatis的jar包,本文中使用maven进行管理,配置如下:

 <!-- 导入mybatis jar包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>
    <!-- 导入oraclejar包 -->
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>10.2.0.1.0</version>
    </dependency>

其中对于oracle的jar包,需要使用mvn install命令进行安装,需要提前下载好所需要的oraclejar包,具体命令如下:
mvn install:install-file -Dfile=jar包的位置 -DgroupId=pom中groupId -DartifactId=pom中artifactId -Dversion=pom中version -Dpackaging=jar

二、Mybatis xml配置

1、配置数据源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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
                <property name="username" value="****"/>
                <property name="password" value="***"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mybatis/entity/userMapping.xml"/><!-- 映射文件路径 -->
    </mappers>
</configuration>

2、配置实体映射文件userMapping.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">
<mapper namespace="mybatis.testcurd">
    <!-- 以下使用实体来进行增删改查 -->
    <!-- 插入语句 -->
    <insert id="insertUser" parameterType="com.mybatis.entity.User"><!-- 传入的参数的类型 -->
        <selectKey resultType="java.lang.Long" keyProperty="id" order="BEFORE">
            SELECT user_t_seq.nextval FROM DUAL 
        </selectKey>
        insert into user_t(id,username,password,birthday,email,zipcode,address) 
        values(#{id},#{username},#{password},#{birthday},#{email},#{zipcode},#{address})
    </insert>

    <!-- 查询 语句,返回值为list集合-->
    <select id="queryUserInfoById" parameterType="long" resultType="com.mybatis.entity.User">
        select * from user_t where id = #{id}
    </select>

    <!-- 更新语句 -->
    <update id="updateUserById" parameterType="com.mybatis.entity.User">
        update user_t set username=#{username} where id=#{id} 
    </update>

    <!-- 删除语句 -->
    <delete id="deleteUserById" parameterType="long">
        delete user_t where id = #{id}
    </delete>


    <!-- 使用map来进行增删改查 -->
    <insert id="insertUserByMap" parameterType="map">
        <selectKey keyColumn="id" keyProperty="id" order="BEFORE" resultType="java.lang.Long">
            select user_t_seq.nextval from dual
        </selectKey>
        insert into user_t(id,username,password,birthday,email,zipcode,address) 
        values(#{id},#{username},#{password},#{birthday},#{email},#{zipcode},#{address})
    </insert>

    <!--使用map传递参数  -->
    <select id="selectUserByMap" parameterType="map" resultType="map">
        select * from user_t
    </select>

    <select id="selectOneUserByMap" parameterType="map" resultType="map">
        select * from user_t where id= #{id}
    </select>

    <update id="updateUserByMap" parameterType="map">
        update user_t set username=#{username} where id=#{id}
    </update>

    <delete id="deleteUserByMap" parameterType="map">
        delete from user_t where id = #{id}
    </delete>
</mapper>

3、进行测试,测试代码如下:

    private SqlSession session = null;

    @Before
    public void before(){
        SqlSessionFactory factory = SqlSessionFactoryUtil.getSqlSessionFactory();
        if(factory != null){
            session = factory.openSession();
        }
    }

    @Test
    public void insert(){
        User user = new User();
        user.setUsername("张三");
        user.setPassword("zhangsan123");
        user.setAddress("上海市浦东新区周家渡");
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1990-08-03"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setZipcode("217651");
        user.setEmail("zhangsan@126.com");
        if(session != null){
            session.insert("mybatis.testcurd.insertUser",user);
        }
    }

    @Test
    public void testQueryById(){
        if(session != null){
            List<User> lists = session.selectList("mybatis.testcurd.queryUserInfoById", 1L);
            for(User user:lists){
                System.out.println("id:" + user.getId() + ",username:" + user.getUsername() + ",password:"+
                        user.getPassword() + ",address:" + user.getAddress() +
                        ",email:" + user.getEmail() + ",zipcode:" + user.getZipcode());
            }
        }
    }

    @Test
    public void testUpdateById(){
        User user = new User();
        user.setId(1);
        user.setUsername("张三三");
        if(session != null){
            session.update("mybatis.testcurd.updateUserById", user);
        }
    }

    @Test
    public void testDeleteById(){
        if(session != null){
            session.delete("mybatis.testcurd.deleteUserById",1l);
        }
    }

    //使用map来进行数据的增 删 改 查
    @Test
    public void testInsertUserMap(){
        Map map = new HashMap();
        map.put("username", "lisi");
        map.put("password", "lisi123");
        map.put("address", "上海市黄浦区南京东路");
        map.put("email", "lisi@126.com");
        map.put("zipcode", "123456");
        try {
            map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").parse("1990-08-02"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(session != null){
            session.insert("mybatis.testcurd.insertUserByMap", map);
        }
    }
    //使用map进行查询
    @Test
    public void testSelectUserByMap(){
        if(session != null){
            //查询所有
            Map map = session.selectMap("mybatis.testcurd.selectUserByMap","username");
            Set<String> keys = map.keySet();
            for(String key:keys){
                Map mapValue = (Map) map.get(key);
                System.out.println("id:" + mapValue.get("ID") + ",username:" + mapValue.get("USERNAME") + ",password:"+
                        mapValue.get("PASSWORD") + ",address:" + mapValue.get("ADDRESS") +
                        ",email:" + mapValue.get("EMAIL") + ",zipcode:" + mapValue.get("ZIPCODE"));
            }
            Map condition = new HashMap();
            condition.put("id", 21);
            Map oneMap = session.selectMap("mybatis.testcurd.selectOneUserByMap", condition,"username");
            Set<String> oneMapKeys = map.keySet();
            for(String key:oneMapKeys){
                Map mapValue = (Map) map.get(key);
                System.out.println("id:" + mapValue.get("ID") + ",username:" + mapValue.get("USERNAME") + ",password:"+
                        mapValue.get("PASSWORD") + ",address:" + mapValue.get("ADDRESS") +
                        ",email:" + mapValue.get("EMAIL") + ",zipcode:" + mapValue.get("ZIPCODE"));
            }
        }
    }

    //使用map进行更新
    @Test
    public void testUpdateUserByMap(){
        Map map = new HashMap();
        map.put("id",22);
        map.put("username", "李四");
        if(session != null){
            session.update("mybatis.testcurd.updateUserByMap", map);
        }
    }

    @Test
    public void testDeleteUserByMap(){
        Map map = new HashMap();
        map.put("id",22);
        if(session != null){
            session.delete("mybatis.testcurd.deleteUserByMap",map);
        }
    }

    @After
    public void after(){
        if(session != null){
            session.commit();//session需要commit 否则无法尽心提交
            session.close();
        }
    }

4、mybatis的结构如下图所示:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值