MyBatis框架----简单入门程序(crud)

1、创建数据库,并在此数据库中创建一个表,提前插入几条数据在这里插入图片描述
2、创建项目,将MyBatis的核心JAR、lib目录下的依赖JAR包,以及MySQL数据库的驱动JAR包一同添加到项目的lib目录下,并发布到类路径中。
在这里插入图片描述
3、在src下创建log4i.properties文件,用于输出日志文件
在这里插入图片描述
4、在src目录下,创建一个包,并在该包下创建持久类以及映射文件(也可以分开)
在这里插入图片描述
CutomerMapper.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.it.po.Customer">
	<!--1.根据客户编号获取客户信息 -->
	<select id="findCustomerById" parameterType="Integer"
		resultType="com.it.po.Customer"> 
		
		select * from t_customer where id = #{id}
	</select> 
	<!--根据客户名模糊查询客户信息列表-->
	<select id="findCustomerByName" parameterType="String"
	    resultType="com.it.po.Customer">
	    <!-- select * from t_customer where username like '%${value}%' -->
	    select * from t_customer where username like concat('%',#{value},'%')
	</select>
	
	<!-- 添加客户信息 -->
	<insert id="addCustomer" parameterType="com.it.po.Customer">
	    insert into t_customer(username,jobs,phone)
	    values(#{username},#{jobs},#{phone})
	</insert>
	
	<!-- 更新客户信息 -->
	<update id="updateCustomer" parameterType="com.it.po.Customer">
	    update t_customer set
	    username=#{username},jobs=#{jobs},phone=#{phone}
	    where id=#{id}
	</update>
	
	<!-- 删除客户信息 -->
	<delete id="deleteCustomer" parameterType="Integer">
	    delete from t_customer where id=#{id}
	</delete>
</mapper>

5、在src目录下,创建MyBatis的核心配置文件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?serverTimezone=GMT" />
				<!-- 连接数据库的用户名 -->
				<property name="username" value="root" />
				<!-- 连接数据库的密码 -->
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>

	<!--2.配置Mapper的位置 -->
	<mappers>
		<mapper resource="com/it/po/CustomerMapper.xml" />
	</mappers>
</configuration>

6、创建一个包,并在该包创建测试类

package com.it.test;

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

import com.it.po.Customer;

public class MybatisTest {
		
	
	@Test
	public void findCustomerByIdTest() throws Exception {
		// 1、读取配置文件
		String resource = "mybatis-config.xml";
		InputStream inputStream = 
                     Resources.getResourceAsStream(resource);
		// 2、根据配置文件构建SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = 
                     new SqlSessionFactoryBuilder().build(inputStream);
		// 3、通过SqlSessionFactory创建SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// 4、SqlSession执行映射文件中定义的SQL,并返回映射结果
		Customer customer = sqlSession.selectOne("com.it.po" + 
					   ".Customer.findCustomerById", 1);
		// 打印输出结果
		System.out.println(customer.toString());
		// 5、关闭SqlSession
		sqlSession.close();
	}
	/**
	 * 根据用户名称来模糊查询用户信息列表
	 */
	@Test
	public void findCustomerByNameTest() throws Exception{	
	    // 1、读取配置文件
	    String resource = "mybatis-config.xml";
	    InputStream inputStream = Resources.getResourceAsStream(resource);
	    // 2、根据配置文件构建SqlSessionFactory
	    SqlSessionFactory sqlSessionFactory = 
	new SqlSessionFactoryBuilder().build(inputStream);
	    // 3、通过SqlSessionFactory创建SqlSession
	    SqlSession sqlSession = sqlSessionFactory.openSession();
	    // 4、SqlSession执行映射文件中定义的SQL,并返回映射结果
	    List<Customer> customers = sqlSession.selectList("com.it.po"
					+ ".Customer.findCustomerByName", "j");
	    for (Customer customer : customers) {
	        //打印输出结果集
	        System.out.println(customer);
	    }
	    // 5、关闭SqlSession
	    sqlSession.close();
	}
	
	/**
	 * 添加客户
	 */
	@Test
	public void addCustomerTest() throws Exception{		
	    // 1、读取配置文件
	    String resource = "mybatis-config.xml";
	    InputStream inputStream = Resources.getResourceAsStream(resource);
	    // 2、根据配置文件构建SqlSessionFactory
	    SqlSessionFactory sqlSessionFactory = 
	    		new SqlSessionFactoryBuilder().build(inputStream);
	    // 3、通过SqlSessionFactory创建SqlSession
	    SqlSession sqlSession = sqlSessionFactory.openSession();
	    // 4、SqlSession执行添加操作
	    // 4.1创建Customer对象,并向对象中添加数据
	    Customer customer = new Customer();
	    customer.setUsername("rose");
	    customer.setJobs("student");
	    customer.setPhone("13333533092");
	    // 4.2执行SqlSession的插入方法,返回的是SQL语句影响的行数
		int rows = sqlSession.insert("com.it.po"
					+ ".Customer.addCustomer", customer);
	    // 4.3通过返回结果判断插入操作是否执行成功
	    if(rows > 0){
	        System.out.println("您成功插入了"+rows+"条数据!");
	    }else{
	        System.out.println("执行插入操作失败!!!");
	    }
	    // 4.4提交事务
	    sqlSession.commit();
	    // 5、关闭SqlSession
	    sqlSession.close();
	}

	/**
	 * 更新客户
	 */
	@Test
	public void updateCustomerTest() throws Exception{		
	    // 1、读取配置文件
	    String resource = "mybatis-config.xml";
	    InputStream inputStream = Resources.getResourceAsStream(resource);
	    // 2、根据配置文件构建SqlSessionFactory
	    SqlSessionFactory sqlSessionFactory = 
	    		new SqlSessionFactoryBuilder().build(inputStream);
	    // 3、通过SqlSessionFactory创建SqlSession
	    SqlSession sqlSession = sqlSessionFactory.openSession();
	    // 4、SqlSession执行更新操作
	    // 4.1创建Customer对象,对对象中的数据进行模拟更新
	    Customer customer = new Customer();
	    customer.setId(4);
	    customer.setUsername("rose");
	    customer.setJobs("programmer");
	    customer.setPhone("13311111111");
	    // 4.2执行SqlSession的更新方法,返回的是SQL语句影响的行数
	    int rows = sqlSession.update("com.it.po"
	            + ".Customer.updateCustomer", customer);
	    // 4.3通过返回结果判断更新操作是否执行成功
	    if(rows > 0){
	        System.out.println("您成功修改了"+rows+"条数据!");
	    }else{
	        System.out.println("执行修改操作失败!!!");
	    }
	    // 4.4提交事务
	    sqlSession.commit();
	    // 5、关闭SqlSession
	    sqlSession.close();
	}

	/**
	 * 删除客户
	 */
	@Test
	public void deleteCustomerTest() throws Exception{		
	    // 1、读取配置文件
	    String resource = "mybatis-config.xml";
	    InputStream inputStream = Resources.getResourceAsStream(resource);
	    // 2、根据配置文件构建SqlSessionFactory
	    SqlSessionFactory sqlSessionFactory = 
	            new SqlSessionFactoryBuilder().build(inputStream);
	    // 3、通过SqlSessionFactory创建SqlSession
	    SqlSession sqlSession = sqlSessionFactory.openSession();
	    // 4、SqlSession执行删除操作
	    // 4.1执行SqlSession的删除方法,返回的是SQL语句影响的行数
	    int rows = sqlSession.delete("com.it.mapper"
	            + ".Customer.deleteCustomer", 4);
	    // 4.2通过返回结果判断删除操作是否执行成功
	    if(rows > 0){
	        System.out.println("您成功删除了"+rows+"条数据!");
	    }else{
	        System.out.println("执行删除操作失败!!!");
	    }
	    // 4.3提交事务
	    sqlSession.commit();
	    // 5、关闭SqlSession
	    sqlSession.close();
	}

	
}

7、测试结果
在这里插入图片描述
8、总结MyBatis的操作步骤

  1. 读取配置文件
  2. 根据配置文件构建SqlSessionFactory
  3. 通过SqlSessionFacory创建SqlSession
  4. 使用SqlSession对象操作数据库
  5. 关闭SqlSession对象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值