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 {
InputStream is= Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession=factory.openSession();
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.selectAll();
for (User user : userList) {
System.out.println(user);
}
}
}
UserMapper代码
@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");
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = factory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Integer result = userMapper.insert(user);
sqlSession.commit();
System.out.println(result);
sqlSession.close();
}
}
UserMapper代码
@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 {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = factory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.selectByName("三");
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
}
UserMapper代码
@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");
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = factory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Integer result = userMapper.update(user);
sqlSession.commit();
System.out.println(result);
sqlSession.close();
}
}
UserMapper代码
@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 {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static ThreadLocal<SqlSession> local = new ThreadLocal<>();
private static SqlSession openSession(){
SqlSession sqlSession = local.get();
if(sqlSession == null){
sqlSession = factory.openSession();
local.set(sqlSession);
}
return sqlSession;
}
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;
编写功能接口
@Select("SELECT * FROM `user` WHERE birthday >= #{beginTime} AND birthday <= #{endTime}")
public List<User> condition(UserVo userVo);
测试
public static void main(String[] args) throws IOException {
UserMapper userMapper = MyBatisUtils.getMapper(UserMapper.class);
UserVo userVo = new UserVo();
userVo.setBeginTime("2010");
userVo.setEndTime("2020");
List<User> list = userMapper.condition(userVo);
list.forEach(System.out::println);
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;
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 {
@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 {
@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 {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = factory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.selectAll();
for(User user: list) {
System.out.println(user);
}
sqlSession.close();
}
}
order测试
public class Test02_SelectAllOrderByUId {
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = factory.openSession();
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
List<Order> list = orderMapper.selectAllByUid("u001");
list.forEach(System.out::println);
sqlSession.close();
}
}
|