Mybatis概述
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理注册驱动、创建Connection、创建Statement、手动设置参数、结果集检索及映射等繁杂的过程代码。
1.基本操作
配置文件
注:lib包需解压
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db1
jdbc.username=root
jdbc.password=123456
SqlMapConfig.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>
<!--抽取数据库配置-->
<!-- <properties>-->
<!-- <property name="jdbc.driver" value="com.mysql.cj.jdbc.Driver" />-->
<!-- <property name="jdbc.url" value="jdbc:mysql://localhost:3306/ssm_db1" />-->
<!-- <property name="jdbc.username" value="root" />-->
<!-- <property name="jdbc.password" value="123456" />-->
<!-- </properties>-->
<!-- 抽取成文件-->
<properties resource="db.properties" />
<!-- java对象属性驼峰,对应数据的下划线-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="ture"/>
</settings>
<!-- 环境: default的值引用什么id,就表示使用什么数据库了-->
<environments default="db1">
<!-- 配置数据库连接信息及事务 -->
<environment id="db1">
<!-- 表示使用事务:默认是自动开启事务 -->
<transactionManager type="JDBC" />
<!-- 使用连接池 -->
<dataSource type="POOLED">
<!-- 数据库连接基本信息 -->
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载一个功能接口-->
<mapper class="com.czxy.ssm.mapper.UserMapper" />
<!-- 表示加载此包下的所有dao接口-->
<!-- <package name="com.czxy.ssm.mapper"/>-->
</mappers>
</configuration>
创建domain包,定义Javabean
定义mapper包,创建接口
查询所有
测试类
public class Test01_SelectAll {
public static void main(String[] args) throws IOException {
//1 加载配置文件
InputStream is= Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
//3 通过工厂获得会话(连接)
SqlSession sqlSession=factory.openSession();
//4 获得功能接口
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
//4 调用功能
List<User> userList = userMapper.selectAll();
//5 打印查询结果
for (User user : userList) {
System.out.println(user);
}
}
}
UserMapper代码
/**
* 查询所有
* @return
*/
@Select("select * from user")
public List<User> selectAll();
添加
测试类
public class Test03_Insert {
public static void main(String[] args) throws IOException {
// 模拟数据
User user = new User();
user.setUid("u004");
user.setUsername("111");
user.setPassword("fanlonggege");
//1 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 通过工厂获得会话
SqlSession sqlSession = factory.openSession();
//4 通过会话获得功能接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//5 添加
Integer result = userMapper.insert(user);
// 提交
sqlSession.commit();
//6 处理数据
System.out.println(result);
//7 释放资源
sqlSession.close();
}
}
UserMapper代码
/**
* 添加
* @param user
* @return
*/
@Insert("INSERT INTO `user`(uid,username,`password`) VALUES(#{uid},#{username},#{password})")
public Integer insert(User user);
模糊查询
测试类
public class Test02_Like {
public static void main(String[] args) throws IOException {
//1 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 通过工厂获得会话
SqlSession sqlSession = factory.openSession();
//4 通过会话获得功能接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//5 查询
List<User> list = userMapper.selectByName("三");
//6 处理数据
for (User user : list) {
System.out.println(user);
}
//7 释放资源
sqlSession.close();
}
}
UserMapper代码
/**
* 模糊查询
* @param name
* @return
*/
@Select("SELECT * FROM `user` WHERE `name` LIKE '%${name}%'")
public List<User> selectByName(@Param("name") String name);
更新
测试类
public class Test04_Update {
public static void main(String[] args) throws IOException {
// 模拟数据
User user = new User();
user.setUid("u004");
user.setUsername("利古拉斯");
user.setPassword("123456");
user.setName("789");
//1 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 通过工厂获得会话
SqlSession sqlSession = factory.openSession();
//4 通过会话获得功能接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//5 添加
Integer result = userMapper.update(user);
// 提交
sqlSession.commit();
//6 处理数据
System.out.println(result);
//7 释放资源
sqlSession.close();
}
}
UserMapper代码
/**
* 更新
* @param user
* @return
*/
@Update("UPDATE `user` SET username=#{username},`password`=#{password}, `name`=#{name} WHERE uid = #{uid};")
public Integer update(User user);
核心配置文件详解:
properties 用于抽取经常修改的内容
方式1:直接抽取
方式2:将进行修改的内容抽取到properties文件中
开启驼峰映射
<!-- 系统参数设置 -->
<settings>
<!-- 驼峰映射:
数据库字段:user_name
java驼峰命名:userName
-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
加载一个类
<mappers>
<!-- 加载一个功能接口 -->
<mapper class="com.czxy.ssm.mapper.UserMapper"/>
</mappers>
加载一个包
<mappers>
<!-- 表示加载此包下的所有dao接口-->
<package name="com.czxy.ssm.mapper"/>
</mappers>
API详解
导入MybatisUtils
public class MyBatisUtils {
// 会话工厂
private static SqlSessionFactory factory;
static{
try {
// 1.1 加载核心配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
// 1.2 获得工厂
factory = new SqlSessionFactoryBuilder().build(is);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static ThreadLocal<SqlSession> local = new ThreadLocal<>();
/**
* 获得新会话
* @return
*/
private static SqlSession openSession(){
SqlSession sqlSession = local.get();
if(sqlSession == null){
sqlSession = factory.openSession();
local.set(sqlSession);
}
return sqlSession;
}
/**
* 获得mapper
* @param clazz
* @return
*/
public static <T> T getMapper(Class<T> clazz){
return openSession().getMapper(clazz);
}
/**
* 释放资源
*/
public static void close() {
SqlSession sqlSession = openSession();
if(sqlSession != null){
sqlSession.close();
}
}
/**
* 提交并释放资源
*/
public static void commitAndclose() {
SqlSession sqlSession = openSession();
if(sqlSession != null){
sqlSession.commit();
close();
}
}
/**
* 回滚并释放资源
*/
public static void rollbackAndclose() {
SqlSession sqlSession = openSession();
if(sqlSession != null){
sqlSession.rollback();
close();
}
}
}
编写Vo,条件查询封装类
public class UserVo {
private String beginTime;
private String endTime;
//get set方法
编写功能接口
/**
* 条件查询
* @param userVo
* @return
*/
@Select("SELECT * FROM `user` WHERE birthday >= #{beginTime} AND birthday <= #{endTime}")
public List<User> condition(UserVo userVo);
测试
public static void main(String[] args) throws IOException {
//1 通过会话获得功能接口
UserMapper userMapper = MyBatisUtils.getMapper(UserMapper.class);
//2 更新
UserVo userVo = new UserVo();
userVo.setBeginTime("2010");
userVo.setEndTime("2020");
List<User> list = userMapper.condition(userVo);
// 打印结果
list.forEach(System.out::println);
//3 提交并关闭
MyBatisUtils.commitAndclose();
}
输出:结果集映射
- 结果集映射:查询结果 与 JavaBean之间的映射关系。表的列名和JavaBean的属性名对应关系。
- @Results 用于配置JavaBean和表的映射关系的
- @Result 配置JavaBean一个属性和 表的一个列之间对应关系。
- @ResultMap 共享已经映射关系
- 实例1:JavaBean和表映射关系
@Select("select * from user")
@Results({
@Result(column = "user_name",property = "userName"),
@Result(column = "password", property = "password")
})
public List<User> selectAll();
实例2:共享映射关系
@Select("SELECT * FROM `user` WHERE `name` LIKE '%${name}%'")
@ResultMap("userResultMap")
public List<User> selectByName(@Param("name") String name);
多表操作:一对多
JavaBean:User
public class User {
private String uid;
private String userName;
private String password;
private String name;
private String email;
private Date birthday;
private String sex;
private Integer state;
private String code;
JavaBean:Order
public class Order {
private String oid; // 订单编号
private Date ordertime; // 下单时间
private Double total; // 订单总金额
private Integer state; // 订单状态 0 未支付 1 已支付 2已发货 3已收货
private String address; // 收货人地址
private String name; // 收货人姓名
private String telephone; // 收货人电话
private String uid;
对应关系
public class User {
// 一对多关系:一个用户拥有多个订单
private List<Order> orderList = new ArrayList<>()
UserMapper
public interface UserMapper {
/**
* 查询所有
* @return
*/
@Select("select * from user")
@Results(id="userResultMap", value={
@Result(column = "user_name",property = "userName"),
@Result(column = "password", property = "password")
})
public List<User> selectAll();
}
OrderMapper
查询指定用户的所有的订单
public interface OrderMapper {
/**
* 查询指定用户的所有订单
* @param uid
* @return
*/
@Select("SELECT * FROM orders WHERE uid = #{uid}")
public List<Order> selectAllByUid(@Param("uid") String uid);
}
user测试
public class Test01_SelectAll {
public static void main(String[] args) throws IOException {
//1 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 通过工程获得会话(连接)
SqlSession sqlSession = factory.openSession();
//4 获得功能接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//5 进行查询
List<User> list = userMapper.selectAll();
//6 处理数据
for(User user: list) {
System.out.println(user);
}
//7 释放资源
sqlSession.close();
}
}
order测试
public class Test02_SelectAllOrderByUId {
public static void main(String[] args) throws IOException {
//1 加载配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 通过工程获得会话(连接)
SqlSession sqlSession = factory.openSession();
//4 获得功能接口
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
//5 进行查询
List<Order> list = orderMapper.selectAllByUid("u001");
//6 处理数据
list.forEach(System.out::println);
//7 释放资源
sqlSession.close();
}
}