03_MyBatis基本查询,mapper文件的定义,测试代码的编写,resultMap配置返回值,sql片段配置,select标签标签中的内容介绍,配置使用二级缓存,使用别名的数据类型,条件查询ma
1 PersonTestMapper.xml中的内容如下:
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEmapper PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:命名空间,用来唯一标识一个映射文件,命名规范就是当前的文件的包加上文件名 --> <mappernamespace="com.rl.mapper.PersonTestMapper"> <!-- 根据id来查询一个Person的数据 sql语句接收参数的一个语法#{},如果接收的是一个{}中的内容任意select id:sql语句的唯一的标识不能重复 parameterType:sql要接收的数据类型 resultType:sql所返回的数据类型 --> <!-- 实际项目中数据库的表的字段一般由多个单词来构成由下划线来分隔多个单词 在java的model的实体类中的属性多个单词的命名规范是驼峰模式personAddr --> <selectid="selectPersonById"parameterType="java.lang.Integer"resultType="com.rl.model.Person"> select * from person_test t where t.ID = #{id} </select> </mapper> |
2 PersonMapper.xml的配置内容如下(resultMap配置返回值,sql片段配置,select标签标签中的内容介绍,配置使用二级缓存,使用别名的数据类型,条件查询map传递参数,模糊查询,插入,更新,删除,where条件查询,动态修改,in查询foreach迭代,批量插入foreach,批量删除,一对多查询,extends:resultMap的继承,多对多查询,延迟加载):
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEmapper PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:命名空间,用来唯一标识一个映射文件,命名规范就是当前的文件的包名+mapper的xml文件名 --> <mappernamespace="com.rl.mapper.PersonMapper"> <!--当前映射文件开启二级缓存--> <cachetype="org.mybatis.caches.ehcache.EhcacheCache"/> <!-- id:resultMap的唯一标识 type:给哪个实体类做结果的映射 --> <resultMaptype="person"id="BaseResultMap"> <!-- column:数据库中表的字段 property:数据库中表所有映射的实体类javaBean中的属性名 --> <idcolumn="person_id"property="personId"/> <resultcolumn="name"property="name"/> <resultcolumn="gender"property="gender"/> <resultcolumn="person_addr"property="personAddr"/> <resultcolumn="birthday"property="birthday"/> </resultMap> <!-- 公用的sql片段,也可以接收参数,动态sql,所有的sql可以使用 --> <sqlid="columns"> PERSON_ID, NAME, GENDER, PERSON_ADDR, BIRTHDAY </sql> <!-- 根据id来查询一个Person的数据 sql语句接收参数的一个语法#{},如果接收的是一个{}中的内容任意select id:sql语句的唯一的标识不能重复 parameterType:sql要接收的数据类型 resultType:sql所返回的数据类型 --> <!-- 实际项目中数据库的表的字段一般由多个单词来构成由下划线来分隔多个单词 在java的model的实体类中的属性多个单词的命名规范是驼峰模式personAddr --> <!-- useCache:控制当前的这个sql是否使用二级缓存 --> <selectid="selectPersonById"parameterType="int"resultMap="BaseResultMap"useCache="true"> select * from person t where t.person_id = #{id} </select> <selectid="selectPersonCount"resultType="int"> select count(*) from person </select> <!--这里引用了上面的sql片段 <selectid="selectPersonAll"resultMap="BaseResultMap"> select <includerefid="columns"/> </select> <!-- 可以使用map map.put("gender",1); map.put("birthday" new Date()); #{}中的内容使用Map的key来接收参数 --> <selectid="selectPersonByParams"parameterType="map"resultMap="BaseResultMap"> <![CDATA[ select * from person t where t.gender = #{gender} and t.birthday < #{birthday} ]]> </select> <!-- 使用查询对象的get方法来接收参数(也就是属性名) --> <selectid="selectPersonByParams1"parameterType="qc"resultMap="BaseResultMap"> <![CDATA[ select * from person t where t.gender = #{gender} and t.birthday < #{birthday} ]]> </select> <!-- 模糊查询使用${} select * from person t where t.name like '%安%' parameterType:不能直接使用String,一定要用查询对象或者map --> <selectid="selectPersonByLike"parameterType="qc"resultMap="BaseResultMap"> select * from person t where t.name like '%${name}%' </select> <!--库表变更 <insertid="insert"parameterType="person"> <!-- keyProperty:实体类中主键属性,主键生成后把主键返回给这个属性 order:生成主键的sql和insert执行的顺序,mysql是AFTER, resultType: sql: 在mysql中select 在oracle中 selectKey做了两件事:1.主键自增 --> <selectKeykeyProperty="personId"order="AFTER"resultType="int"> select LAST_INSERT_ID() </selectKey> insert into person (person_id, name, gender, person_addr, birthday) values(#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}) </insert> <updateid="update"parameterType="person"> update person p set p.name = #{name}, p.gender = #{gender}, p.person_addr = #{personAddr}, p.birthday = #{birthday} where p.person_id = #{personId} </update> <!-- 删除的sql不能使用别名 --> <deleteid="delete"parameterType="int"> delete from person where person_id = #{personId} </delete> <!-- =============================动态sql================================== <!-- map.put("name", "安"); map.put("gender", "0"); map.put("personAddr", "东京") map.put("birthday", new Date()); <where>会自动处理and,第一个and可以不写,其他的and必须要写 --> <selectid="selectPersonByCondition"parameterType="map"resultMap="BaseResultMap"> select * from person t <where> <iftest="name t.name like '%${name}%' </if> <iftest="gender and t.gender = #{gender} </if> <iftest="personAddr and t.person_addr like '%${personAddr}%' </if> <iftest="birthday <![CDATA[ and t.birthday < #{birthday} ]]> </if> </where> </select> <!-- 动态修改 <set>标签可以去掉最后一个逗号 flushCache:二级缓存的刷新的配置:默认是true:会刷新,如果false就不刷新缓存 --> <updateid="dynamicUpdate"parameterType="person"flushCache="false"> update person t <set> <iftest="name t.name = #{name}, </if> <iftest="gender t.gender = #{gender}, </if> <iftest="personAddr t.person_addr = #{personAddr}, </if> <iftest="birthday t.birthday = #{birthday} </if> </set> where t.person_id = #{personId} </update> <!-- select * from person t where t.person_id in (1,2,3) map.put("ids", list); --> <selectid="selectPersonByIn"parameterType="map"resultMap="BaseResultMap"> select * from person t where t.person_id in <foreachcollection="ids"item="personId"open="("close=")"separator=","index="index"> #{personId} </foreach> </select> <!-- map.put("pList", pList); insert into person (person_id, name, gender, person_addr, birthday) values (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}), (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}), (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}), (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}), (#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday}); --> <insertid="insertBatch"parameterType="map"> <selectKeykeyProperty="personId"order="AFTER"resultType="int"> select LAST_INSERT_ID() </selectKey> insert into person (person_id, name, gender, person_addr, birthday) values <foreachcollection="pList"item="person"separator=","> (#{person.personId}, #{person.name}, #{person.gender}, #{person.personAddr}, #{person.birthday}) </foreach> </insert> <deleteid="deleteBatch"parameterType="map"> delete from person where person_id in <foreachcollection="ids"item="personId"open="("close=")"separator=","index="index"> #{personId} </foreach> </delete> <!-- ===============================关联查询================== <!--一对多 <resultMaptype="person"id="selectPersonAndOrderByPIdRM"> <idcolumn="person_id"property="personId"/> <resultcolumn="name"property="name"/> <resultcolumn="gender"property="gender"/> <resultcolumn="person_addr"property="personAddr"/> <resultcolumn="birthday"property="birthday"/> <!-- collection:一对多的关联映射 property:一的端集合的属性名 ofType:集合中的泛型 --> <collectionproperty="ordersList"ofType="com.rl.model1.Orders"> <idcolumn="ORDER_ID"property="orderId"jdbcType="INTEGER"/> <resultcolumn="PERSON_ID"property="personId"jdbcType="INTEGER"/> <resultcolumn="TOTAL_PRICE"property="totalPrice"jdbcType="REAL"/> <resultcolumn="ADDR"property="addr"jdbcType="VARCHAR"/> </collection> </resultMap> <!-- extends:resultMap的继承 --> <resultMaptype="person"id="selectPersonAndOrderByPIdRM1"extends="BaseResultMap"> <collectionproperty="ordersList"ofType="com.rl.model1.Orders"> <idcolumn="ORDER_ID"property="orderId"jdbcType="INTEGER"/> <resultcolumn="PERSON_ID"property="personId"jdbcType="INTEGER"/> <resultcolumn="TOTAL_PRICE"property="totalPrice"jdbcType="REAL"/> <resultcolumn="ADDR"property="addr"jdbcType="VARCHAR"/> </collection> </resultMap> <resultMaptype="person"id="selectPersonOrderAndDetailByPIdRM"extends="BaseResultMap"> <collectionproperty="ordersList"ofType="com.rl.model1.Orders"> <idcolumn="ORDER_ID"property="orderId"jdbcType="INTEGER"/> <resultcolumn="PERSON_ID"property="personId"jdbcType="INTEGER"/> <resultcolumn="TOTAL_PRICE"property="totalPrice"jdbcType="REAL"/> <resultcolumn="ADDR"property="addr"jdbcType="VARCHAR"/> <collectionproperty="detailList"ofType="com.rl.model1.OrderDetail"> <idcolumn="DETAIL_ID"property="detailId"jdbcType="INTEGER"/> <resultcolumn="ORDER_ID"property="orderId"jdbcType="INTEGER"/> <resultcolumn="PRICE"property="price"jdbcType="REAL"/> <resultcolumn="QUANTITY"property="quantity"jdbcType="INTEGER"/> <resultcolumn="ITEM_NAME"property="itemName"jdbcType="VARCHAR"/> </collection> </collection> </resultMap> <resultMaptype="person"id="selectPersonAndRoleByPIdRM"extends="BaseResultMap"> <collectionproperty="roleList"ofType="com.rl.model1.Role"> <idcolumn="ROLE_ID"property="roleId"jdbcType="INTEGER"/> <resultcolumn="ROLE_NAME"property="roleName"jdbcType="VARCHAR"/> <resultcolumn="DESCRIPT"property="descript"jdbcType="VARCHAR"/> </collection> </resultMap> <selectid="selectPersonAndOrderByPId"parameterType="int"resultMap="selectPersonAndOrderByPIdRM1"> select * from person p, orders o where p.PERSON_ID = o.PERSON_ID and p.PERSON_ID = #{personId} </select> <selectid="selectPersonOrderAndDetailByPId"parameterType="int"resultMap="selectPersonOrderAndDetailByPIdRM"> select * from person p, orders o, order_detail p.PERSON_ID = o.PERSON_ID and o.ORDER_ID = od.ORDER_ID and p.PERSON_ID = #{personId} </select> <!--多对多从Person一端看 <selectid="selectPersonAndRoleByPId"parameterType="int"resultMap="selectPersonAndRoleByPIdRM"> SELECT p.*, r.* from person p, person_role role r where p.PERSON_ID = pr.PERSON_ID and pr.ROLE_ID = r.ROLE_ID and p.PERSON_ID = #{personId} </select> <!-- =========================延迟加载======================== <resultMaptype="person"id="selectPersonByIdLazyRM"extends="BaseResultMap"> <!-- column:主sql的一列作为子sql的参数 select:指定子sql的位置 --> <collectionproperty="ordersList"column="person_id"select="com.rl.mapper.OrdersMapper.selectOrderByPersonId"> </collection> </resultMap> <selectid="selectPersonByIdLazy"parameterType="int"resultMap="selectPersonByIdLazyRM"> select * from person t where t.person_id = #{personId} </select> </mapper> |
RoleMapper.xml
<?xml <!DOCTYPE <mapper <resultMap <id <result <result </resultMap> <sql ROLE_ID, ROLE_NAME, DESCRIPT </sql> <select select <include from role where ROLE_ID = #{roleId,jdbcType=INTEGER} </select> <delete delete from role where ROLE_ID = #{roleId,jdbcType=INTEGER} </delete> <insert insert into role (ROLE_ID, ROLE_NAME, DESCRIPT ) values (#{roleId,jdbcType=INTEGER}, #{roleName,jdbcType=VARCHAR}, #{descript,jdbcType=VARCHAR} ) </insert> <insert insert into role <trim <if ROLE_ID, </if> <if ROLE_NAME, </if> <if DESCRIPT, </if> </trim> <trim <if #{roleId,jdbcType=INTEGER}, </if> <if #{roleName,jdbcType=VARCHAR}, </if> <if #{descript,jdbcType=VARCHAR}, </if> </trim> </insert> <update update role <set <if ROLE_NAME = #{roleName,jdbcType=VARCHAR}, </if> <if DESCRIPT = #{descript,jdbcType=VARCHAR}, </if> </set> where ROLE_ID = #{roleId,jdbcType=INTEGER} </update> <update update role set ROLE_NAME = #{roleName,jdbcType=VARCHAR}, DESCRIPT = #{descript,jdbcType=VARCHAR} where ROLE_ID = #{roleId,jdbcType=INTEGER} </update> <resultMap <collection <id <result <result <result <result </collection> </resultMap> <select SELECT p.*, r.* from person p, person_role pr, role r where p.PERSON_ID = pr.PERSON_ID and pr.ROLE_ID = r.ROLE_ID and r.ROLE_ID = #{roleId} </select> </mapper> |
OrdersMapper.xml
<?xml <!DOCTYPE <mapper <resultMap <id <result <result <result </resultMap> <sql ORDER_ID, PERSON_ID, TOTAL_PRICE, ADDR </sql> <select select <include from orders where ORDER_ID = #{orderId,jdbcType=INTEGER} </select> <delete delete from orders where ORDER_ID = #{orderId,jdbcType=INTEGER} </delete> <insert insert into orders (ORDER_ID, PERSON_ID, TOTAL_PRICE, ADDR) values (#{orderId,jdbcType=INTEGER}, #{personId,jdbcType=INTEGER}, #{totalPrice,jdbcType=REAL}, #{addr,jdbcType=VARCHAR}) </insert> <insert insert into orders <trim <if ORDER_ID, </if> <if PERSON_ID, </if> <if TOTAL_PRICE, </if> <if ADDR, </if> </trim> <trim <if #{orderId,jdbcType=INTEGER}, </if> <if #{personId,jdbcType=INTEGER}, </if> <if #{totalPrice,jdbcType=REAL}, </if> <if #{addr,jdbcType=VARCHAR}, </if> </trim> </insert> <update update orders <set <if PERSON_ID = #{personId,jdbcType=INTEGER}, </if> <if TOTAL_PRICE = #{totalPrice,jdbcType=REAL}, </if> <if ADDR = #{addr,jdbcType=VARCHAR}, </if> </set> where ORDER_ID = #{orderId,jdbcType=INTEGER} </update> <update update orders set PERSON_ID = #{personId,jdbcType=INTEGER}, TOTAL_PRICE = #{totalPrice,jdbcType=REAL}, ADDR = #{addr,jdbcType=VARCHAR} where ORDER_ID = #{orderId,jdbcType=INTEGER} </update> <resultMap <!-- association:多对一的关联映射 property:多的一端所属的一的一端类的属性名 javaType:一的一端的数据类型 --> <association <id <result <result <result <result </association> </resultMap> <resultMap <collection <id <result <result <result <result </collection> </resultMap> <!-- 多对一和一对多的混合查询的resultMap association要放在Collection的前面 --> <resultMap <association <id <result <result <result <result </association> <collection <id <result <result <result <result </collection> </resultMap> <select select * from orders o, person p where o.PERSON_ID = p.PERSON_ID and o.ORDER_ID = #{orderId} </select> <select select * from orders o, person p, order_detail where o.PERSON_ID = p.PERSON_ID and o.ORDER_ID = od.ORDER_ID and o.ORDER_ID = #{orderId} </select> <!-- 延迟加载的子sql,传递过来的参数是person_id --> <select select * from orders t where t.person_id = #{personid} </select> <resultMap <association </resultMap> <resultMap <association <collection </resultMap> <select select * from orders t where t.order_id = #{orderId} </select> <!-- 查询订单的所属人和订单明细,延迟加载 --> <select select * from orders t where t.order_id = #{orderId} </select> </mapper> |
3配置sqlMapConfig.xml中的<mappers>配置:
<!--集中管理表的映射文件 <mappers> <mapperresource="com/rl/mapper/PersonTestMapper.xml"/> <mapperresource="com/rl/mapper/PersonMapper.xml"/> <mapperresource="com/rl/mapper/RoleMapper.xml"/> <mapperresource="com/rl/mapper/OrdersMapper.xml"/> <mapperresource="com/rl/mapper/OrderDetailMapper.xml"/> </mappers> |
4测试代码如下:
MybatisTest.java
package com.rl.test; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; 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 com.rl.model1.Person; import com.rl.model1.QueryCondition; /** * mybatis的简单查询 */ public class MybatisTest { SqlSessionFactory sessionFactory; @Before public void setUp() throws Exception { InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); sessionFactory = new SqlSessionFactoryBuilder().build(in); } /** * */ @Test public void selectPersonById() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { //第一个参数:指定要执行的sql语法是namespace.sql的id,第二个参数sql要接收的参数 com.rl.model.Person person "com.rl.mapper.PersonTestMapper.selectPersonById", 1); System.out.println(person); } finally{ session.close(); } } /** * */ @Test public void selectPersonById1() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { //第一个参数:指定要执行的sql语法是namespace.sql的id,第二个参数sql要接收的参数 Person person System.out.println(person); } finally{ session.close(); } } /** * */ @Test public void selectPersonCount() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { Integer count = session.selectOne("com.rl.mapper.PersonMapper.selectPersonCount"); System.out.println(count); } finally{ session.close(); } } /** * */ @Test public void selectPersonAll() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { //查询集合的时候需要使用selectList List<Person> pList = session.selectList("com.rl.mapper.PersonMapper.selectPersonAll"); for(Person p : pList){ System.out.println(p); } } finally{ session.close(); } } /** * */ @Test public void selectPersonByParams() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { Map<String, Object> map = new HashMap<String, Object>(); map.put("gender",0); map.put("birthday", new Date()); //查询集合的时候需要使用selectList List<Person> pList = session.selectList("com.rl.mapper.PersonMapper.selectPersonByParams",map); for(Person p : pList){ System.out.println(p); } } finally{ session.close(); } } /** * */ @Test public void selectPersonByParams1() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { QueryCondition qc = new QueryCondition(); qc.setGender("0"); qc.setBirthday(new Date()); //查询集合的时候需要使用selectList List<Person> pList = session.selectList("com.rl.mapper.PersonMapper.selectPersonByParams1",qc); for(Person p : pList){ System.out.println(p); } } finally{ session.close(); } } /** * */ @Test public void selectPersonByLike() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { QueryCondition qc = new QueryCondition(); qc.setName("武"); //查询集合的时候需要使用selectList List<Person> pList = session.selectList("com.rl.mapper.PersonMapper.selectPersonByLike",qc); for(Person p : pList){ System.out.println(p); } } finally{ session.close(); } } } |
MybatisTest1.java的内容如下:
package com.rl.test; import java.io.InputStream; import java.util.Date; 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 com.rl.model1.Person; /** * mybatis的数据库表的变更 */ public class MybatisTest1 { SqlSessionFactory sessionFactory; @Before public void setUp() throws Exception { InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); sessionFactory = new SqlSessionFactoryBuilder().build(in); } /** * * public void saveOrder(Orders order, List<OrderDetail> detailList){ orderDao.save(order); for(OrderDetail detail : detailList){ detail.setOrderId(order.getOrderId()); detailDao.save(detail) } } */ @Test public void insert(){ SqlSession session = sessionFactory.openSession(); Person p = new Person(); //p.setPersonId(3); p.setName("武松"); p.setGender("0"); p.setPersonAddr("阳谷县"); p.setBirthday(new Date()); try { session.insert("com.rl.mapper.PersonMapper.insert", p); //库表的变更都需要提交 session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ session.close(); } } /** * */ @Test public void update(){ SqlSession session = sessionFactory.openSession(); Person p = new Person(); p.setPersonId(3); p.setName("陆虞候"); p.setGender("0"); p.setPersonAddr("阳谷县"); p.setBirthday(new Date()); try { session.update("com.rl.mapper.PersonMapper.update", p); //库表的变更都需要提交 session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ session.close(); } } /** * */ @Test public void delete(){ SqlSession session = sessionFactory.openSession(); try { session.delete("com.rl.mapper.PersonMapper.delete", 4); //库表的变更都需要提交 session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ session.close(); } } } |
MybatisTest2.java
package com.rl.test; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; 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 com.rl.model1.Person; /** * mybatis的动态sql */ public class MybatisTest2 { SqlSessionFactory sessionFactory; @Before public void setUp() throws Exception { InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); sessionFactory = new SqlSessionFactoryBuilder().build(in); } @Test public void selectPersonByCondition() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "安"); map.put("gender", "0"); //map.put("personAddr", "东京"); //map.put("birthday", new Date()); //第一个参数:指定要执行的sql语法是namespace.sql的id,第二个参数sql要接收的参数 List<Person> pList for(Person p : pList){ System.out.println(p); } } finally{ session.close(); } } @Test public void dynamicUpdate(){ SqlSession session = sessionFactory.openSession(); Person p = new Person(); p.setPersonId(3); p.setName("陆虞候"); p.setGender("0"); //p.setPersonAddr("阳谷县"); //p.setBirthday(new Date()); try { session.update("com.rl.mapper.PersonMapper.dynamicUpdate", p); //库表的变更都需要提交 session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ session.close(); } } /** * foreach的用法 */ @Test public void selectPersonByIn() { //创建session对象 SqlSession session = sessionFactory.openSession(); try { Map<String, Object> map = new HashMap<String, Object>(); /*List list = new ArrayList(); list.add(1); list.add(2); list.add(3);*/ String [] list = {"1","2","3"}; map.put("ids", list); List<Person> pList for(Person p : pList){ System.out.println(p); } } finally{ session.close(); } } /** * */ @Test public void insertBatch(){ SqlSession session = sessionFactory.openSession(); Map<String,Object> map = new HashMap<String,Object>(); List<Person> pList= new ArrayList<Person>(); try { for(int i = 0; i < 1000009; i++){ Person p = new Person(); p.setName("武松"+i); p.setGender("0"); p.setPersonAddr("阳谷县"); p.setBirthday(new Date()); pList.add(p); if(i%100 == 0){ map.put("pList", pList); session.insert("com.rl.mapper.PersonMapper.insertBatch", map); pList.clear(); } } map.put("pList", pList); session.insert("com.rl.mapper.PersonMapper.insertBatch", map); //库表的变更都需要提交 session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ session.close(); } } @Test public void deleteBatch(){ SqlSession session = sessionFactory.openSession(); Map<String,Object> map = new HashMap<String,Object>(); List<Integer> ids= new ArrayList<Integer>(); try { for(int i = 106; i < 1000115; i++){ ids.add(i); if(i%100 == 0){ map.put("ids", ids); session.delete("com.rl.mapper.PersonMapper.deleteBatch", map); ids.clear(); } } map.put("ids", ids); session.insert("com.rl.mapper.PersonMapper.deleteBatch", map); //库表的变更都需要提交 session.commit(); } catch (Exception e) { e.printStackTrace(); session.rollback(); }finally{ session.close(); } } } |
MybatisTest3.java的内容如下:
package com.rl.test; import java.io.InputStream; 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 com.rl.model1.Orders; import com.rl.model1.Person; import com.rl.model1.Role; /** *mybatis的关联查询 */ publicclass SqlSessionFactory @Before publicvoid InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); sessionFactory } /** * */ @Test publicvoid //创建session对象 SqlSession session = try //第一个参数:指定要执行的sql语法是namespace.sql的id,第二个参数sql要接收的参数 Person person System.out.println(person); } session.close(); } } /** * */ @Test publicvoid //创建session对象 SqlSession session = try //第一个参数:指定要执行的sql语法是namespace.sql的id,第二个参数sql要接收的参数 Person person System.out.println(person); } session.close(); } } /** * */ @Test publicvoid //创建session对象 SqlSession session = try //第一个参数:指定要执行的sql语法是namespace.sql的id,第二个参数sql要接收的参数 Person person System.out.println(person); } session.close(); } } /** * */ @Test publicvoid //创建session对象 SqlSession session = try //第一个参数:指定要执行的sql语法是namespace.sql的id,第二个参数sql要接收的参数 Role role System.out.println(role); } session.close(); } } /** * *这里的mapper配置文件在后续的博文中定义。 */ @Test publicvoid //创建session对象 SqlSession session = try Orders order System.out.println(order); } session.close(); } } /** * *这里的mapper配置文件在后续的博文中定义。 */ @Test publicvoid //创建session对象 SqlSession session = try Orders order System.out.println(order); } session.close(); } } } |
03_MyBatis基本查询,mapper文件的定义,测试代码的编写,resultMap配置返回值,sql片段配置,select标签标签中的内容介绍,配置使用二级缓存,使用别名的数据类型,条件查询ma的更多相关文章
- mapper文件提示:No data sources are configured to run this sql
mapper文件发出黄色警告. 输入数据库用户名和密码等等. 自动同步ok 就会发现代码变绿了,ok
- hibernate--一级和二级缓存(使用Ehcache)以及查询缓存
https://blog.csdn.net/u012411414/article/details/50483185 有一下几点需要理清才行: 一级缓存是session缓存 session关闭就小时 二 ...
- .net单元测试——常用测试方式(异常模拟、返回值测试、参数测试、数据库访问代码测试)
最近在看.net单元测试艺术,我也喜欢单元测试,今天介绍一下如何测试异常.如何测试返回值.如何测试模拟对象的参数传递.如何测试数据库访问代码.单元测试框架使用的是NUnit,模拟框架使用的是:Rhin ...
- .Net调用Java编写的WebServices返回值为Null的解决方法(SoapUI工具测试有返回值)
最近在项目中与别的公司对接业务,对方是Java语言,需要调用对方的WebServices,结果常规的添加web引用的方法可以传过去值,但是返回值为null 查了很多资料,没有解决方法 思考应该是.Ne ...
- Mybatis之collection嵌套查询mapper文件写法
mapper.xml写法举例 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper ...
- JAVA 和 C# 调用外部.exe文件,传值并等等exe完成,获取返回值
JAVA- String ykexe = getProperty("ykexe") + " " + tableout; //getproperty(" ...
- MyBatis关联查询、多条件查询
MyBatis关联查询.多条件查询 1.一对一查询 任务需求; 根据班级的信息查询出教师的相关信息 1.数据库表的设计 班级表: 教师表: 2.实体类的设计 班级表: public class Cla ...
- sql server查询可编程对象定义的方式对比以及整合
本文目录列表: 1.sql server查看可编程对象定义的方式对比 2.整合实现所有可编程对象定义的查看功能的存储dbo.usp_helptext2 3.dbo.helptext2的选择性测试 4. ...
- spring data jpa实现多条件查询(分页和不分页)
目前的spring data jpa已经帮我们干了CRUD的大部分活了,但如果有些活它干不了(CrudRepository接口中没定义),那么只能由我们自己干了.这里要说的就是在它的框架里,如何实现自 ...
随机推荐
- SPOJ VLATTICE(莫比乌斯反演)
题意: 在一个三维空间中,已知(0,0,0)和(n,n,n),求从原点可以看见多少个点 思路: 如果要能看见,即两点之间没有点,所以gcd(a,b,c) = 1 /*来自kuangbi ...
- C语言设计第一次作业
1 (1)题目:求圆面积和周长 (2)流程图: (3)测试数据及运行结果: (4)实验分析:暂时没问题. 2 (1)题目:输入一个四位年份,判断其是否是闰年.闰年的判别条件是该年年份能被4整除但不能被 ...
- H3C S3100交换机配置VLAN和远程管理
一.基本设置 1. console线连接成功 2. 进入系统模式 <H3C>system-view //提示符由<H3C> 变为 [H3C] 3. 更改设备名称 [H3C]sy ...
- React 关于组件(界面)更新
在最近在学 React , 将组件的UI更新稍微整理了一下.根据业务要求,可能会出现如下的技术实现要求:1.更新自己2.更新子组件3.更新兄弟组件4.更新父组件5.父 call 子 function ...
- vscode 搭建go开发环境的13个插件的安装
由于网的问题 大家都不能直接go get 这里从易到难按难度给大家推荐几种方法 最简单的FQ 但是能FQ你还不能装 请问是假的FQ吗? 第一 用git 直接git反而能从那边趴下代码 但是要自己go ...
- 关于npm run build 报错解决方案
# 特定的错误 ERROR in statics/mobile/js/vendor.cef13a0e680a5bc0d8b3.js from UglifyJsUnexpected token: pun ...
- Button 使用Command 按钮置灰未更新
当Button绑定了Command,按钮在窗口弹出.或者其它事件时,会自动置灰. 有时,异步执行时间较长时,界面一些绑定了命令的Button,State不会变化,会一直置灰. 直到再次转移Focus. ...
- Android TextView常用属性
[说明] TextView是用来显示文本的组件.以下介绍的是XML代码中的属性,在java代码中同样可通过 "组件名.setXXX()方法设置.如,tv.setTextColor(); [属 ...
- 下篇:python的基本数据类型以及对应的常用方法(列表、元组、字典、集合)
为了日后便于查询,本文所涉及到的所有命令集合如下: python中的基本数据类型有数字.字符串.布尔值.列表.元组.字典.就像每一个职业有自己特定的技能,比如医生能看病,农民能种田,每种数据类型也有属 ...
- 0428css样式
CSS样式表|-引入的三种方式|--内联样式|----标签内部(空格style)|--内嵌样式|----<head></head>标签内部(<style></ ...