MyBatis框架使用流程和部分总结
MyBatis框架使用流程和部分总结
1.mybatis介绍
1.1 -mybatis是基于ibatis的数据库持久层框架,其最大的特点就是支持个性化sql的编写,相对于SpringDataJpa这种全自动类型的框架来说,其开发效率相对较低,但由于能够自定义sql,所以其性能方面是能够控制的,也就是有优化的空间,学习成本低;
1.2 -而SpringJpa这种全自动框架,框架帮我们完成了几乎所有工作,包括数据库sql的编写,而该框架要兼容各大数据库,因此其sql语句是及其冗长的,虽然框架什么都帮我们做了,开发效率也高,但要做sql优化的话,需要较高成本,因此,SpringJpa框架相对于myBatis来说较为笨重,而mybatis则轻量灵活.
1.3 -目前大多数公司都使用的是SSM即(Spring-SpringMVC-Mybatis)框架
1.4 -因此Mybatis是每位后端程序员必须掌握的框架之一.
2.项目构建流程
创建一个简单的java项目(工具使用的是IDEA)
->创建lib文件夹,将需要的jar包导入
再创建一个资源文件夹
准备各种配置文件
资源文件夹中放置的文件
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>
<!--引用数据库连接参数-->
<properties resource="jdbc.properties"/>
<!--mybatis取别名的标签,别名不区分大小写-->
<typeAliases>
<!--配置一个domain-->
<typeAlias type="cn.itsource.domain.Product" alias="product"/>
<!--配置一个包,包下面的类都取别名(就是它的类型)-->
</typeAliases>
<!--
environments:环境(们),可以有多个
default:默认使用的哪个环境
生产环境,测试环境
-->
<environments default="development">
<!--
environment:一个环境就代表一个数据库的连接信息
-->
<environment id="development">
<!--
配置事务管理器的类型 type=”[JDBC|MANAGED]”
JDBC:使用JDBC的默认事务功能
MANAGED:这个配置几乎没做什么(没有事务)
-->
<transactionManager type="JDBC"></transactionManager>
<!--
dataSource:连接池(数据源) 肯定要写这四个数据库配置
以后集成会改成:DBCP/C3P0
-->
<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>
<!--是路径,用/斜杠,读取配置文件-->
<!--映射对应的xml文件:包含咱们的sql-->
<mapper resource="cn/itsource/domain/ProductMapper.xml"/>
</mappers>
</configuration>
jdbc.properties
//数据库连接参数
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=123456
log4j.properties
# 全局:你要打印的东西:只打印错误
log4j.rootLogger=ERROR, stdout
#log4j.rootLogger=NONE
#把左边包名改成你自己的包名
#局部要求 ERROR:错误 Warn:警告 Info:信息 Debug:调试 TRACE:详细
log4j.logger.cn.itsource=TRACE
#代表的是打印的位置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#打印的格式(可以灵活地指定布局模式)
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#这里就是自定义的格式 %d:时间 %p:级别
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
基本的配置文件已经准备好了,但是mybatis的配置文件还有一个很重要的,那就是对应实体domain类中的XxxxMapper.xml文件
以Product为列,配置文件如下所示
ProductMapper.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">
<!--
namespece:命名空间
-->
<mapper namespace="cn.itsource.domain.ProductMapper">
<!--
当表中的列与类中的属性对应不上,就需要我们手动配置映射,
resultMap:结果映射(手动映射)
id:名称
type:要映射的对象类型
-->
<resultMap id="ProductMap" type="Product">
<id column="id" property="id"/>
<result column="dir_id" property="dir_id"/>
</resultMap>
<!--
select:查询
以后我们要写很多SQL,Java代表需要精确的找到某一条SQL
怎么找呢? namespece + id
cn.itsource.domain.ProductMapper.findOne
id:这条SQL的唯一名称
parameterType:传入的参数类型(long:大Long还是小long)
long:是大Long _long:小long
resultType:返回的(每一条数据)结果类型 -> 必需写全限定名称
-->
<!--查询一条数据-->
<select id="findOne" parameterType="long" resultType="cn.itsource.domain.Product">
select * from product where id = #{id}
</select>
<!--查询所有数据-->
<select id="findAll" resultType="cn.itsource.domain.Product">
SELECT * FROM product
</select>
<!--保存数据-->
<insert id="save" parameterType="cn.itsource.domain.Product"
useGeneratedKeys="true" keyColumn="id" keyProperty="id">
INSERT INTO product (productName,dir_id,salePrice,supplier,brand,cutoff,costPrice)
VALUES (#{productName},#{dir_id},#{salePrice},#{supplier},#{brand},#{cutoff},#{costPrice})
</insert>
<!--修改-->
<update id="update" parameterType="cn.itsource.domain.Product">
UPDATE product set productName=#{productName},dir_id=#{dir_id},
salePrice=#{salePrice},supplier=#{supplier},
brand=#{brand},cutoff=#{cutoff},costPrice=#{costPrice}
WHERE id=#{id}
</update>
<!--删除-->
<delete id="delete" parameterType="long">
DELETE FROM product WHERE id=#{id}
</delete>
<!--
#与$的区别
1.$必须要求传过来的是对象
它拿的是里面对象的属性
2.#是使用,占位符的方式(预编译) $是直接拼接字符串
预编译的方式:性能更好,更安全,防止sql注入
以后使用:
能用#就用#,如果有#搞不定,就用$拼接字符串
-->
<!-- <select id="findOne2" parameterType="cn.itsource.domain.ProductQuery" resultMap="ProductMap">
SELECT * from product where id = ?
</select>-->
</mapper>
这个Mapper配置文件, 有几个重要的属性
namespace:命名空间,
select,inser,update,delete标签,和其中的id属性
其中命名空间(namespace)+id(“save”)能够帮助你找到类中的具体方法
这是mybatis框架中最重要的一个特点,我们去上面写一下mybatis和jpa的区别吧
通过这个XxxMapper.xml配置文件,我们就能够定制我们的sql语句了
//选一个标签做示例
<select id="findOne" parameterType="long" resultType="cn.itsource.domain.Product">
select * from product where id = #{id}
</select>
//在mybatis中,就是通过在xml配置文件中写sql语句来实现sql语句的定制化的,
//其中通过命名空间namespace+id来确定具体的执行
简单测试
在以上一些简单配置完成之后,我们来做一个简单的配置
1.准备domain,自己准备一个数据库,建表,这些都准备好,
public class Product {
private Long id;
private String productName;
private Double salePrice;
private String supplier;
private String brand;
private Double cutoff;
private Double costPrice;
private Long dir_d;
{
...get
...省略了get/set方法,这个工具自动生成,就不浪费空间了
...set
}
@Override//准备toString,需要打印效果
public String toString() {
return "Product{" +
"id=" + id +
", productName='" + productName + '\'' +
", dir_id=" + dir_d +
", salePrice=" + salePrice +
", supplier='" + supplier + '\'' +
", brand='" + brand + '\'' +
", cutoff=" + cutoff +
", costPrice=" + costPrice +
'}';
}
}
2.准备测试类
public class MybatisTest {
@Test
public void testFindOne() throws Exception{
//1.准备reader
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//2.创建SQLSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
//3.创建session对象
SqlSession sqlSession = factory.openSession();
//4.完成对应操作
//cn.itsource.domain.ProductMapper.findOne ProductMapper
Product product = sqlSession.selectOne("cn.itsource.domain.ProductMapper.findOne", 1L);
//输出查看效果
System.out.println(product);
//关闭sqlSession
sqlSession.close();
}
@Test
public void testFindAll() throws Exception{
/**
*测试,查询所有数据的方法
*/
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession();
List<Product> products = sqlSession.selectList("cn.itsource.domain.ProductMapper.findAll");
products.forEach(e-> System.out.println(e));
sqlSession.close();
}
}
测试成功后截图:
这样我们就完成了一个简单的查询一条数据,那么类比的,当我们对数据库进行一系列的增删改查的时候,同样也是这样的操作,在XxxxMapper.xml中用标签配置特定的sql语句,用namespace+id选中类中的方法,然后执行该方法,这样我们对数据库的操作就ok了.
该框架最大的优点就是能够定制sql语句,而且还是写在xml配置文件,虽然手写sql对程序员来说增加的工作,但能够优化sql则在很大程度上决定了数据库操作的操作效率,mybatis定制化sql的目的就是为了优化数据库的查询.
基本小结
因此,只要了解了mybatis的核心是通过定制化sql来优化数据库操作,就能够明白他的一系列配置文件的作用了,这对日常开发是非常有用的.!