myBatis 学习笔记

基础5步走
创建一个用于查看控制台sql语句的.properties文件
创建MyBatis核心配置文件
创建映射文件mapper,用于对数据库进行操作
创建一个普通的类定义一些属性
创建一个测试类进行测试

下方为一个简单的测试,数据库表为t_customer,id自增,username,jobs,phone

1.log4j.properties的创建

# 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

2.mybatis-config的创建

<?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="mysql">   
     <environment id="mysql">   
       <transactionManager type="JDBC"/>  
         <dataSource type="POOLED">      
            <property name="driver" value="com.mysql.jdbc.Driver"/>   
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/>     
            <property name="username" value="root"/>  
            <property name="password" value="123456"/>  
         </dataSource> 
      </environment>  
    </environments>  
                <mappers>   
                 <mapper resource="com/itheima/mapper/CustomerMapper.xml"/>  
                 </mappers>
</configuration>

3.CustomerMapper的创建

<?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="com.itheima.mapper.CustomerMapper">
	<!-- 根据客户编号获得客户信息 -->
 	<select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
    select * from t_customer where id=#{id} 
    </select> 
    
    <!-- 模糊查询 -->
    <select id="findCustomerByName" parameterType="String" resultType="com.itheima.po.Customer">
    select * from t_customer where username like '%${value}%'
    </select>
    
    <!-- 添加客户 -->
    <insert id="addCustomer" parameterType="com.itheima.po.Customer" >
    insert into t_customer(username,jobs,phone)
    value(#{username},#{jobs},#{phone})
    </insert>
    
    <update id="updateCustomer" parameterType="com.itheima.po.Customer">
    update t_customer set
    username=#{username},jobs=#{jobs},phone=#{phone}
    where id=#{id}
    </update>
    
    <delete id="deleCustomer" parameterType="Integer">
    delete from t_customer where id=#{id}
    </delete>
    
    </mapper>

4.Customer类创建

package com.itheima.po;

public class Customer {
private Integer id;
private String username;
private String jobs;
private String phone;

public Integer 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+"]";
}

}

5.测试类创建

package com.itheima.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.itheima.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 session=sqlSessionFactory.openSession();
		//4.sqlsession执行映射文件中定义的sql,并返回结果
		Customer custome=session.selectOne("com.itheima.mapper.CustomerMapper.findCustomerById",1);
		System.out.println(custome.toString());
		session.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 session=sqlSessionFactory.openSession();
		//4.sqlsession执行映射文件中定义的sql,并返回结果
		List<Customer> customers=session.selectList("com.itheima.mapper.CustomerMapper."
				+ "findCustomerByName","j");
		for(Customer customer:customers) {
			System.out.println(""+customer);
		}
		
		session.close();
	}
   
   @Test
   public void addCustomerTest()throws Exception{
	   String resource="mybatis-config.xml";
	   InputStream inputStream=Resources.getResourceAsStream(resource);
	   SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
	   SqlSession session=sessionFactory.openSession();
	   
	   Customer customer=new Customer();
	   customer.setUsername("rose");
	   customer.setJobs("student");
	   customer.setPhone("665465");
	   
	   int rows=session.insert("com.itheima.mapper.CustomerMapper."
				+ "addCustomer",customer);
	   if(rows>0) {
		   System.out.println("成功插入"+rows+"条数据");
	   }
	   else {System.out.println("插入失败");}
	   session.commit();
	   session.close();
   }
   
   @Test
   public void updateCustomerTest()throws Exception{
	   String resource="mybatis-config.xml";
	   InputStream inputStream=Resources.getResourceAsStream(resource);
	   SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
	   SqlSession session=sessionFactory.openSession();
	   
	   Customer customer=new Customer();
	   customer.setId(2);
	   customer.setUsername("jack");
	   customer.setJobs("student");
	   customer.setPhone("132456");
	   
	   int rows=session.insert("com.itheima.mapper.CustomerMapper."
				+ "updateCustomer",customer);
	   if(rows>0) {
		   System.out.println("成功插入"+rows+"条数据");
	   }
	   else {System.out.println("插入失败");}
	   session.commit();
	   session.close();
   }
   
   @Test
   public void deleteCustomerTest()throws Exception{
	   String resource="mybatis-config.xml";
	   InputStream inputStream=Resources.getResourceAsStream(resource);
	   SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
	   SqlSession session=sessionFactory.openSession();
	 
	   int rows=session.insert("com.itheima.mapper.CustomerMapper."
				+ "deleCustomer",2);
	   if(rows>0) {
		   System.out.println("成功插入"+rows+"条数据");
	   }
	   else {System.out.println("插入失败");}
	   session.commit();
	   session.close();
   }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值