Mybatis 的使用

首先 创建一个数据库

2   导包:在Eclipse中,创建一个名为chapter06的Web项目,将MyBatis的核心JAR包、lib目录中的依赖JAR包,以及MySQL数据库的驱动JAR包一同添加到项目的lib目录下, 并发布到类路径中。

3 由于MyBatis默认使用log4j输出日志信息,所以如果要查看控制台的输出SQL语句,那么就需要在classpath路径下配置其

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.qcby.ssm=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

日志文件。在项目的src目录下创建log4j.properties文件

4  在src目录下,创建一个com.itheima.po包,在该包下创建持久化类Customer,并在类中声明id、username、jobs和phone属性,及其对应的getter/setter方法。

package com.qcby.ssm;

import javax.management.loading.PrivateClassLoader;

public class Customer {
	//
	private Integer id;
	//
	private String username;
	@Override
	public String toString() {
		return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + 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;
	}
	private String jobs;
	private String phone;
	

}

5在src目录下,创建一个com.itheima.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当前xml的包路径 -->
<mapper namespace="com.qcby.ssm.Customer"> 
<select id="findCustomerById" parameterType="Integer"
		resultType="com.itheima.po.Customer">
		select * from t_customer where id = #{id}
	</select>
       </mapper>

6连接数据库的配置文件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"> 
                 <!--使用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="728616" />
                            </dataSource>
                       </environment>
                  </environments> 
<mappers>
<mapper resource="com/qcby/ssm/CustomerMapper.xml"/>
</mappers>
</configuration>

7测试文件

package com.qcby.ssm;

import java.io.IOException;
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;

public class MybatisTest {
	//根本据客户编号 查询客户信息
	//一般情况下调用那个id方法名就取什么
	@Test
	public void findCustomerById() throws IOException {
		//读取Mybatis的配置文明件 这里的xml要放在src下面如果不放在路径下面就要加上路径名带斜杠的那种
		String resource="mybatis-config.xml";
		InputStream inputStream=Resources.getResourceAsStream(resource);
		//根据配置文件构建Sqlsessionfactory的工厂
		SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		
		//利用Sqlsessionfactory来创建Sqlsession
		SqlSession sqlSession=sqlSessionFactory.openSession();
		//利用SqlSession来执行Maperr中的sql语句
		//Customer.xml里的namespace.id
		Customer customer=sqlSession.selectOne("com.qcby.ssm.CustomerMapper.findCustomerById",1);
		//打印输出结果
		System.out.println(customer);
		//关闭sqlSession
		sqlSession.close();
		
	}

}

M的增删改查    只用修改CustomerMapper.xml和test文件即可

<?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当前xml的包路径 -->
<mapper namespace="com.qcby.ssm.CustomerMapper"> 
<!-- resultType是customer。java的路径 -->
<select id="findCustomerById" parameterType="Integer"
		resultType="com.qcby.ssm.Customer">
		select * from t_customer where id = #{id}
	</select>
	<!-- 模糊查询 -->
	   <select id="findCustomerByName" parameterType="String"
                   resultType="com.qcby.ssm.Customer">
               select * from t_customer where username like '%${value}%'
       </select>
       <!-- 添加 -->
       <insert id="addCustomer"  parameterType="com.qcby.ssm.Customer">
        insert into t_customer(username,jobs,phone)
        values(#{username},#{jobs},#{phone})
</insert>

<!-- 修改 -->
<update id="updateCustomer" parameterType="com.qcby.ssm.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>

package com.qcby.ssm;

import java.awt.List;
import java.io.IOException;
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;

public class MybatisTest {
	//根本据客户编号 查询客户信息
	//一般情况下调用那个id方法名就取什么
	@Test
	public void findCustomerById() throws IOException {
		//读取Mybatis的配置文明件 这里的xml要放在src下面如果不放在路径下面就要加上路径名带斜杠的那种
		String resource="mybatis-config.xml";
		InputStream inputStream=Resources.getResourceAsStream(resource);
		//根据配置文件构建Sqlsessionfactory的工厂
		SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		
		//利用Sqlsessionfactory来创建Sqlsession
		SqlSession sqlSession=sqlSessionFactory.openSession();
		//利用SqlSession来执行Maperr中的sql语句
		//Customer.xml里的namespace.id
		Customer customer=sqlSession.selectOne("com.qcby.ssm.CustomerMapper.findCustomerById",1);
		//打印输出结果
		System.out.println(customer);
		//关闭sqlSession
		sqlSession.close();
		
	}
	
	
	
	@Test
	public void findCustomerByName() throws IOException {
		//读取Mybatis的配置文明件 这里的xml要放在src下面如果不放在路径下面就要加上路径名带斜杠的那种
		String resource="mybatis-config.xml";
		InputStream inputStream=Resources.getResourceAsStream(resource);
		//根据配置文件构建Sqlsessionfactory的工厂
		SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		
		//利用Sqlsessionfactory来创建Sqlsession
		SqlSession sqlSession=sqlSessionFactory.openSession();
		//利用SqlSession来执行Maperr中的sql语句
		//Customer.xml里的namespace.id
		java.util.List<Customer> customers=sqlSession.selectList("com.qcby.ssm.CustomerMapper.findCustomerByName", "张");
		//打印输出结果
		for(Customer customer:customers) {
			System.out.println(customers);
		}
		//关闭sqlSession
		sqlSession.close();
		
	}
	//添加
	@Test
	public void addCustomer() throws IOException {
		//读取Mybatis的配置文明件 这里的xml要放在src下面如果不放在路径下面就要加上路径名带斜杠的那种
		String resource="mybatis-config.xml";
		InputStream inputStream=Resources.getResourceAsStream(resource);
		//根据配置文件构建Sqlsessionfactory的工厂
		SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		
		//利用Sqlsessionfactory来创建Sqlsession
		SqlSession sqlSession=sqlSessionFactory.openSession();
		//利用SqlSession来执行Maperr中的sql语句
		//Customer.xml里的namespace.id
		
		Customer customer=new Customer();
		customer.setUsername("张思");
		customer.setJobs("司机");
		customer.setPhone("586456");
		int rows=sqlSession.insert("com.qcby.ssm.CustomerMapper.addCustomer", customer);
		//打印输出结果
		if(rows>0) {
			System.out.println("您成功插入了"+rows+"条");
		}else {
			System.out.println("插入失败");
		}
		//提交事务
		sqlSession.commit();
		//关闭sqlSession
		sqlSession.close();
		
	}
	
	//修改
	@Test
	public void updateCustomer() throws IOException {
		//读取Mybatis的配置文明件 这里的xml要放在src下面如果不放在路径下面就要加上路径名带斜杠的那种
		String resource="mybatis-config.xml";
		InputStream inputStream=Resources.getResourceAsStream(resource);
		//根据配置文件构建Sqlsessionfactory的工厂
		SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		
		//利用Sqlsessionfactory来创建Sqlsession
		SqlSession sqlSession=sqlSessionFactory.openSession();
		//利用SqlSession来执行Maperr中的sql语句
		//Customer.xml里的namespace.id
		
		Customer customer=new Customer();
		customer.setId(1);
		customer.setUsername("张二");
		int rows=sqlSession.insert("com.qcby.ssm.CustomerMapper.updateCustomer", customer);
		//打印输出结果
		if(rows>0) {
			System.out.println("您成功修改了"+rows+"条");
		}else {
			System.out.println("修改失败");
		}
		//提交事务
		sqlSession.commit();
		//关闭sqlSession
		sqlSession.close();
		
	}
	
	//删除deleteCustomer
	@Test
	public void deleteCustomer() throws IOException {
		//读取Mybatis的配置文明件 这里的xml要放在src下面如果不放在路径下面就要加上路径名带斜杠的那种
		String resource="mybatis-config.xml";
		InputStream inputStream=Resources.getResourceAsStream(resource);
		//根据配置文件构建Sqlsessionfactory的工厂
		SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		
		//利用Sqlsessionfactory来创建Sqlsession
		SqlSession sqlSession=sqlSessionFactory.openSession();
		//利用SqlSession来执行Maperr中的sql语句
		//Customer.xml里的namespace.id
		int rows=sqlSession.delete("com.qcby.ssm.CustomerMapper.deleteCustomer", 3);
		//打印输出结果
		if(rows>0) {
			System.out.println("您成功删除了"+rows+"条");
		}else {
			System.out.println("删除失败");
		}
		//提交事务
		sqlSession.commit();
		//关闭sqlSession
		sqlSession.close();
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值