Mybatis
导入相关包
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>Last-version</version></dependency>
Mybatis配置
新建 mybatisConfig.xml 文件放于java工程resources目录下。
<?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><!--| 全局配置设置|| 可配置选项 默认值, 描述|| aggressiveLazyLoading true, 当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。| multipleResultSetsEnabled true, 允许和不允许单条语句返回多个数据集(取决于驱动需求)| useColumnLabel true, 使用列标签代替列名称。不同的驱动器有不同的作法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。| useGeneratedKeys false, 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。| autoMappingBehavior PARTIAL, 指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。| defaultExecutorType SIMPLE, 配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。| defaultStatementTimeout null, 设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时| --><settings><!--是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典Java 属性名 aColumn 的类似映射。 --><setting name="mapUnderscoreToCamelCase" value="true"/><!-- 打印查询语句 --><!--<setting name="logImpl" value="STDOUT_LOGGING" />--><!-- 这个配置使全局的映射器启用或禁用缓存 --><setting name="cacheEnabled" value="true"/><!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 --><setting name="lazyLoadingEnabled" value="true"/><setting name="multipleResultSetsEnabled" value="true"/><setting name="useColumnLabel" value="true"/><setting name="defaultExecutorType" value="REUSE"/><setting name="defaultStatementTimeout" value="25000"/><setting name="logImpl" value="STDOUT_LOGGING"/></settings><!--配置环境和DB链接--><environments default="test1"><environment id="test1"><transactionManager type="JDBC"/><!-- 配置数据库连接信息 --><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://xx.xx.xx.xx/xxx?serverTimezone=GMT%2b8"/><property name="username" value="dev_test1"/><property name="password" value="dev_test1"/></dataSource></environment></environments><!--配置要扫描的mapper--><mappers><!-- <mapper class="com.lucky.dao.ShopInfoMapper"/>--><package name="com.lucky.dao"/></mappers></configuration>
构建 SqlSessionFactory
因为项目不是Spring / Spring Boot ,所以我们需要创建一个 SqlSessionFactory ,SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。
String resource = "mybatisConfig.xml";//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)InputStream is = null;try {is = Resources.getResourceAsStream(resource);} catch (IOException e) {e.printStackTrace();}//构建sqlSession的工厂SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);SqlSession session = sessionFactory.openSession();
Mapper
Mybatis 部分理论上就已经完成了基本的配置,可以通过 session 来调用mapper。但这些mapper往往我们需要自己编写,为了减少编写量引入Mapper 。Mapper给我们提供了基础的数据库CRUD。
导入相关包
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper --><dependency><groupId>tk.mybatis</groupId><artifactId>mapper</artifactId><version>last-version</version></dependency>
mapper继承 Mapper
例如下面是ShopInfoMapper继承Mapper,Mapper提供了各种基础的数据库操作方法。
public interface ShopInfoMapper extends Mapper<TShopInfo> {}
编码代码集成
跟Mybatis集成它分 SqlSessionFactory 创建前和创建后两种方式配置通用Mapper。 这里以创建后为例。
修改创建SqlSessionFactory的代码后如下,添加最后两行
String resource = "mybatisConfig.xml";//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)InputStream is = null;try {is = Resources.getResourceAsStream(resource);} catch (IOException e) {e.printStackTrace();}//构建sqlSession的工厂SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);SqlSession session = sessionFactory.openSession();// 创建一个MapperHelperMapperHelper mapperHelper = new MapperHelper();mapperHelper.processConfiguration(session.getConfiguration());
Demo
创建一个 TShopInfo 实体类,部分如下:
@Datapublic class TShopInfo implements Serializable {/*** 主键*/private Long id;/*** 部门ID*/private Long departmentId;/*** 门店名称*/private String shopName;}
创建一个接口类ShopInfoMapper:
public interface ShopInfoMapper extends Mapper<TShopInfo> {@Select("SELECT shop_name FROM t_shop_info WHERE id = #{id}")String queryByid(int id);}
使用;
ShopInfoMapper shopInfoMapper = session.getMapper(ShopInfoMapper.class);@Test(description = "获取店铺列表")public void getShopListTest1() {String tShopInfo1 = shopInfoMapper.queryByid(170);log.info(tShopInfo1);TShopInfo tShopInfo = new TShopInfo();tShopInfo.setId(169l);// selectOne Mapper提供TShopInfo tShopInfo2 = shopInfoMapper.selectOne(tShopInfo);log.info(tShopInfo2.toString());}
