MyBatis
工作原理:
创建项目,导入需要用到的jar包
在src目录下创建log4j.properties,myBatis的核心配置
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.cn.edu=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
创建持久化类Customer,类中属性对应mysql的表中的数据
package cn.edu.po;
/**
*
* 客户持久化类
*
*/
public class Customer {
private Integer id;//主键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 + "]";
}
}
创建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="cn.edu.po.Customer">
<!-- 根据客户编号获取配置信息 -->
<select id="findCustomerById" parameterType="java.lang.Integer"
resultType="cn.edu.po.Customer">
<!-- 相当于占位符 -->
select * from t_customer where id = #{id}
</select>
<!-- 根据客户名称获取配置信息 -->
<select id="findCustomerByName" parameterType="String"
resultType="cn.edu.po.Customer">
<!-- 相当于占位符 -->
<!-- select * from t_customer where username like '%${value}%' -->
<!-- 放置sql注入问题,也就是多加一个'符号的话就会识别不出来value这个值 ,不用${value}形式 用#{id}形式可以做到 -->
select * from t_customer where username like
concat('%',#{username},'%')
</select>
<insert id="addCustomer" parameterType="cn.edu.po.Customer">
insert into t_customer(username,jobs,phone)
values(#{username},#{jobs},#{phone})
</insert>
<!-- 更新用户信息 -->
<update id="updateCustomer" parameterType="cn.edu.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>
创建测试类MyBatisTest:
package cn.edu.test;
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;
import org.junit.Test;
import cn.edu.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 = new SqlSessionFactoryBuilder().build(inputStream);
// 3.通过工厂构建sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 4.用对象执行xml映射文件中的sql,传入参数,第一个参数为Mapper中sql的id,第二个为占位符的值,不懂的话可转到Mapper中查看
Customer customer = sqlSession.selectOne("cn.edu.po.Customer.findCustomerById", 1);
System.out.println(customer.toString());
//5.关闭流
sqlSession.close();
}
/**
* 模糊查询
*
* @throws Exception
*/
@Test
public void findCustomerBynameTest() throws Exception {
// 1.读取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.根据配置文件构建工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3.通过工厂构建sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Customer> customerList = sqlSession.selectList("cn.edu.po.Customer.findCustomerByName", "j");
for (Customer customer : customerList) {
System.out.println(customer);
}
//5.关闭流
sqlSession.close();
}
/**
* 添加客户
*
* @throws Exception
*/
@Test
public void addCustomerTest() throws Exception {
// 1.读取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.根据配置文件构建工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3.通过工厂构建sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.创建Customer对象并添加数据
Customer customer=new Customer();
customer.setUsername("rose");
customer.setJobs("student");
customer.setPhone("12345678912");
//执行插入,返回了影响的行数
int rows=sqlSession.insert("cn.edu.po.Customer.addCustomer", customer);
if(rows>0)
System.out.println("成功插入"+rows+"条数据!");
else
System.out.println("插入失败");
//提交事务,增删改都涉及到事务,需要提交事务,可以理解为规则,必须有,否则无法存入数据库
sqlSession.commit();
//5.关闭流
sqlSession.close();
}
/**
* 更新客户
*
* @throws Exception
*/
@Test
public void updateCustomerTest() throws Exception {
// 1.读取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.根据配置文件构建工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3.通过工厂构建sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.创建Customer对象并添加数据
Customer customer=new Customer();
customer.setId(5);
customer.setUsername("rose");
customer.setJobs("programmer");
customer.setPhone("11145678912");
//执行更新,返回了影响的行数
int rows=sqlSession.update("cn.edu.po.Customer.updateCustomer", customer);
if(rows>0)
System.out.println("成功更新了"+rows+"条数据!");
else
System.out.println("更新失败");
//提交事务,增删改都涉及到事务,需要提交事务,可以理解为规则,必须有,否则无法存入数据库
sqlSession.commit();
//5.关闭流
sqlSession.close();
}
/**
* 删除客户
*
* @throws Exception
*/
@Test
public void deleteCustomerTest() throws Exception {
// 1.读取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.根据配置文件构建工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3.通过工厂构建sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行删除,返回了影响的行数
int rows=sqlSession.update("cn.edu.po.Customer.deleteCustomer", 5);
if(rows>0)
System.out.println("成功删除了"+rows+"条数据!");
else
System.out.println("删除失败");
//提交事务,增删改都涉及到事务,需要提交事务,可以理解为规则,必须有,否则无法存入数据库
sqlSession.commit();
//5.关闭流
sqlSession.close();
}
}
使用Junit进行单元测试,程序测试成功。程序调试中遇到错误,问题出在Mapper.xml中的parameterType写成了parameterMap,而mybaties中已经不再用这个属性了。
本博客仅供个人学习,请勿用于商业用途。