mabits

来源:互联网 发布:淘宝一口价怎么改 编辑:程序博客网 时间:2024/06/06 13:08

一、传入参数的传递

parameterType指定参数类型
基本类型参数(int、string.......)
pojo类型:user对象
map类型
包装类型

1、map类型的传递

需求:查询用户性别为男,姓张的用户
  1. <mapper namespace="com.itcast.dao.UserMapper" >
  2. <!-- 需求:查询用户性别为男,姓张的用户 -->
  3. <select id="findUserWithMap" parameterType="map" resultType="user" >
  4. select * from user where sex=#{sex} and username like "%"#{username}"%"
  5. </select>
  6. </mapper>

  1. @Test
  2. public void fun1() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  7. Map<String, Object> map = new HashMap<>();
  8. map.put("sex", "男");
  9. map.put("username", "张");
  10. List<User> list = userMapper.findUserWithMap(map);
  11. System.out.println(list);
  12. }

2、包装类型的传递

需求:查询用户性别为男,姓张的用户
  1. <!-- 需求:查询用户性别为男,姓张的用户 -->
  2. <select id="findUserWithQueryVo" parameterType="queryvo" resultType="user" >
  3. select * from user where sex=#{user.sex} and username like "%"#{user.username}"%"
  4. </select>
  1. @Test
  2. public void fun2() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  7. User user = new User();
  8. user.setSex("男");
  9. user.setUsername("张");
  10. QueryVo queryVo = new QueryVo();
  11. queryVo.setUser(user);
  12. List<User> list = userMapper.findUserWithQueryVo(queryVo);
  13. System.out.println(list);
  14. }

二、返回参数的类型

基本类型
pojo类型
返回集合类型

1、返回基本类型
需求:查询用户性别为男,姓张的用户总计数
  1. <!-- 查询用户性别为男,姓张的用户总记录数 -->
  2. <select id="findUserWithQueryVoCount" parameterType="queryvo" resultType="int" >
  3. select count(2) from user where sex=#{user.sex} and username like "%"#{user.username}"%"
  4. </select>
  1. @Test
  2. public void fun3() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  7. User user = new User();
  8. user.setSex("男");
  9. user.setUsername("张");
  10. QueryVo queryVo = new QueryVo();
  11. queryVo.setUser(user);
  12. int count = userMapper.findUserWithQueryVoCount(queryVo);
  13. System.out.println(count);
  14. }

2、resultType特性

特性:查询数据库列名必须和映射的javabean属性名称一一对应,且名称相同,否则不能映射成功
验证:
  1. <!-- 验证resultType的映射特性-->
  2. <select id="findUserWithResultType" resultType="user" >
  3. select id _id,username _username,birthday _birthday,sex _sex,address _address from user
  4. </select>
  1. @Test
  2. public void fun4() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  7. List<User> list= userMapper.findUserWithResultType();
  8. System.out.println(list);
  9. }

返回结果错误:[null, null, null, null, null, null, null, null, null]

解决映射不成功的方案:
    *    定义别名
    *    resultMap

3、resultMap映射特点

解决resultType 数据库列名与javabean属性名不相同不能映射的问题
需要先定义一个resultMap的映射关系
                    主键映射 :使用id
        column:查询数据库列名
        property:javabean属性名
  1. <!-- 定义resultMap -->
  2. <resultMap type="user" id="userMap">
  3. <!-- 主键映射 -->
  4. <id column="_id" property="id" />
  5. <!-- 普通属性映射 -->
  6. <result column="_username" property="username" />
  7. <result column="_birthday" property="birthday" />
  8. <result column="_sex" property="sex" />
  9. <result column="_address" property="address" />
  10. </resultMap>
  11. <!-- resultMap解决数据库列名与javabean属性名不相同不能映射的状况-->
  12. <select id="findUserWithResultMap" resultMap="userMap" >
  13. select id _id,username _username,birthday _birthday,sex _sex,address _address from user
  14. </select>
java代码和上面一样


三、多表关联的查询:

1、多的一方    一对一查询

   可以用resultType也可以用resultMap查询
①  用resultType来映射
需求:通过订单查询用户和订单所有数据,一个订单只对应一个用户,所以是一对一查询
新定义一个订单实体类,再用一个OrdersCustom类继承Orders类中所有属性,再添加User类中的所有属性,注意把User类中的主键名字改成uid,因为不能和Orders的主键id名字重复啊,查询后的结果就封装在OrdersCustom这个类的属性中
  1. <mapper namespace="com.itcast.dao.OrdersMapper" >
  2. <select id="findOrdersWithUserByResultType" resultType="ordersCustom" >
  3. select o.id,o.user_id userId,o.number,o.createtime createTime,o.note,
  4. u.id uid,u.username,u.birthday,u.sex,u.address
  5. from user u,orders o where u.id=o.user_id
  6. </select>
  7. </mapper>
  1. @Test
  2. public void fun1() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);
  7. List<OrdersCustom> list = ordersMapper.findOrdersWithUserByResultType();
  8. System.out.println(list);
  9. }

②用resultMap来映射
                       配置一对一关系映射:association 
property:指定映射orders中那个属性
javaType:指定关系映射对象类型
  1. <mapper namespace="com.itcast.dao.OrdersMapper" >
  2. <!--
  3. 定义关系映射:resultMap
  4. type:指定映射类型
  5. id:resultMap映射关系唯一标识
  6. -->
  7. <resultMap type="orders" id="ordersMap">
  8. <!--
  9. 主键映射 :使用id
  10. column:查询数据库列名
  11. property:javabean属性名
  12. -->
  13. <id column="id" property="id" />
  14. <!-- 普通属性映射 -->
  15. <result column="user_id" property="userId" />
  16. <result column="number" property="number" />
  17. <result column="createtime" property="createTime" />
  18. <result column="note" property="note" />
  19. <!-- 表关联
  20. 配置一对一关系映射:association
  21. property:指定映射orders中那个属性
  22. javaType:指定关系映射对象类型
  23. -->
  24. <association property="user" javaType="user">
  25. <id column="uid" property="id" />
  26. <result column="username" property="username" />
  27. <result column="birthday" property="birthday" />
  28. <result column="sex" property="sex" />
  29. <result column="address" property="address" />
  30. </association>
  31. </resultMap>
  32. <select id="findOrdersWithUserByResultMap" resultMap="ordersMap" >
  33. SELECT orders.*,user.id uid,user.username,user.birthday,user.sex,user.address
  34. FROM orders,user WHERE orders.user_id = user.id
  35. </select>
  36. </mapper>
  1. @Test
  2. public void fun2() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);
  7. List<Orders> list = ordersMapper.findOrdersWithUserByResultMap();
  8. System.out.println(list);
  9. }


2、一的一方    一对多查询

一个用户对应了多个订单,如果通过用户查询用户数据和对应的订单数据,那就是一对多查询
一对多查询只能用resultMap来映射
  1. <mapper namespace="com.itcast.dao.UserMapper" >
  2. <resultMap type="user" id="userMap">
  3. <id column="uid" property="id" />
  4. <result column="username" property="username"/>
  5. <result column="birthday" property="birthday"/>
  6. <result column="sex" property="sex"/>
  7. <result column="address" property="address"/>
  8. <!-- ofType:制定映射的javabean类型,property:表示映射到user中的那个属性 -->
  9. <collection property="oList" ofType="orders" >
  10. <!--
  11. 主键映射 :使用id
  12. column:查询数据库列名
  13. property:javabean属性名
  14. -->
  15. <id column="id" property="id"/>
  16. <!-- 普通属性映射 -->
  17. <result column="user_id" property="userId"/>
  18. <result column="number" property="number"/>
  19. <result column="createtime" property="createTime"/>
  20. <result column="note" property="note"/>
  21. </collection>
  22. </resultMap>
  23. <!-- 查询用户订单,一对多 -->
  24. <select id="findUserWithOrdersByMap" resultMap="userMap" >
  25. select user.id uid,user.username,user.birthday,user.sex,user.address,
  26. orders.id,orders.user_id userId,orders.number,orders.createtime createTime,orders.note
  27. from user,orders where orders.user_id=user.id
  28. </select>
  29. </mapper>
  1. @Test
  2. public void fun3() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  7. List<User> list = userMapper.findUserWithOrdersByMap();
  8. System.out.println(list);
  9. }


四、动态sql查询

1、if标签和where标签连用

       where标签自动生成where语句,并且where标签可以自动去掉sql语句的第一个多余的“and”
       if标签::当if标签传入的是pojo类型,或者包装类型,test里面就直接写传入类型里面的属性名,但是当传入的parameterType是基本数据类型,例如string,如要判断string类型的内容,则需要在test里面判断:_parameter
①不用where标签的做法:
  1. <!-- 需求:查询用户性别为男,姓张的用户 -->
  2. <select id="findUserWithQueryVo" parameterType="queryvo" resultType="user" >
  3. select * from user where 1=1
  4. <if test="user.sex!=null and user.sex!=''">
  5. andsex=#{user.sex}
  6. </if>
  7. <if test="user.username!=null and user.username!=''">
  8. and username like "%"#{user.username}"%"
  9. </if>
  10. </select>
  1. @Test
  2. public void fun2() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  7. User user = new User();
  8. user.setSex(null);
  9. user.setUsername("张");
  10. QueryVo queryVo = new QueryVo();
  11. queryVo.setUser(user);
  12. List<User> list = userMapper.findUserWithQueryVo(queryVo);
  13. System.out.println(list);
  14. }

②用where标签的做法:
  1. <!-- 需求:查询用户性别为男,姓张的用户 -->
  2. <select id="findUserWithQueryVo" parameterType="queryvo" resultType="user" >
  3. select * from user
  4. <!-- where标签自动生成where语句,并且去掉第一个多余的and -->
  5. <where>
  6. <if test="user.sex!=null and user.sex!=''">
  7. andsex=#{user.sex}
  8. </if>
  9. <if test="user.username!=null and user.username!=''">
  10. and username like "%"#{user.username}"%"
  11. </if>
  12. </where>
  13. </select>
java程序和上面一样


2、动态更新语句:

<set>标签类似于where标签
 



3、sql片段

       把相同的sql片段抽取出去
<sql id="" ></sql>标签定义片段;;<include refid="" ></include>来引入sql片段
id和refid相对应
  1. <mapper namespace="com.itcast.dao.UserMapper" >
  2. <!-- 定义一个sql片段,抽取公共的sql语句 -->
  3. <sql id="where_if_vo">
  4. <where>
  5. <if test="user.sex!=null and user.sex!=''">
  6. andsex=#{user.sex}
  7. </if>
  8. <if test="user.username!=null and user.username!=''">
  9. and username like "%"#{user.username}"%"
  10. </if>
  11. </where>
  12. </sql>
  13. <!-- 需求:查询用户性别为男,姓张的用户 -->
  14. <select id="findUserWithQueryVo" parameterType="queryvo" resultType="user" >
  15. select * from user
  16. <!-- where标签自动生成where语句,并且去掉第一个多余的and -->
  17. <include refid="where_if_vo"></include>
  18. </select>
  19. <!-- 查询用户性别为男,姓张的用户总记录数 -->
  20. <select id="findUserWithQueryVoCount" parameterType="queryvo" resultType="int" >
  21. select count(2) from user
  22. <include refid="where_if_vo"></include>
  23. </select>
  24. </mapper>

4、foreach动态遍历集合参数

①第一种方法:
    select * from user where (id=22 or id=23 or id=33)
   
  1. <!-- 接收集合参数 -->
  2. <select id="findUserWithOr" parameterType="queryvo" resultType="user" >
  3. select * from user
  4. <where>
  5. <foreach collection="ids" item="id" open="(" separator="or" close=")" >
  6. id=#{id}
  7. </foreach>
  8. </where>
  9. </select>
  1. @Test
  2. public void fun4() throws IOException{
  3. InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
  4. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  5. SqlSession sqlSession = sqlSessionFactory.openSession();
  6. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  7. QueryVo queryVo = new QueryVo();
  8. List<Integer> ids = new ArrayList<>();
  9. ids.add(22);
  10. ids.add(24);
  11. ids.add(26);
  12. queryVo.setIds(ids);
  13. List<User> list = userMapper.findUserWithOr(queryVo);
  14. System.out.println(list);
  15. }

②另一种方法:
select *  from user where id in (22,23,33)
  1. <!-- 接收集合参数 -->
  2. <select id="findUserWithIn" parameterType="queryvo" resultType="user" >
  3. select * from user
  4. <where>
  5. <foreach collection="ids" item="id" open="id IN(" separator="," close=")" >
  6. #{id}
  7. </foreach>
  8. </where>
  9. </select>
java代码只要改个方法名即可

arraylist、list=======》list
数组====》array




五、mybatis和spring整合

spring配置文件:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns="http://www.springframework.org/schema/beans"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-4.2.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
  15. <context:property-placeholder location="classpath:jdbc.properties" />
  16. <!-- 整合持久层框架 -->
  17. <!-- 数据源 -->
  18. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
  19. <property name="driverClassName" value="${jdbc.driver}"></property>
  20. <property name="url" value="${jdbc.url}"></property>
  21. <property name="username" value="${jdbc.username}"></property>
  22. <property name="password" value="${jdbc.password}"></property>
  23. </bean>
  24. <!-- 创建工厂,生成sqlSession -->
  25. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
  26. <property name="dataSource" ref="dataSource" ></property>
  27. <!-- 扫描别名 -->
  28. <property name="typeAliasesPackage" value="com.itcast.domain" ></property>
  29. <!-- 加载sqlMapConfig.xml文件 -->
  30. <property name="configLocation" value="classpath:sqlMapConfig.xml" ></property>
  31. </bean>
  32. <!-- 扫描接口,开启接口代理方式开发 -->
  33. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
  34. <property name="basePackage" value="com.itcast.dao" ></property>
  35. </bean>
  36. </beans>
另一种扫描接口的方法:
<bean class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
或者直接在sqlMapConfig.xml里面配置

1、传统模式整合:

applicationContext.xml配置
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns="http://www.springframework.org/schema/beans"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-4.2.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
  15. <context:property-placeholder location="classpath:jdbc.properties" />
  16. <!-- 整合持久层框架 -->
  17. <!-- 数据源 -->
  18. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
  19. <property name="driverClassName" value="${jdbc.driver}"></property>
  20. <property name="url" value="${jdbc.url}"></property>
  21. <property name="username" value="${jdbc.username}"></property>
  22. <property name="password" value="${jdbc.password}"></property>
  23. </bean>
  24. <!-- 创建工厂,生成sqlSession -->
  25. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
  26. <property name="dataSource" ref="dataSource" ></property>
  27. <!-- 扫描别名 -->
  28. <property name="typeAliasesPackage" value="com.itcast.domain" ></property>
  29. <!-- 加载sqlMapConfig.xml文件 -->
  30. <property name="configLocation" value="classpath:sqlMapConfig.xml" ></property>
  31. </bean>
  32. <!-- 定义dao对象,注入工厂对象 -->
  33. <bean class="com.itcast.dao.impl.UserMapperImpl" >
  34. <property name="sqlSessionFactory" ref="sqlSessionFactory" ></property>
  35. </bean>
  36. </beans>

sqlMapConfig.xml配置:
  1. <configuration>
  2. <mappers>
  3. <!-- <package name="com.itcast.dao"/> -->
  4. <mapper resource="com/itcast/dao/UserMapper.xml" />
  5. </mappers>
  6. </configuration>
使用传统模式,有实现类
  1. public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
  2. @Override
  3. public List<User> findUserWithQueryVo(QueryVo queryVo) {
  4. List<User> list = this.getSqlSession().selectList("com.itcast.dao.UserMapper.findUserWithQueryVo", queryVo);
  5. return list;
  6. }
  7. }
测试类:
  1. @Test
  2. public void fun2() throws IOException{
  3. ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
  4. UserMapperImpl mapperImpl = context.getBean(UserMapperImpl.class);
  5. User user = new User();
  6. user.setSex("男");
  7. user.setUsername("张");
  8. QueryVo queryVo = new QueryVo();
  9. queryVo.setUser(user);
  10. List<User> list = mapperImpl.findUserWithQueryVo(queryVo);
  11. System.out.println(list);
  12. }

2、接口代理模式整合:

applicationContext.xml加上接口扫描即可

测试:
UserMapper bean = context.getBean(UserMapper.class);








原创粉丝点击