Mybatis入门之增删改查

Mybatis入门之增删改查

导入包:

引入配置文件:

sqlMapConfig.xml(mybatis的核心配置文件)、log4j.properties(日志记录文件)

<?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>
    <!-- 和Spring整合后 environments配置将废除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 加载映射文件 -->
    <mappers>
        <mapper resource="deep/sqlmap/Account.xml"/>
    </mappers>
</configuration>
#Global logging configuration
log4j.rootLogger=DEBUG,stdout
#Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p[%t]-%m%n

数据库准备:(略)

实体类编写后针对实体类编写的映射文件

<?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:命名空间,用于隔离sql -->
<mapper namespace="account">
    <!-- 通过ID查询一个用户 -->
    <!-- parameterType入参的类型,resultType返回值的类型 -->
    <!-- #{v} 参数占位符 -->
    <select id="findUserById" parameterType="Integer" resultType="deep.pojo.Account">
        select * from account where id = #{v}
    </select>

    <!--
        #{}            占位符
        ${}            字符串拼接
     -->
    <!-- 根据用户名模糊查询用户列表 -->
    <select id="findUserByUsername" parameterType="String" resultType="deep.pojo.Account">
        <!-- 这种方式不防止sql注入 -->
        <!-- select * from account where username like ‘%${value}%‘ -->
        select * from account where username like "%"#{v}"%"
    </select>

    <!-- 添加用户 -->
    <insert id="insertUser" parameterType="deep.pojo.Account">
        <!-- 在查询结束后查询最新插入的id,并返回给对象,赋值给对象的id属性 -->
        <selectKey keyProperty="id" resultType="Integer" order="AFTER">
            select LAST_INSERT_ID()
        </selectKey>
        insert into account (username,birthday,address,sex)
        value (#{username},#{birthday},#{address},#{sex})
    </insert>

    <!-- 更新 -->
    <update id="updateUserById" parameterType="deep.pojo.Account">
        update account
        set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address}
        where id = #{id}
    </update>

    <!-- 删除 -->
    <delete id="deleteUserById" parameterType="Integer">
        delete from account
        where id = #{v}
    </delete>

</mapper>    

执行

package deep.junit;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

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 org.junit.Test;

import deep.pojo.Account;

public class MyBatisFirstTest {

    @Test
    public void testMybatis() throws Exception {
        //加载核心配置文件
        String resource = "sqlMapConfig.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //执行sql语句
        Account account = sqlSession.selectOne("account.findUserById", 1);

        System.out.println(account);
    }

    //根据用户名称模糊查询用户列表
    @Test
    public void testFindUserByUsername() throws Exception{
        String resource = "sqlMapConfig.xml";
        InputStream in = Resources.getResourceAsStream(resource);

        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //执行sql语句
        List<Account> accounts = sqlSession.selectList("account.findUserByUsername", "五");
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    //根据用户名称模糊查询用户列表
        @Test
        public void testInsertUser() throws Exception{
            String resource = "sqlMapConfig.xml";
            InputStream in = Resources.getResourceAsStream(resource);

            //创建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

            //创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();

            //执行sql语句
            Account account = new Account();
            account.setUsername("麻子2");
            account.setBirthday(new Date());
            account.setAddress("sdfasdfads");
            account.setSex("男");
            int i = sqlSession.insert("account.insertUser", account);

            //自己手动提交事务
            sqlSession.commit();

            System.out.println(account.getId());
        }

    //更新用户
        @Test
        public void testUpdateUserById() throws Exception{
            String resource = "sqlMapConfig.xml";
            InputStream in = Resources.getResourceAsStream(resource);

            //创建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

            //创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();

            //执行sql语句
            Account account = new Account();
            account.setId(28);
            account.setUsername("麻子更新");
            account.setBirthday(new Date());
            account.setAddress("地址更新");
            account.setSex("女");
            int update = sqlSession.update("account.updateUserById", account);

            //自己手动提交事务
            sqlSession.commit();
        }

        //更新用户
                @Test
                public void testDelete() throws Exception{
                    String resource = "sqlMapConfig.xml";
                    InputStream in = Resources.getResourceAsStream(resource);

                    //创建SqlSessionFactory
                    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

                    //创建SqlSession
                    SqlSession sqlSession = sqlSessionFactory.openSession();

                    sqlSession.delete("account.deleteUserById", 28);

                    //自己手动提交事务
                    sqlSession.commit();
                }

}

原文地址:https://www.cnblogs.com/deepSleeping/p/10444075.html

时间: 2024-10-26 20:01:38

Mybatis入门之增删改查的相关文章

MyBatis入门案例 增删改查

一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybat

mybatis入门(二):增删改查

mybatis的原理: 1.mybatis是一个持久层框架,是apache下的顶级项目 mybatis托管到googlecode下,目前托管到了github下面 2.mybatis可以将向prepareStatement中输入的参数自动进行输入映射,将查询结果集灵活的映射成java对象.(输出映射) mybatis的一般使用到的maven包: <dependency> <groupId>mysql</groupId> <artifactId>mysql-co

mybatis入门二-----增删改查

一.使用MyBatis对表执行CRUD操作--基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapp

Mybatis简单的入门之增删改查

一般的步骤如下 1.添加Mybatis所需要的包,和连接数据库所需的包 2.配置mybatis-config.xml文件 3.配置与pojo对应的映射文件 mybatis-config,xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http:/

mybatis(单表增删改查)

(mybatis注意各个文件的映射问题) 用到的t_user数据库脚本: -- 导出 mybatis 的数据库结构 CREATE DATABASE IF NOT EXISTS `mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `mybatis`; -- 导出 表 mybatis.t_user 结构 CREATE TABLE IF NOT EXISTS `t_user` ( `id` int(10) NOT NULL AUTO_INCREM

mybatis(单表增删改查useMapper版)

数据库脚本(注意测试时先add-->load-->update-->delete-->list)UserMapper版 -- -------------------------------------------------------- -- 主机: 127.0.0.1 -- 服务器版本: 5.5.36-MariaDB - mariadb.org binary distribution -- 服务器操作系统: Win32 -- HeidiSQL 版本: 8.0.0.4396 --

ztree使用系列三(ztree与springmvc+spring+mybatis整合实现增删改查)

在springmvc+spring+mybatis里整合ztree实现增删改查,上一篇已经写了demo,下面就只贴出各层实现功能的代码: Jsp页面实现功能的js代码如下: <script> //用于捕获分类编辑按钮的 click 事件,并且根据返回值确定是否允许进入名称编辑状态 function beforeEditName(treeId, treeNode) { var zTree = $.fn.zTree.getZTreeObj("treeDemo"); zTree.

SpringMVC,MyBatis商品的增删改查

一.需求 商品的增删改查 二.工程结构 三.代码 1.Mapper层 (1) ItemsMapperCustom.java 1 package com.tony.ssm.mapper; 2 3 import java.util.List; 4 5 import com.tony.ssm.po.ItemsCustom; 6 import com.tony.ssm.po.ItemsQueryVo; 7 8 public interface ItemsMapperCustom { 9 //商品查询列表

Hibernate入门_增删改查

一.Hibernate入门案例剖析:  ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private Integer age; private String name; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public Integer getAge()