Mybatis的入门
一、Mybatis基础概述
1.什么是MyBatis?
2.Hibernate与MyBatis的区别
总结:
Hibernate:
优点:只需要写好JAVA代码,其会自动生成SQL,对不熟悉SQL的开发者说效率高
缺点:不够灵活不能决定SQL怎么编写
MyBatis:需要自己写SQL语句,更加灵活
二、Mybatis的下载和使用
1.下载地址
https://github.com/mybatis/mybatis-3/releases
三、Mybatis的工作原理
四、Mybatis的入门程序
1.目标的查询(根据ID和模糊查询)
①.数据库的创建
②.表的创建(设id为主键)
③.插入数据
④.展示数据库
⑤.创建项目并导入JAR包
⑥.创建日志文件
若不知道怎么写,可以再下载的mybatis3.4.2里这个文件下寻找
找到后稍作修改即可
可以将TRACE改成DEBUG级别
⑦.创建实体类
创建后生成getters和setters方法,为了便于展示在生成toString方法。
⑧.写实体类的Mapper.xml方法,根据id进行查询
头文件依旧可以在上面的文件里找到
⑨.写mybatis的核心配置文件
⑩.测试类
⑪.运行结果
⑫.利用客户名称进行模糊查询
只需要在CustomerMapper.xml文件下添加一个sql语句即可(concat为字符串的拼接,返回值sql注入)
再在测试类中稍作查询条件的修改
测试结果
2.目标的增加
只需要在实体类的配置文件中添加
即可。
测试类代码如下
运行结果
3.目标的修改
跟上面相似,直接上代码
4.目标的删除
5.程序代码如下:
日志文件 log4j2.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.cn.pdsu.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
package cn.pdsu.edu.pojos;
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 + "]";
}
}
实体类的配置文件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.pdsu.edu.pojos.Customer">
<!-- parameterType为传入的参数 resultType为返回的结果类型 -->
<!-- 根据客户编号获取客户信息 -->
<select id="findCustomerById" parameterType="Integer"
resultType="cn.pdsu.edu.pojos.Customer">
<!-- #{id}相当于?(占位符) -->
select * from t_customer where id = #{id}
</select>
<!-- 根据客户名称模糊查询客户信息 -->
<select id="findCustomerByName" parameterType="String"
resultType="cn.pdsu.edu.pojos.Customer">
<!-- 只要parameterType是基础类型,全都写value -->
<!-- select * from t_customer where username like '%${value}%' -->
<!-- 防止sql的注入问题,不用${value}这种形式,用#{id}这种形式可以做到 -->
select * from t_customer where username like
concat('%',#{username},"%")
</select>
<!-- 添加客户信息 -->
<!-- parameterType传入参数类型 由于要添加信息,没有返回参数 -->
<insert id="addCustomer"
parameterType="cn.pdsu.edu.pojos.Customer">
<!-- 由于id设置为自增,不用添加 -->
insert into t_customer(username,jobs,phone)
values(#{username},#{jobs},#{phone})
</insert>
<!-- 更新客户信息 根据ID -->
<update id="updateCustomer"
parameterType="cn.pdsu.edu.pojos.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>
核心配置文件
<?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.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC" />
<property name="username" value="XXX" />
<property name="password" value="XXX" />
</dataSource>
</environment>
</environments>
<!-- 2配置Mapper的位置 -->
<mappers>
<!-- 可以配置多个Mapper -->
<mapper resource="cn/pdsu/edu/pojos/CustomerMapper.xml" />
</mappers>
</configuration>
测试类
package cn.pdsu.edu.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.apache.tools.ant.types.CommandlineJava.SysProperties;
import org.junit.Test;
import cn.pdsu.edu.pojos.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。并返回结果映射
// 第一个参数是sql的Id, 第二个参数是传入给sql的占位符的参数
Customer customer = sqlSession.selectOne("cn.pdsu.edu.pojos.Customer.findCustomerById", 1);
// 打印输出结果
System.out.println(customer.toString());
// 关闭SQLSession
sqlSession.close();
}
/**
* 根据用户名称模糊查询用户列表
*
* @throws Exception
*/
@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("cn.pdsu.edu.pojos.Customer.findCustomerByName", "j");
for (Customer customer : customers) {
// 打印输出结果
System.out.println(customer);
}
// 关闭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映射执行文件中定义的SQL。并返回结果映射
// 4.1创建Customer对象,并向其中添加数据
Customer customer = new Customer();
customer.setUsername("rose");
customer.setJobs("student");
customer.setPhone("6666666666");
// 4.2执行SqlSession的插入方法,返回的是SQL影响的行数
// 第一个参数是sql的Id, 第二个参数是传入给sql的占位符的参数
int rows = sqlSession.insert("cn.pdsu.edu.pojos.Customer.addCustomer", customer);
//4.3通返回结果判断是否返回成功
if (rows > 0) {
System.out.println("您成功插入了" + rows + "条信息");
} else {
System.out.println("操作失败");
}// 4.4事务提交---增删改查都涉及到事物提交
sqlSession.commit();
// 关闭customerSQLSession
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映射执行文件中定义的SQL。并返回结果映射
// 4.1创建Customer对象,并向其中添加数据
Customer customer = new Customer();
//由于根据id进行修改,所以要id
customer.setId(4);
customer.setUsername("rose");
customer.setJobs("programmer");
customer.setPhone("999999999999");
// 4.2执行SqlSession的插入方法,返回的是SQL影响的行数
// 第一个参数是sql的Id, 第二个参数是传入给sql的占位符的参数
int rows = sqlSession.update("cn.pdsu.edu.pojos.Customer.updateCustomer", customer);
//4.3通返回结果判断是否返回成功
if (rows > 0) {
System.out.println("您成功修改了" + rows + "条信息");
} else {
System.out.println("修改操作失败");
}// 4.4事务提交---增删改查都涉及到事物提交
sqlSession.commit();
// 关闭customerSQLSession
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映射执行文件中定义的SQL。并返回SQL影响的行数
// 第一个参数是sql的Id, 第二个参数是传入给sql的占位符的参数
int rows = sqlSession.update("cn.pdsu.edu.pojos.Customer.deleteCustomer", 4);
//4.3通返回结果判断是否返回成功
if (rows > 0) {
System.out.println("您成功删除了" + rows + "条信息");
} else {
System.out.println("删除操作失败");
}
// 4.4事务提交---增删改查都涉及到事物提交
sqlSession.commit();
// 关闭customerSQLSession
sqlSession.close();
}
}
五、Mybatis入门小结
1.MyBatis的操作步骤