四:Mybatis基础:
原生JDBC存在的问题:
1:频繁创建,释放数据库连接,造成系统资源浪费,影响性能
2:SQL语句与JAVA代码耦合,不宜维护
3:查询操作时需要手动将结果集封装到实体,
插入操作时也需要手动将实体数据设置到SQL语句中的占位符
mybatis对原生JDBC存在的问题提出的解决方案:
1:使用数据库连接池初始化连接资源
2:将SQL语句抽取到XML配置文件中
3:使用反射等底层技术,自动将实体与表进行属性与字段的自动映射
mybatis简介:
mybatis是一个优秀的基于java的持久层款框架,他内部封装了jdbc,
使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动,创建
连接,创建statement等繁杂的过程。
mybatis通过xml或注解的方式将要执行的各种statement配置起来,并
通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句。
最后mybatis框架执行sql并将结果映射为java对象并返回,采用ORM思想
解决了实体和数据库映射的问题,对jdbc进行了封装,屏蔽了jdbc api底层访问
细节,使我们不用于jdbc api打交道,就可以完成对数据库的持久化操作。
mybatis入门案例:
JDBC配置文件:(jdbc.properties)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jtdb-small
user=root
password=123456
核心配置文件:(sqlMapperConfig.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标签,加载外部properties标签 -->
<properties resource="jdbc.properties"></properties>
<!-- 自定义别名 -->
<!-- 位置固定:typeAliases 标签顺序必须在 properties,settings,标签之后 -->
<typeAliases>
<!-- 可以简化编写SQL的mapper.xml文件中的resultType,parameterType编写 -->
<typeAlias type="Mybatis.com.pojo.Item" alias="Item"></typeAlias>
</typeAliases>
<!-- default="developement":指定默认的环境名称-->
<environments default="developement">
<!-- id="developement":指定当前环境的名称-->
<environment id="developement">
<!-- type="JDBC":指事务管理类型是JDBC-->
<!-- transactionManager的类型有两种:
JDBC:这个配置就是直接使用了JDBC的提交和回滚设置,
它依赖于从数据源得到的连接来管理事务作用域
MANAGED:这个配置几乎没做什么,它从来不提交或回滚一个连接,
而是让容器来管理事务的整个生命周期。默认情况下它会关闭连接,
然而一些容器并不希望这样,因此需要将closeConnection属性
设置为false来阻止它默认的关闭行为,该参数不常用。-->
<transactionManager type="JDBC"></transactionManager>
<!-- type="POOLED":指定当前数据源类型是连接池 -->
<!-- dataSource的类型有三种:
UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接,
可以理解为原生JDBC
POOLED:这种数据源的实现利用了”池“的概念将JDBC连接对象组织起来,
可以理解为数据库连接池,该参数常用
JNDI:这个数据源的实现是为了在如EJB或应用服务器这类容器中使用,
容器可以集中或在外部配置数据源,然后放在一个JNDI上下文的引用 -->
<dataSource type="POOLED">
<!-- 数据源配置的基本参数 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--加载映射文件-->
<!-- mappers and mapper
该标签的作用是加载映射的,加载方式有如下几种:
A:使用相对于类路径的资源引用:
<mapper resource="mapper/ItemMapper.xml"></mapper>
B:使用完全限定资源定位符(URL):
<mapper url="file:///var/mapper/ItemMapper.xml"></mapper>
C:使用映射器接口实现类的完全限定类名:
<mapper class="mapper.ItemMapper"></mapper>
D:使用包内的映射器接口实现全部注册为映射器:
<package name="mapper"></mapper>
其中B,C,D了解即可 -->
<mappers>
<mapper resource="mapper/ItemMapper.xml"></mapper>
</mappers>
</configuration>
映射文件:(mapper.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!-- 映射文件DTD约束头 -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- mapper:根标签 -->
<mapper namespace="itemMapper"> <!-- namespace:命名空间,与下面语句的ID一起组成查询语句的标识 -->
<!-- select:查询操作,可选的还有 insert,update,delete -->
<!-- id:语句ID,与上面的命名空间一起组成查询语句的标识 -->
<!-- resultType : 查询结果返回对应的实体类型 -->
<select id="findAll" resultType="Item">
<!-- 要执行的SQL语句 -->
SELECT * FROM tb_item
</select>
<!-- 条件查询 -->
<select id="getItemById" resultType="Item">
<!-- 要执行的SQL语句 -->
SELECT * FROM tb_item WHERE id = #{id}
</select>
<!--插入操作 -->
<!-- parameterType : 指定要插入的数据类型 -->
<insert id="save" parameterType="Item">
<!-- #{id} : #{实体属性名} -->
INSERT INTO tb_item VALUE (#{id},#{title},#{sellPoint},#{price},
#{num},#{barcode},#{image},#{cid},#{status},#{created},#{updated})
</insert>
<!--修改操作 -->
<update id="update" parameterType="Item">
UPDATE tb_item SET title = #{title},sell_point = #{sellPoint} WHERE id = #{id}
</update>
<!-- 删除操作 -->
<delete id="delete" parameterType="java.lang.Long">
DELETE FROM tb_item WHERE id = #{id}
</delete>
<!-- selectOne查询操作 -->
<select id="getItemOne" parameterType="java.lang.Long" resultType="Item">
SELECT * FROM tb_item WHERE id = #{id}
</select>
</mapper>
实体类:(Item)
package Mybatis.com.pojo;
import java.math.BigDecimal;
import java.util.Date;
public class Item {
private Long id; //商品编号
private String title; //标题
private String sellPoint; //买点
private BigDecimal price; //价格
private Integer num; //数量
private String barcode; //条形码
private String image; //图片
private Long cid; //外键,详情ID
private Integer status; //状态 1:正常,2下架
private Date created; //创建时间
private Date updated; //修改时间
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSellPoint() {
return sellPoint;
}
public void setSellPoint(String sellPoint) {
this.sellPoint = sellPoint;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Long getCid() {
return cid;
}
public void setCid(Long cid) {
this.cid = cid;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
@Override
public String toString() {
return "Item [id=" + id + ", title=" + title + ", sell_point=" + sellPoint + ", price=" + price + ", num="
+ num + ", barcode=" + barcode + ", image=" + image + ", cid=" + cid + ", status=" + status
+ ", created=" + created + ", updated=" + updated + "]";
}
}
测试案例:(MyBatisTest)
package Mybatis.com.test;
import Mybatis.com.pojo.Item;
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 java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
public class MyBatisTest {
//查询测试
@Test
public void test0() throws IOException {
//加载核心配置文件:
// 通过mybatis提供的Resources工具类,在项目路径下获取核心配置文件,转换为输入流
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
//获得session工厂对象:
// 通过加载核心配置文件的输入流构建一个SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象:
// 通过工厂对象创建SqlSession实例
/**
* openSession():会默认开启一个事务,但事务不会自动提交,
* 故需要手动提交事务,更新数据操作才会持久化到数据库中
* openSession(boolean autoConmmit):参数为是否自动提交,
* 如果设置为true,那么不需要要手动提交事务。
*/
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行SQL语句
//SqlSession是mybatis一个重要的类
/**
* 主要方法有:
* <T> T selectOne(String statement, Object parameter)
* <E> List<E> selectList(String statement, Object parameter)
* int insert(String statement, Object parameter)
* int update(String statement, Object parameter)
* int delete(String statement, Object parameter)
* 操作事务的方法有:
* void commit(); //提交操作
* void rollback(); //回滚操作
*/
List<Item> item = sqlSession.selectList("itemMapper.findAll");
//遍历结果集
for (Item i : item) {
System.out.println(i);
}
//释放资源
sqlSession.close();
}
//条件查询测试
@Test
public void test1() throws IOException {
//加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//模拟Item对象
Item item = new Item();
item.setId(875724L);
//执行SQL语句
List<Item> listitem = sqlSession.selectList("itemMapper.getItemById",item);
//遍历结果集
for (Item i : listitem) {
System.out.println(i);
}
//释放资源
sqlSession.close();
}
//新增测试
@Test
public void test2() throws IOException {
//加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//模拟Item对象
Item item = new Item(123L,"测试",
"测试",new BigDecimal(100),123,
"测试","测试",123L,123,
new Date(),new Date());
// item.setId(123L);
// item.setTitle("测试");
// item.setSellPoint("测试");
// item.setPrice(new BigDecimal(100));
// item.setNum(123);
// item.setBarcode("测试");
// item.setImage("测试");
// item.setCid(123L);
// item.setStatus(123);
// item.setCreated(new Date());
// item.setUpdated(new Date());
//执行SQL语句
sqlSession.insert("itemMapper.save",item);
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
}
//修改操作
@Test
public void test3() throws IOException {
//加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//模拟Item对象
Item item = new Item();
item.setId(123L);
item.setTitle("测试00");
item.setSellPoint("测试00");
//执行SQL语句
sqlSession.update("itemMapper.update",item);
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
}
//修改操作
@Test
public void test4() throws IOException {
//加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行SQL语句
sqlSession.delete("itemMapper.delete",123L);
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
}
//selectOne查询测试
@Test
public void test5() throws IOException {
//加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行SQL语句
Item Item = sqlSession.selectOne("itemMapper.getItemOne",875724L);
//打印结果
System.out.println(Item);
//释放资源
sqlSession.close();
}
}
本文只是个人学习内容整理的笔记,如有侵权,即联系870013269@qq.com删除