mybatis
mybatisPlus
JPA
mybatis
MyBatis 是一款优秀的持久层框架,说白话就是一款操作数据库的框架。它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
引入依赖、编写Mybatis-Config.xml配置(数据库连接配置)
<!-- mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<?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.数据库连接信息-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="jdbc"></transactionManager>
<dataSource type="pooled">
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEcndoing=utf8"/>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
实际开发:
1.编写Entity的实体类
2.编写Dao接口
3.编写Dao接口映射文件 xml文件
4.在MybatisConfig.xml关联映射文件
5.编写测试类
附:Mybatis工具类
1.编写Entity的实体类
package com.imooc.mybatis.entity;
/**
* 商品实体类,与数据库中的goods表对应;
*/
public class Goods {
private Integer goodsId; // 商品ID
private String title; // 商品标题
private String subTitle; //商品副标题
private Float originalCost; //原始价格
private Float currentPrice; //当前价格
private Float discount; //折扣
private Integer isFreeDelivery; //是否包邮
private Integer categoryId; //商品分类编号
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public Float getOriginalCost() {
return originalCost;
}
public void setOriginalCost(Float originalCost) {
this.originalCost = originalCost;
}
public Float getCurrentPrice() {
return currentPrice;
}
public void setCurrentPrice(Float currentPrice) {
this.currentPrice = currentPrice;
}
public Float getDiscount() {
return discount;
}
public void setDiscount(Float discount) {
this.discount = discount;
}
public Integer getIsFreeDelivery() {
return isFreeDelivery;
}
public void setIsFreeDelivery(Integer isFreeDelivery) {
this.isFreeDelivery = isFreeDelivery;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
}
2.编写Dao接口
import java.util.List;
/**
* Dao接口
*/
public interface GoodsDao{
/**
* 查询所有商品
*/
public List<Goods> findAll();
}
3.编写Dao接口映射文件 xml文件
在resource下创建mappers文件夹,在mappers创建文件good.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="goods">
<select id="findAll" resultType="com.imooc.mybatis.entity.Goods">
select * from t_goods order by goods_id desc limit 10;
</select>
<!--动态sql-->
<!-- 1.where + if -->
<select id="selectUserByNameOrSex" resultType="com.kzy.mybatis.entity.User"
parameterType="com.kzy.entity.User">
select * from user
<where>
<if test="username != null">
username=#{username}
</if>
<if test="sex != null">
and sex=#{sex}
</if>
</where>
</select>
<!-- 2.set+ if -->
<update id="updateUserById" parameterType="com.kzy.mybatis.entity.User">
update user u
<set>
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex}
</if>
</set>
where id=#{id}
</update>
<!--3. choose+when+otherwise-->
<select id="selectUserByChoose" resultType="com.kzy.mybatis.entity.User" parameterType="com.kzy.mybatis.entity.User">
select * from user
<where>
<choose>
<when "id != null and test=id !='' ">
id=#{id}
</when>
<when test="username != null and username !='' ">
and username=#{username}
</when>
<otherwise>
and sex=#{sex}
</otherwise>
</choose>
</where>
</select>
</mapper>
4.在MybatisConfig.xml关联映射文件
让mybatis认识这个goods.xml,需要在mybatis-config.xml中对其进行声明
<mappers>
<mapper resource="mappers/goods.xml"></mapper>
</mappers>
5.编写测试类
public class TestCustomerDao {
public static void main(String[] args) throws Exception {
//1.加载SqlMapConfig.xml
InputStream in = Resources.getResourceAsStream("Mybatis-Config.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.创建SqlSession
SqlSession sqlSession = factory.openSession();
//4.生成Dao接口代理对象
GoodsDao goodsDao= sqlSession.getMapper(GoodsDao.class);
//5.执行Dao接口方法
List<Goods> list = goodsDao.findAll();
for(Goods c:list){
System.out.println(c);
}
//6.释放资源
sqlSession.close();
in.close();
}
}
附:Mybatis工具类
package util;
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 java.io.InputStream;
public class MyBatisUtil {
//获得SqlSession工厂
private static SqlSessionFactory factory;
//创建ThreadLocal绑定当前线程中的SqlSession对象
private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<SqlSession>();
static {
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (Exception e) {
e.printStackTrace();
}
}
//获得连接(从THREAD_LOCAL中获得当前线程SqlSession)
private static SqlSession openSession(){
SqlSession session = THREAD_LOCAL.get();
if(session == null){
session = factory.openSession();
THREAD_LOCAL.set(session);
}
return session;
}
/**
* 释放连接(释放当前线程中的SqlSession)
*/
public static void closeSession(){
SqlSession session = THREAD_LOCAL.get();
session.close();
THREAD_LOCAL.remove();
}
/**
* 提交事务(提交当前线程中的SqlSession所管理的事务)
*/
public static void commit(){
SqlSession session = openSession();
session.commit();
closeSession();
}
/**
* 回滚事务(回滚当前线程中的SqlSession所管理的事务)
*/
public static void rollback(){
SqlSession session = openSession();
session.rollback();
closeSession();
}
/**
* 获得接口实现类对象
* @param clazz 泛型对象
* @param <T> 泛型
* @return
*/
public static <T> T getMapper(Class<T> clazz){
SqlSession session = openSession();
return session.getMapper(clazz);
}
}