MyBatis 入门程序

一、终端 上创建数据库,并插入3条数据数据

 

mysql -u root -p

show databases;

create database mybatis;

use mybatis;

create table t_customer( id int(32) primary key auto_increment, username varchar(50), jobs varchar(50), phone varchar(16));

insert into t_customer values('1','kangxf','java','13712345678');
insert into t_customer values('2','majp','android','13798765678');
insert into t_customer values('3','kangxg','ios','13711225678');

select * from t_customer;

+----+----------+---------+-------------+
| id | username | jobs    | phone       |
+----+----------+---------+-------------+
|  1 | kangxf   | java    | 13712345678 |
|  2 | majp     | android | 13798765678 |
|  3 | kangxg   | ios     | 13711225678 |
+----+----------+---------+-------------+

二、创建MyBatisBasic web 项目

  1. 加入开发包和所有依赖包

 

 2 由于MyBatis默认使用log4j输出日志信息,所以如果要查看控制台输出SQL语句,那么就需要在classpath路径下配置日志文件。log4j.properties 配置代码可在mybatis-3.4.2.pdf文件中找到,复制到文件中,并进行修改


# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima = 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 在src目录下创建 com.kangxg.po包 并在该包下创建Customer 持久化类

package com.kangxg.po;
/*
 *  客户持久化类
 */
public class Customer {
  //
  private Integer id;
  private String  username;
  private String  jobs;
  private String  phone;
  
  public Integer getId()
  {
     return this.id ;
  }
  public void setId(Integer id)
  {
      this.id = id;
  }
    
  public String getUsername()
  {
     return this.username ;
  }
  public void setIUsername(String username)
  {
      this.username = username;
  }
  public String getJobs()
  {
     return this.jobs ;
  }
  public void setJobs(String jobs)
  {
      this.jobs = jobs;
  }
  public String getPhone()
  {
     return this.phone ;
  }
  public void setPhone(String phone)
  {
      this.phone = phone;
  }
  @Override
  public String toString()
  {
      return "Customer [id =" + id +"," +"username =" +username +", jobs =" +jobs +", phone =" +phone +"]";
  }
}

4. 在src目录下创建 com.kangxg.Mapper包,并创建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">
<!-- namespace 表示命名空间  -->
<mapper namespace="com.kangxg.mapper.CustomerMapper">
  <!-- 根据客户编号获取客户信息  -->
  <select id="findCustomerById" parameterType = "Integer" resultType="com.kangxg.po.Customer">
    select * from t_customer where id = #{id}
  </select>
</mapper>
   配置文件可在 MyBatis的使用手册PDF文件 第2小节2.1.5 中找到,复制过来就好。

5 在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/mybatis-3-config.dtd">
<configuration>
  <!-- 1.配置环境,默认环境id 为 mysql -->
  <environments default="mysql">
    <!-- 1.2.配置id 为 mysql 的数据库环境-->
    <environment id="mysql">
      <!-- JDBC 事务管理-->
      <transactionManager type="JDBC"/>
       <!-- 数据库连接池-->
      <dataSource type="POOLED">
         <!-- 数据库驱动 -->
         <property name = "driver" value = "com.mysql.jdbc.Driver" />
         <!-- 连接数据库URL-->
         <property name = "url" value = "jdbc:mysql://localhost:3306/mybatis" />
         <!-- 连接数据库的用户名-->
         <property name = "username" value = "root" />
         <!-- 连接数据库的密码-->
         <property name = "password" value = "kangxg198811" />
      </dataSource>
    </environment>
  </environments>
  <!-- 2.配置Mapper的位置-->
  <mappers>
    <mapper resource="com/kangxg/mapper/CustomerMapper.xml"/>
  </mappers>
</configuration>
配置文件可在 MyBatis的使用手册PDF文件 第2小节2.1.2 中找到,复制过来进行修改。

7 在src目录下创建com.kangxg.test包 并创建单元测试文件 MybatisTest

package com.kangxg.test;

import java.io.InputStream;

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 com.kangxg.po.Customer;

public class MybatisTest {
   /*
   * 根据客户编号查询客户信息
   */
    @Test
    public void findCustomerByIdTest()throws Exception
    {
        //1 读取配置文件
        String rescource ="mybatis-config.xml";
        InputStream inputStream = (InputStream) Resources.getResourceAsStream(rescource);
        //2 根据配置文件构建 sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3 通过 SqlSessionFactory 创建  sqlSession
        SqlSession sqlSession =  sqlSessionFactory.openSession();
        //4 sqlSession 执行映射文件中定义的SQL,并返回映射结果 findCustomerById
        Customer customer = sqlSession.selectOne("com.kangxg.mapper"+".CustomerMapper.findCustomerById",1);
        
        System.out.println(customer.toString());
        sqlSession.close();
    }
}

8 debug 运行程序

三、创建用户

1.映射文件增加配置信息

  <!-- 添加用户信息  -->
  <insert id = "addCustomer" parameterType = "com.kangxg.po.Customer" >
     insert into  t_customer(username,jobs,phone) values(#{username},#{jobs},#{phone})
  </insert>
2.向单元测试增加测试方法

      /*
       * 根据客户编号查询客户信息
       */
        @Test
        public void addCustomerTest()throws Exception
        {
            //1 读取配置文件
            String rescource ="mybatis-config.xml";
            InputStream inputStream = (InputStream) Resources.getResourceAsStream(rescource);
            //2 根据配置文件构建 sqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //3 通过 SqlSessionFactory 创建  sqlSession
            SqlSession sqlSession =  sqlSessionFactory.openSession();
            //4 创建 Customer 类型对戏对象,并向对象添加数据
            Customer customer = new Customer();
            customer.setIUsername("mff");
            customer.setJobs("test");
            customer.setPhone("98765432101");
            int rows = sqlSession.insert("com.kangxg.mapper"+".CustomerMapper.addCustomer",customer);
            if(rows >0)
            {
                System.out.println("您成功插入了"+rows +"条数据");
            }
            else
            {
                System.out.println("执行插入操作失败");
            }
            
            sqlSession.commit();
            sqlSession.close();
        }
3,运行程序

四、更新客户

1.映射文件增加配置信息

  <!-- 更新用户信息  -->
  <update id = "updateCustomer" parameterType = "com.kangxg.po.Customer" >
     update t_customer set username = #{username},jobs = #{jobs},phone = #{phone}
      where id = #{id}
  </update>
2.向单元测试增加测试方法
      /*
           * 根据客户编号查询客户信息
           */
            @Test
            public void updateCustomerTest()throws Exception
            {
                //1 读取配置文件
                String rescource ="mybatis-config.xml";
                InputStream inputStream = (InputStream) Resources.getResourceAsStream(rescource);
                //2 根据配置文件构建 sqlSessionFactory
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                //3 通过 SqlSessionFactory 创建  sqlSession
                SqlSession sqlSession =  sqlSessionFactory.openSession();
                //4 创建 Customer 类型对戏对象,并向对象数据更新
                Customer customer = new Customer();
                customer.setId(5);
                customer.setIUsername("xxmn");
                customer.setJobs("ios");
                customer.setPhone("13111111111");
                int rows = sqlSession.insert("com.kangxg.mapper"+".CustomerMapper.updateCustomer",customer);
                if(rows >0)
                {
                    System.out.println("您成功修改了"+rows +"条数据");
                }
                else
                {
                    System.out.println("执行修改操作失败");
                }
                
                sqlSession.commit();
                sqlSession.close();
            }
3,运行程序

 

mysql> select * from t_customer;
+----+----------+---------+-------------+
| id | username | jobs    | phone       |
+----+----------+---------+-------------+
|  1 | kangxf   | java    | 13712345678 |
|  2 | majp     | android | 13798765678 |
|  3 | kangxg   | ios     | 13711225678 |
|  5 | xxmn     | ios     | 13111111111 |
+----+----------+---------+-------------+
4 rows in set (0.00 sec)

五、删除客户

1.映射文件增加配置信息

  <!-- 更新用户信息  -->
  <delete id = "deleteCustomer" parameterType = "Integer" >
      delete from t_customer  where id = #{id}
  </delete>
2.向单元测试增加测试方法
              /*
               * 根据客户编号查询客户信息
               */
                @Test
                public void deleteCustomerTest()throws Exception
                {
                    //1 读取配置文件
                    String rescource ="mybatis-config.xml";
                    InputStream inputStream = (InputStream) Resources.getResourceAsStream(rescource);
                    //2 根据配置文件构建 sqlSessionFactory
                    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                    //3 通过 SqlSessionFactory 创建  sqlSession
                    SqlSession sqlSession =  sqlSessionFactory.openSession();
                    //4 创建 Customer 类型对戏对象,并向对象数据更新
                    int rows = sqlSession.delete("com.kangxg.mapper"+".CustomerMapper.deleteCustomer",5);
                    if(rows >0)
                    {
                        System.out.println("您成功删除了"+rows +"条数据");
                    }
                    else
                    {
                        System.out.println("执行删除操作失败");
                    }
                    
                    sqlSession.commit();
                    sqlSession.close();
                }
3,运行程序

 

mysql> select * from t_customer;
+----+----------+---------+-------------+
| id | username | jobs    | phone       |
+----+----------+---------+-------------+
|  1 | kangxf   | java    | 13712345678 |
|  2 | majp     | android | 13798765678 |
|  3 | kangxg   | ios     | 13711225678 |
+----+----------+---------+-------------+
3 rows in set (0.00 sec)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值