mybatis框架学习
核心xml配置属性
核心xml配置就是指mybatis-config.xml中的一些属性的配置
- configuration(配置)
- properties(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- databaseIdProvider(数据库厂商标识)
- environment(环境变量)
- mappers(映射器)
properties:引入外部配置文件
用来引入外部的配置。
比如引入外部数据库配置:
<!--加载.properties配置文件-->
<properties resource="db.properties"></properties>
设置(settings)
一些常用的配置
<settings>
<!--开启下划线到驼峰式命名法的自动映射 默认是false-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--是否启用缓存 默认是true-->
<setting name="cacheEnabled" value="true"/>
<!--是否启用延迟加载功能 多对象关联 默认是false-->
<setting name="lazyLoadingEnabled" value="false"/>
<!--是否积极加载所有属性-->
<setting name="aggressiveLazyLoading" value="false"/>
<!--是否使用自动生成主键 默认false-->
<setting name="useGeneratedKeys" value="true"/>
<!--配置mybatis日志输出-->
<setting name="logImpl" value="LOG4J"/>
</settings>
在官网上找到的完整的setting配置:
<settings>
<!--全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。默认true-->
<setting name="cacheEnabled" value="true"/>
<!--延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 默认false-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--是否允许单个语句返回多结果集(需要数据库驱动支持)。 默认是true-->
<setting name="multipleResultSetsEnabled" value="true"/>
<!--使用列标签代替列名。实际表现依赖于数据库驱动,具体可参考数据库驱动的相关文档,或通过对比测试来观察。默认是true-->
<setting name="useColumnLabel" value="true"/>
<!--允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管一些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。默认false-->
<setting name="useGeneratedKeys" value="false"/>
<!--指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示关闭自动映射;PARTIAL 只会自动映射没有定义嵌套结果映射的字段。 FULL 会自动映射任何复杂的结果集(无论是否嵌套)。 默认PARTIAL-->
<setting name="autoMappingBehavior" value="PARTIAL"/>
<!--指定发现自动映射目标未知列(或未知属性类型)的行为。
NONE: 不做任何反应(默认)
WARNING: 输出警告日志 ('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARN)
FAILING: 映射失败 (抛出 SqlSessionException)-->
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<!--配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。 默认SIMPLE-->
<setting name="defaultExecutorType" value="SIMPLE"/>
<!--设置超时时间,它决定数据库驱动等待数据库响应的秒数。-->
<setting name="defaultStatementTimeout" value="25"/>
<!--为驱动的结果集获取数量(fetchSize)设置一个建议值。此参数只可以在查询设置中被覆盖。-->
<setting name="defaultFetchSize" value="100"/>
<!--是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。-->
<setting name="safeRowBoundsEnabled" value="false"/>
<!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。-->
<setting name="mapUnderscoreToCamelCase" value="false"/>
<!--MyBatis 利用本地缓存机制(Local Cache)防止循环引用和加速重复的嵌套查询。 默认值为 SESSION,会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地缓存将仅用于执行语句,对相同 SqlSession 的不同查询将不会进行缓存。-->
<setting name="localCacheScope" value="SESSION"/>
<!--当没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。-->
<setting name="jdbcTypeForNull" value="OTHER"/>
<!--指定对象的哪些方法触发一次延迟加载。-->
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
类型别名(typeAliases)
<typeAliases>
<!--类起别名!-->
<!-- 如果起别名太多了
<typeAlias type="com.lanou.pojo.Product" alias="Product"></typeAlias>
<typeAlias type="com.lanou.pojo.Product" alias="Product"></typeAlias>
<typeAlias type="com.lanou.pojo.Product" alias="Product"></typeAlias>-->
<package name="com.lanou.pojo"></package>
</typeAliases>
环境配置(environments)
<!--环境 连接数据库的环境 default:默认使用的数据库id-->
<environments default="development">
<!--开发库-->
<!--id:当前连接数据库的唯一标识-->
<environment id="development">
<!--增删改 默认使用事务管理 需要手动commit-->
<transactionManager type="JDBC"/>
<!--数据源:连接池-->
<dataSource type="POOLED">
<!--驱动-->
<property name="driver" value="${driver}"/>
<!--url-->
<property name="url" value="${url}"/>
<!--用户名-->
<property name="username" value="${username}"/>
<!--密码-->
<property name="password" value="${password}"/>
</dataSource>
</environment>
映射器(mappers)
<!--加载所有相关的sql mapper 映射文件-->
<mappers>
<mapper resource="com/lanou/mapper/ProductMapper.xml"/>
<mapper resource="com/lanou/mapper/ProductInfoMapper.xml"/>
</mappers>
比如引入db.properties文件中的内容如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybaits
username=root
password=123456
比如引入日志文件log4j.properties
# 全局日志配置
log4j.rootLogger=TRACE, stdout
# MyBatis 日志配置
log4j.logger.com.lanou.mapper=TRACE
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mybatis-config.xml核心配置文件中的代码
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--mybaits核心配置-->
<configuration>
<!--加载.properties配置文件-->
<properties resource="db.properties"></properties>
<settings>
<!--开启下划线到驼峰式命名法的自动映射 默认是false-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--是否启用缓存 默认是true-->
<setting name="cacheEnabled" value="true"/>
<!--是否启用延迟加载功能 多对象关联 默认是false-->
<setting name="lazyLoadingEnabled" value="false"/>
<!--是否积极加载所有属性-->
<setting name="aggressiveLazyLoading" value="false"/>
<!--是否使用自动生成主键 默认false-->
<setting name="useGeneratedKeys" value="true"/>
<!--配置mybatis日志输出-->
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<!--类起别名!-->
<!-- 如果起别名太多了
<typeAlias type="com.lanou.pojo.Product" alias="Product"></typeAlias>
<typeAlias type="com.lanou.pojo.Product" alias="Product"></typeAlias>
<typeAlias type="com.lanou.pojo.Product" alias="Product"></typeAlias>-->
<package name="com.lanou.pojo"></package>
</typeAliases>
<!--环境 连接数据库的环境 default:默认使用的数据库id-->
<environments default="development">
<!--开发库-->
<!--id:当前连接数据库的唯一标识-->
<environment id="development">
<!--增删改 默认使用事务管理 需要手动commit-->
<transactionManager type="JDBC"/>
<!--数据源:连接池-->
<dataSource type="POOLED">
<!--驱动-->
<property name="driver" value="${driver}"/>
<!--url-->
<property name="url" value="${url}"/>
<!--用户名-->
<property name="username" value="${username}"/>
<!--密码-->
<property name="password" value="${password}"/>
</dataSource>
</environment>
<!--测试库-->
<environment id="test">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!--数据库是写死的-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybaits"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
<!--mysql oracle-->
</environments>
<!--加载所有相关的sql mapper 映射文件-->
<mappers>
<mapper resource="com/lanou/mapper/ProductMapper.xml"/>
<mapper resource="com/lanou/mapper/ProductInfoMapper.xml"/>
</mappers>
</configuration>
xml映射文件
select
查询语句
属性 | 用法 |
---|---|
id | 在命名空间中唯一的标识符,可以被用来引用这条语句。 |
parameterType | 将会传入这条语句的参数的类全限定名或别名。 |
resultType | 返回结果的类全限定名或别名。 resultType 和 resultMap 之间只能同时使用一个。 |
resultMap | 对外部 resultMap 的命名引用。 |
flushCache | 将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false。 |
useCache | 将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来,默认值:对 select 元素为 true。 |
timeout | 多长时间未响应 |
fetchSize | 这是一个给驱动的建议值,尝试让驱动程序每次批量返回的结果行数等于这个设置值。 默认值为未设置(unset)(依赖驱动)。 |
statementType | 可选 STATEMENT,PREPARED 或 CALLABLE。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。 |
databaseId | 如果配置了数据库厂商标识(databaseIdProvider),MyBatis 会加载所有不带 databaseId 或匹配当前 databaseId 的语句;如果带和不带的语句都有,则不带的会被忽略。 |
resultOrdered | 这个设置仅针对嵌套结果 select 语句:如果为 true,将会假设包含了嵌套结果集或是分组,当返回一个主结果行时,就不会产生对前面结果集的引用。 这就使得在获取嵌套结果集的时候不至于内存不够用。默认值:false。 |
resultSets | 这个设置仅适用于多结果集的情况。它将列出语句执行后返回的结果集并赋予每个结果集一个名称,多个名称之间以逗号分隔。 |
insert, update 和 delete
增删改
属性 | 用法 |
---|---|
flushCache | 默认值:(对 insert、update 和 delete 语句)true。 |
keyColumn | (仅适用于 insert 和 update)设置生成键值在表中的列名 |
keyProperty | (仅适用于 insert 和 update)指定能够唯一识别对象的属性 |
结果映射
resultMap
属性 | 用法 |
---|---|
association | 多对一映射 |
javaType | 多对一映射 |
column | 表中的字段(列) |
property | java类属性名 |
autoMappering=“true” 不用配置result
属性 | 用法 |
---|---|
collection | 一对多 |
<!--一对多映射-->
<select id="findProductList" resultMap="productMap">
select p.id as tid,p.product_type,p.status,i.* from
product p left outer join productInfo i on p.id = i.p_id
</select>
<!--id:唯一 type:返回对象类型-->
<resultMap id="productMap" type="Product">
<!--id 定义主键匹配关系 column:列名 property:类型属性名-->
<id column="tid" property="id"></id>
<!---->
<result column="product_type" property="productType"></result>
<result column="status" property="status"></result>
<!--集合关系 一对多 映射-->
<!--column指的是外键 ofType指的是这个集合中存在的bean类-->
<collection property="proInfoList" column="type_id" ofType="ProductInfo">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<result column="p_id" property="pId"></result>
<result column="info" property="info"></result>
</collection>
</resultMap>
多对一映射
<select id="findProductList" resultMap="productInfoMap">
select i.*,p.id as tid, p.product_type,p.status
from productinfo i join product p on i.p_id =p.id
</select>
<resultMap id="productInfoMap" type="ProductInfo" autoMapping="true">
<id column="id" property="id"></id>
<!--<result column="" property=""/>-->
<!--多对一映射-->
<association property="product" javaType="Product" column="p_id" autoMapping="true">
<id column="id" property="id"></id>
<!--autoMappering="true" 不用配置下面的result-->
<!--<result column="" property=""/>-->
</association>
</resultMap>
动态 SQL
where if语句
where关键字作用:
1> 当where代码块中所有条件都不成立的时候, 整个where代码块不生效
2> 当where代码块中至少有一个条件成立的时候, 它会 在where代码块之前添加一个 where关键字 如果你的where代码块是以and|or开头, 它会帮你删掉第一个and|or
商品类型不为空
<select id="findProducts" resultType="Product">
select * from product
<where>
<if test="productType!=null">product_type=#{productType}</if>
and status = #{status}
</where>
</select>
set 用于update语句
修改id是某某的类型和状态
<update id="updateProduct">
update product
<set>
<if test="productType!=null">product_type=#{productType},</if>
<if test="status!=0">status=#{status}</if>
</set>
where id = #{id}
</update>
foreach主要是用来做遍历。
典型的应用场景是SQL中的in语法中,select * from user where uid in (1,2,3) 在这样的语句中,传入的参数部分必须依靠 foreach遍历才能实现。比如批量添加商品信息
<insert id="saveBatch" parameterType="Product" databaseId="mysql" statementType="STATEMENT" useGeneratedKeys="true" keyProperty="id">
insert into product(product_type,status) values
<foreach collection="list" item="obj" separator=",">
(#{obj.productType},#{obj.status})
</foreach>
</insert>
练习
创建一个项目导包
Product对应数据库中的商品分列表
import org.apache.ibatis.type.Alias;
import java.util.List;
@Alias(value = "Product")//级别比包的高
public class Product {
private Integer id;
private String productType;
private Integer status;
private List<ProductInfo> proInfoList;
//setter和getter
}
ProductInfo对应数据表中的商品详情表
public class ProductInfo {
private int id;
private String name;
private String info;
private int pId;
//一对多
private Product product;
//setter getter
}
然后创建对应的接口
import org.apache.ibatis.annotations.Param;
import org.junit.Test;
import java.util.List;
import java.util.Map;
/*
产品类型的增删改查
*/
public interface ProductMapper {
//查找所有的
public List<Product> findAll();
//通过typeName和status查询
public Product findProducts(@Param("productType") String productType, @Param("status") Integer status);
//通过typename查询
public Product findProduct(String productType);
//删除 通过id
public int deleteProduct(int id);
public List<Map> find();
//修改updateProduct
public int updateProduct(Product product);
//增加一个商品分类
public int saveProduct(Product pro);
//新增多个
public int saveBatch(List<Product> list);
//
public List<Product> findProductList();
}
创建对应的productinfo接口
import com.lanou.pojo.Product;
import com.lanou.pojo.ProductInfo;
import java.util.List;
/*
产品详情的查
*/
public interface ProductInfoMapper {
public List<ProductInfo> findProductList();
}
创建对应的sql映射文件
创建对应的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">
<!--sql mapper映射文件-->
<!--namespace:命名空间 唯一的,不能重复并且要求接口的全名(包名.类名)保持一致-->
<mapper namespace="com.lanou.mapper.ProductMapper">
<select id="findAll" resultType="Product">
select * from product
</select>
<select id="findProducts" resultType="Product">
select * from product
<where>
<if test="productType!=null">product_type=#{productType}</if>
and status = #{status}
</where>
</select>
<select id="findProduct" resultType="Product">
select * from product where product_type=#{productType}
</select>
<insert id="saveProduct" parameterType="Product">
insert into product(id,product_type,status) value (#{id},#{productType},#{status})
</insert>
<delete id="deleteProduct">
delete from product where id=#{id}
</delete>
<!--返回map结构 一个对象Map 多个对象List<Map>-->
<select id="find" resultType="Map">
select * from product,productinfo where product.id = productinfo.pid
</select>
<update id="updateProduct">
update product
<set>
<if test="productType!=null">product_type=#{productType},</if>
<if test="status!=0">status=#{status}</if>
</set>
where id = #{id}
</update>
<!--插入多条数据-->
<!--
JDBC操作:
Statement:拼接sql
PreparedStatement:预编译?参数占位符 防止sql注入攻击,提高效率
Mybatis对JDBC封装
#{obj.status}取数据 ====> 预编译模式PreparedStatement
statementType="PREPARED" 一般情况下都是用预编译 #{}接收
statementType="STATEMENT" 当表名或者列名需要动态传入时,选择STATEMENT拼接sql ${}
statementType="CALLABLE" 调用存储过程时使用
-->
<insert id="saveBatch" parameterType="Product" databaseId="mysql" statementType="STATEMENT" useGeneratedKeys="true" keyProperty="id">
insert into product(product_type,status) values
<foreach collection="list" item="obj" separator=",">
(#{obj.productType},#{obj.status})
</foreach>
</insert>
<!--一对多映射-->
<select id="findProductList" resultMap="productMap">
select p.id as tid,p.product_type,p.status,i.* from
product p left outer join productInfo i on p.id = i.p_id
</select>
<!--id:唯一 type:返回对象类型-->
<resultMap id="productMap" type="Product">
<!--id 定义主键匹配关系 column:列名 property:类型属性名-->
<id column="tid" property="id"></id>
<!---->
<result column="product_type" property="productType"></result>
<result column="status" property="status"></result>
<!--集合关系 一对多 映射-->
<!--column指的是外键 ofType指的是这个集合中存在的bean类-->
<collection property="proInfoList" column="type_id" ofType="ProductInfo">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<result column="p_id" property="pId"></result>
<result column="info" property="info"></result>
</collection>
</resultMap>
</mapper>
创建对应的ProductInfoMapper.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">
<!--sql mapper映射文件-->
<!--namespace:命名空间 唯一的,不能重复并且要求接口的全名(包名.类名)保持一致-->
<mapper namespace="com.lanou.mapper.ProductInfoMapper">
<select id="findProductList" resultMap="productInfoMap">
select i.*,p.id as tid, p.product_type,p.status
from productinfo i join product p on i.p_id =p.id
</select>
<resultMap id="productInfoMap" type="ProductInfo" autoMapping="true">
<id column="id" property="id"></id>
<!--<result column="" property=""/>-->
<!--多对一映射-->
<association property="product" javaType="Product" column="p_id" autoMapping="true">
<id column="id" property="id"></id>
<!--autoMappering="true" 不用配置下面的result-->
<!--<result column="" property=""/>-->
</association>
</resultMap>
</mapper>
创建测试类
测试商品分类testProduct
import com.lanou.mapper.ProductMapper;
import com.lanou.pojo.Product;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TestProduct {
SqlSession sqlSession = null;
@Before
public void before() throws Exception{
//指定配置文件位置
String resources = "mybatis-config.xml";
//将配置文件内容转换为io流 使用Resources工具类中特定的方法转换的
InputStream inputStream = Resources.getResourceAsStream(resources);
//将Io流 生成 会话工厂 由建造者创建会话工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//从工厂中获取指定会话
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void selectAll() throws IOException {
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
//执行接口中的增删改查
//查询全部
List<Product> proList = productMapper.findAll();//没有参数
System.out.println(proList.toString());
//查询单个
Product product = productMapper.findProduct("手机");//一个参数
System.out.println(product.toString());
//插入操作
product = new Product();
product.setProductType("ss");
int num = productMapper.saveProduct(product);
sqlSession.commit();
System.out.println(num);
//删除操作
//int num = productMapper.deleteProduct(4);
// productMapper.deleteProduct(4);
//sqlSession.commit();
//关闭会话
sqlSession.close();
}
@Test
public void selectA() throws IOException {
//指定配置文件位置
String resources = "mybatis-config.xml";
//将配置文件内容转换为io流 使用Resources工具类中特定的方法转换的
InputStream inputStream = Resources.getResourceAsStream(resources);
//将Io流 生成 会话工厂 由建造者创建会话工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//从工厂中获取指定会话
SqlSession sqlSession = sqlSessionFactory.openSession();
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
//执行接口中的增删改查
//查询全部
// List<Product> proList = productMapper.findAll();//没有参数
// System.out.println(proList.toString());
// //查询单个
// Product product = productMapper.findProduct("手机");//一个参数
// System.out.println(product.toString());
//插入操作
// product = new Product();
// product.setproductType("ss");
// int num = productMapper.saveProduct(product);
//sqlSession.commit();
// System.out.println(num);
//删除操作
//int num = productMapper.deleteProduct(4);
// productMapper.deleteProduct(4);
//sqlSession.commit();
Product product = productMapper.findProducts("zz", 0);
System.out.println(product);
//关闭会话
sqlSession.close();
}
/*
*
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 7
*
map太多看所以会报这个,解决办法是把Map放进List集合中
* */
@Test
public void find(){
//指定配置文件位置
String resources = "mybatis-config.xml";
//将配置文件内容转换为io流 使用Resources工具类中特定的方法转换的
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resources);
} catch (IOException e) {
e.printStackTrace();
}
//将Io流 生成 会话工厂 由建造者创建会话工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//从工厂中获取指定会话
SqlSession sqlSession = sqlSessionFactory.openSession();
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
List<Map> map = productMapper.find();
System.out.println(map);
}
@Test
public void updateProduct(){
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
Product pro = new Product();
pro.setId(2);
pro.setProductType(null);
pro.setStatus(2);
productMapper.updateProduct(pro);
sqlSession.commit();
}
@Test
public void savaBatch(){
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
Product product = new Product();
product.setProductType("红红的");
product.setStatus(0);
Product product2 = new Product();
product2.setProductType("粉粉的");
product2.setStatus(0);
Product product3 = new Product();
product3.setProductType("白白的");
product3.setStatus(0);
List<Product> proList = new ArrayList<>();
proList.add(product);
proList.add(product2);
proList.add(product3);
int num = productMapper.saveBatch(proList);
sqlSession.commit();
System.out.println(num);
System.out.println("第一条数据插入的主键是:"+product.getId());
System.out.println("第二条数据插入的主键是:"+product2.getId());
System.out.println("第三条数据插入的主键是:"+product3.getId());
}
}
测试一对多
import com.lanou.mapper.ProductMapper;
import com.lanou.pojo.Product;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class TestOneToMany {
SqlSession sqlSession = null;
@Before
public void before() throws Exception{
//指定配置文件位置
String resources = "mybatis-config.xml";
//将配置文件内容转换为io流 使用Resources工具类中特定的方法转换的
InputStream inputStream = Resources.getResourceAsStream(resources);
//将Io流 生成 会话工厂 由建造者创建会话工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//从工厂中获取指定会话
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void selectAll(){
ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
List<Product> productlist = new ArrayList<>();
productlist = productMapper.findProductList();
System.out.println(productlist);
sqlSession.close();
}
}
测试多对一
import com.lanou.mapper.ProductInfoMapper;
import com.lanou.mapper.ProductMapper;
import com.lanou.pojo.Product;
import com.lanou.pojo.ProductInfo;
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.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class TestManyToOne {
SqlSession sqlSession = null;
@Before
public void before() throws Exception{
//指定配置文件位置
String resources = "mybatis-config.xml";
//将配置文件内容转换为io流 使用Resources工具类中特定的方法转换的
InputStream inputStream = Resources.getResourceAsStream(resources);
//将Io流 生成 会话工厂 由建造者创建会话工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//从工厂中获取指定会话
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void findAll(){
ProductInfoMapper productInfoMapper = sqlSession.getMapper(ProductInfoMapper.class);
List<ProductInfo> productInfolist = new ArrayList<>();
productInfolist = productInfoMapper.findProductList();
System.out.println(productInfolist);
sqlSession.close();
}
}