学习目标
- 了解Mybatis的基本知识
- 熟悉Mybatis的工作原理
- 掌握Mybatis入门程序的编写
文章目录
1.初始Mybatis
- MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
2.Mybatis入门程序
1.在MySQL数据库中,创建一个名为mybatis的数据库,在此数据库中创建user表,同时插入相关数据.
2.在Eclipse中,创建Java Project工程,将Mybatis的核心JAR包,lib目录中的依赖JAR包,以及MySQl数据库的驱动JAR包一同添加到项目的lib目录下,并发布到类路径中.添加后的目录如下图
3.MySQL默认使用log4j输出日志信息.如果要查看控制台的输出SQL语句,需要在src目录下创建log4j.properties文件
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.mybatis.mapper=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
4.在src目录下,创建一个com.mybatis.po包,在该包下创建持久化类Customer.实际上,Customer就是一个POJO(普通Java对象),Mybatis就是采用POJO作为持久化类来完成对数据库的操作的.
package com.mybatis.po;
public class Customer {
private Integer id; // 主键id
private String username; // 客户名称
private String jobs; // 职业
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 Customer(Integer id, String username, String jobs) {
super();
this.id = id;
this.username = username;
this.jobs = jobs;
}
public Customer() {
}
@Override
public String toString() {
return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + "]";
}
}
5.在src目录下,创建一个com.mybatis.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">
<!-- 根据客户名编号查询客户信息列表 -->
<mapper namespace="com.mybatis.mapper.CustomerMapper">
<!-- 根据客户编号获取客户信息 -->
<select id="findCustomerById" parameterType="Integer"
resultType="com.mybatis.po.Customer">
select * from user where id = #{id}
</select>
<!-- 根据客户名模糊查询客户信息列表 -->
<select id="findCustomerByName" parameterType="String"
resultType="com.mybatis.po.Customer">
select * from user where username like '%${value}%'
</select>
<!-- 添加用户信息 -->
<insert id="addCustomer"
parameterType="com.mybatis.po.Customer">
insert into user
(id,username,jobs)
values
(#{id},#{username},#{jobs})
</insert>
<!-- 更新用户信息 -->
<update id="updateCustomer"
parameterType="com.mybatis.po.Customer">
update user set
username=#{username},jobs=#{jobs} where
id=#{id}
</update>
<!-- 删除客户信息 -->
<delete id="deletetCustomer" parameterType="Integer">
delete from user
where id=#{id}
</delete>
</mapper>
6. 在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>
<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" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/mapper/CustomerMapper.xml" />
</mappers>
</configuration>
7.在src目录下,创建一个com.mybatis.test包,在该包下创建测试类MybatisTest,并在类中编写各种测试方法.
package com.mybatis.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.mybatis.po.Customer;
/*
* 入门程序测试类
*/
public class MybatisTest {
@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,并返回映射结果
Customer customer = sqlSession.selectOne("com.mybatis.mapper.CustomerMapper" + ".findCustomerById", 2);
// 打印输出结果
System.out.println(customer.toString());
// 5.关闭SqlSession
sqlSession.close();
}
@Test
public void findCustomerByNameTest2() 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();
// SqlSession执行映射文件中定义的SQl,并返回映射结果
List<Customer> customers = sqlSession.selectList("com.mybatis.mapper.CustomerMapper" + ".findCustomerByName",
"a");
for (Customer customer : customers) {
// 打印输出结果
System.out.println(customer);
}
// 4.4提交事务
sqlSession.commit();
// 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.setId(5);// 每次添加时需要更改id的值
customer.setUsername("Rose");
customer.setJobs("公务员");
// 4.2执行SqlSession的插入方法,返回的是SQL语句影响的行数
int rows = sqlSession.insert("com.mybatis.mapper.CustomerMapper" + ".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(2);
customer.setUsername("mack");
customer.setJobs("教师");
int rows = sqlSession.update("com.mybatis.mapper.CustomerMapper" + ".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.mybatis.mapper.CustomerMapper" + ".deletetCustomer", 3);
if (rows > 0) {
System.out.println("您成功删除了" + rows + "条数据!");
} else {
System.out.println("删除操作失败!");
}
// 4.4提交事务
sqlSession.commit();
// 5.关闭sqlSession
sqlSession.close();
}
}
8.选中每一个方法名,右击使用JUnit4执行.可在控制台查看输出结果.
3.Mybatis操作总结
- 读取配置文件。
- 根据配置文件构建SqlSessionFactory。
- 通过SqlSessionFactory创建SqlSession。
- 使用SqlSession对象操作数据库(包括查询,添加,修改,删除以及提交事务等)。