zoukankan      html  css  js  c++  java
  • 1.1(Mybatis学习笔记)初识Mybatis

    一、Mybatis下载与使用

      下载地址:https://github.com/mybatis/mybatis-3/releases

      

      下载后解压目录:

      

      需要将lib下的jar包和mybatid-x-x-x.jar包导入(数据库驱动也需要导入)。

      

    二、mybatis工作流程

       2.1 读取mybatis-config.xml配置文件。

       2.2 根据mybatis-config.xml中的<mappers>读取映射文件。

       2.3 通过mybatis-config.xml构建SqlSessionFactory。

       2.4 通过SqlSessionFactory创建sqlSession(包含执行SQL的烦烦烦)。

       2.5 mybatis生成executor接口用于操作数据库,它会根据传递的参数来生成需要执行的sql语句。

       2.6 executor接口有一个MapperStatement类型的参数(包含SQL语句的id、参数等信息)。

       2.7 MapperStatement将传递的参数映射到需要执行的sql语句中,类似JDBC中给sql语句设置参数。

       2.8 execute将数据库执行结果映射到对应java对象。

       

      

    三、Mybatis基本增删改查

      首先 建立t_customer表,建表语句如下:

    CREATE TABLE `t_customer` (
      `id` int(32) NOT NULL AUTO_INCREMENT,
      `username` varchar(50) DEFAULT NULL,
      `jobs` varchar(50) DEFAULT NULL,
      `phone` varchar(16) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

      

      建立完表后,我们首先使用mybatis添加数据。

      准备工作:

      首先需要在src目录下新建log4j.properties文件(可用采用Properties)。  

      log4j.properties

    # Global logging configuration
    log4j.rootLogger=ERROR, stdout
    # MyBatis logging configuration...
    log4j.logger.com.mybatis=DEBUG  //com.mybatis是本地包名,指该包下所有类的日志级别为DEBUG
    # 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

      

      3.1增加用户

      Customer.java  (用户类)

    public class Customer {
        private Integer id;
        private String username;
        private String jobs;
        private String phone;
        public int getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getJobs() {
            return jobs;
        }
        public void setJobs(String jobs) {
            this.jobs = jobs;
        }
        public String getPhone() {
            return phone;
        }
        public void setPhone(String phone) {
            this.phone = phone;
        }
        
        @Override
        public String toString() {
            return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]";
        }
        
    }

      在src目录下创建一个包(com.xxx.xxx.mapper),在该包下创建文件CustomerMapper.xml

      CustomerMapper.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 = "com.mybatis.mapper.CustomerMapper" >    
            <!-- 添加用户 id为唯一标识符, 设置参数类型为Customer类型 -->
            <insert id = "addCustomer" parameterType = "com.mybatis.first.Customer">
                insert into t_customer(username, jobs,phone) 
                value(#{username}, #{jobs}, #{phone})
            </insert>    
    
        </mapper>

      #{}代表一个占位符,#{username}代表接收Customer类型中属性名为username的属性值。

      在src目录下创建mybatis-config.xml

      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>
        <!-- 配置默认环境为mysql -->
        <environments default = "mysql">
        <!-- 配置id为SQL的数据库环境 -->
            <environment id = "mysql">
            <!-- 设置事务管理类型为JDBC -->
                <transactionManager type = "JDBC"/>
                <!-- 设置数据源 -->
                <dataSource type = "POOLED">
                    <property name = "driver" value = "com.mysql.jdbc.Driver" />
                    <property name = "url" value = "jdbc:mysql://localhost:3306/mybatis" />
                    <property name = "username" value = "root" />
                    <property name = "password" value = "123456" />
                </dataSource>
            </environment>
        </environments>
        <!-- 设置映射文件 -->
        <mappers>
            <mapper resource = "com/mybatis/mapper/CustomerMapper.xml"/>
        </mappers>
    </configuration>

      测试添加用户:

    import java.io.IOException;
    import java.io.InputStream;
    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;
    
    
    
    public class MybatisTest {
        public static void main(String[] args) throws IOException {
            String resource = "mybatis-config.xml";
            //获取配置文件输入流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //通过配置文件输入流构建sqlSessionFactory,
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //通过sqlSessionFactory获取sqlSession,true代表设置为自动提交。
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //创建客户
            Customer customer = new Customer();
            customer.setUsername("hcf");
            customer.setJobs("student");
            customer.setPhone("13611110007");
            //执行CustomerMapper.xml文件中,id为xxxCustomer的语句,参数为customer对象。
            int num = sqlSession.insert("com.mybatis.mapper.CustomerMapper.addCustomer", customer);
            System.out.println(num);
            //如果没有设置自动提交,使用insert、update、delete时需要使用sqlSession.commit()手动提交。
            sqlSession.close();
        }
    }

    传递的参数为customer,插入语句中#{xxx}代表对象中属性名为xxx的值。

      3.2删除客户

      再CustomerMapper.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 = "com.mybatis.mapper.CustomerMapper" >
            <!-- 添加用户 -->
            <insert id = "addCustomer" parameterType = "com.mybatis.first.Customer">
                insert into t_customer(username, jobs,phone) 
                value(#{username}, #{jobs}, #{phone})
            </insert>

    <!-- 删除用户 传递的参数类型为Integer --> <delete id = "deleteCustomer" parameterType = "Integer"> delete from t_customer where id = #{id} </delete> </mapper>

      

      测试删除 

    import java.io.IOException;
    import java.io.InputStream;
    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;
    
    
    
    public class MybatisTest {
        public static void main(String[] args) throws IOException {
            String resource = "mybatis-config.xml";
            //获取配置文件输入流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //通过配置文件输入流构建sqlSessionFactory,
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //通过sqlSessionFactory获取sqlSession,true代表设置为自动提交。
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //创建客户
            Customer customer = new Customer();
            customer.setId(9);
            customer.setUsername("hcf");
            customer.setJobs("student");
            customer.setPhone("13611110007");
            //执行CustomerMapper.xml文件中,id为xxxCustomer的语句,参数为Integer对象。
            int num = sqlSession.delete("com.mybatis.mapper.CustomerMapper.deleteCustomer", 9);
            System.out.println(num);
            //如果没有设置自动提交,使用insert、update、delete时需要使用sqlSession.commit()手动提交。
            sqlSession.close();
        }
    }

      3.3修改用户

    <?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 = "com.mybatis.mapper.CustomerMapper" >
    
            
            <!-- 添加用户 参数类型为Customer-->
            <insert id = "addCustomer" parameterType = "com.mybatis.first.Customer">
                insert into t_customer(username, jobs,phone) 
                value(#{username}, #{jobs}, #{phone})
            </insert>
            
            <!-- 更新(修改)用户 参数类型为Customer -->
            <update id = "updateCustomer" parameterType = "com.mybatis.first.Customer">
                update t_customer set
                username = #{username}, jobs = #{jobs}, phone = #{phone}
                where id = #{id}
            </update>
            
            <!-- 删除用户 传递的参数类型为Integer -->
            <delete id = "deleteCustomer" parameterType = "Integer">    
                delete from t_customer where id = #{id}
            </delete>
        </mapper>

      测试修改: 

    import java.io.IOException;
    import java.io.InputStream;
    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;
    
    
    
    public class MybatisTest {
        public static void main(String[] args) throws IOException {
            String resource = "mybatis-config.xml";
            //获取配置文件输入流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //通过配置文件输入流构建sqlSessionFactory,
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //通过sqlSessionFactory获取sqlSession,true代表设置为自动提交。
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //创建客户
            Customer customer = new Customer();
            customer.setId(9);
            customer.setUsername("hcf");
            customer.setJobs("student");
            customer.setPhone("13611110007");
            //执行CustomerMapper.xml文件中,id为xxxCustomer的语句,参数为customer对象。
            int num = sqlSession.update("com.mybatis.mapper.CustomerMapper.updateCustomer", customer);
            System.out.println(num);
            //如果没有设置自动提交,使用insert、update、delete时需要使用sqlSession.commit()手动提交。
            sqlSession.close();
        }
    }

      首先数据库类有一条数据:

      

      然后我们运行修改语句。

      

      

      3.4查询用户

    <?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 = "com.mybatis.mapper.CustomerMapper" >
            <!-- 根据ID查询 -->
            <select id="findCustomerById" parameterType = "Integer"
            resultType = "com.mybatis.first.Customer">
                select * from t_customer where id = #{id}
            </select>
            
            <!-- 根据用户名模糊查询 -->
            <select id = "findCustomerByName" parameterType = "String"
                    resultType = "com.mybatis.first.Customer">
                select * from t_customer where username like '%${value}%'
            </select>
            
            <!-- 添加用户 -->
            <insert id = "addCustomer" parameterType = "com.mybatis.first.Customer">
                insert into t_customer(username, jobs,phone) 
                value(#{username}, #{jobs}, #{phone})
            </insert>
            
            <!-- 更新用户 -->
            <update id = "updateCustomer" parameterType = "com.mybatis.first.Customer">
                update t_customer set
                username = #{username}, jobs = #{jobs}, phone = #{phone}
                where id = #{id}
            </update>
            
            <!-- 删除用户 传递的参数类型为Integer -->
            <delete id = "deleteCustomer" parameterType = "Integer">    
                delete from t_customer where id = #{id}
            </delete>
        </mapper>

    测试查询

    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    
    
    public class MybatisTest {
        public static void main(String[] args) throws IOException {
            String resource = "mybatis-config.xml";
            //获取配置文件输入流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //通过配置文件输入流构建sqlSessionFactory,
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //通过sqlSessionFactory获取sqlSession,true代表设置为自动提交。
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //执行CustomerMapper.xml文件中,id为xxxCustomer的语句,参数为Integer对象。
            List<Customer> customers = sqlSession.selectList("com.mybatis.mapper.CustomerMapper.findCustomerById", 9);
            for(Customer temp : customers) {
                System.out.println(customers);
            }
            //如果没有设置自动提交,使用insert、update、delete时需要使用sqlSession.commit()手动提交。
            sqlSession.close();
        }
    }

      

  • 相关阅读:
    switch statement
    Block statement
    Variable hoisting Global variables Constants
    How the Web works
    Discover browser developer tools
    Publishing via GitHub
    第十二节,OpenCV学习(一)图像的读取、显示、保存
    剑指Offer编程题3——从尾到头打印链表
    剑指Offer编程题2——替换空格
    剑指Offer编程题1——二维数组中的查找
  • 原文地址:https://www.cnblogs.com/huang-changfan/p/10452995.html
Copyright © 2011-2022 走看看