MyBatis(二)

MyBatis(二)

传递pojo包装对象

开发中通过pojo传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
Pojo类中包含pojo。

例如:
1.创建一个包装对象
public class QueryVo {
    private User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}
2.Mapper文件配置
//使用包装类型查询用户使用ognl从对象中取属性值,如果是包装对象可以使用.操作符来取内容部的属性
<select id="getUserByQueryVo" parameterType="queryvo" resultType="user">
    select * from user where id = #{user.id}
</select>
3.mapper接口
public interface UserMapper {
    User getUserByQueryVo(QueryVo queryVo);
}
4.测试方法
@Test
public void getUserByQueryVo(){
    //获取session
    SqlSession session = sqlSessionFactory.openSession();
    //获取mapper接口的代理对象
    UserMapper userMapper = session.getMapper(UserMapper.class);
    //创建一个QueryVo对象
    QueryVo queryVo = new QueryVo();
    //创建User对象
    User user = new User();
    user.setId(10);
    queryVo.setUser(user);
    //调用代理对象方法
    User user1 = userMapper.getUserByQueryVo(queryVo);
    System.out.println(user1);
    //关闭session
    session.close();
}

resultMap应用

resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。
    如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。
    resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。

列如:
1.mapper配置文件
<mapper namespace="cn.itcast.mybatis.mapper.OrderMapper">

    <!--定义resultMap type返回结果的pojo可以使用别名-->
    <resultMap id="listOrder" type="orders">
        <!--id 主键映射,property是pojo中主键的属性,column返回结果中主键的列-->
        <id property="id" column="id"/>
        <!--其他普通列的映射-->
        <result property="userId" column="user_id"/>
        <result property="number" column="number"/>
        <result property="createtime" column="createtime"/>
        <result property="note" column="note"/>
    </resultMap>
    <select id="getOrderList" resultMap="listOrder">
        select id,user_id,number,createtime,note from  orders
    </select>
</mapper>

2.mapper接口
public interface OrderMapper {
    List<Orders> getOrderList();
}

3.测试方法

@Test
public void getOrderList(){
    //获取session
    SqlSession session = sqlSessionFactory.openSession();
    //获取mapper接口的代理对象
    OrderMapper orderMapper = session.getMapper(OrderMapper.class);
    List<Orders> list = orderMapper.getOrderList();
    for (Orders orders:list ) {
        System.out.println(orders);
    }
    //关闭session
    session.close();
}

动态sql

1.if和where
<select id="findUserList" parameterType="user" resultType="user">
    select * from user 
    <where>
        <if test="id!=null">
        and id=#{id}
        </if>
        <if test="username!=null and username!=''">
        and username like '%${username}%'
        </if>
    </where>
</select>

2.foreach
<!--动态sql  foreach-->
    <select id="findUserByIds" parameterType="queryvo" resultType="user">
        select * from user
        <where>
            /*collection:集合 item:循环变量 open:从哪里开是循环 close:循环在哪里结束 separator:每次循环结束添加的分隔符*/
            <foreach collection="ids" item="id" open="and id in (" close=")" separator=",">
                #{id}
            </foreach>
        </where>
    </select>

Sql片段

“`xml
Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的,如下:
原始代码:

select * from user


and id=#{id}


and username like ‘%${username}%’


将where抽取成sql片段


and id=#{id}


and username like ‘%${username}%’

使用include引用:

select * from user




注意:如果引用其它mapper.xml的sql片段,则在引用时需要加上namespace,如下:

“`

关联查询

一. 一对一查询   输出结果使用 resultType/ resultMap都可以主要区别在mapper配置文件的编写上和po类的编写
1.使用resultType
创建一个OrdersUser类继承Orders类后OrdersUser类包括了Orders类的所有字段,只需要定义用户的信息字段即可。
public class OrderUser extends Orders {

    private String username;//添加自己需要的信息
    private String address;//添加自己需要的信息

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

2.使用resultMap
在Orders类中加入User属性,user属性中用于存储关联查询的用户信息,因为订单关联查询用户是一对一关系,所以这里使用单个User对象存储关联查询的用户信息。
public class Orders {
    private Integer id;

    private Integer userId;

    private String number;

    private Date createtime;

    private String note;

    private User  user;//添加user

 }

resultType配置:

    <!-- 查询所有订单信息 -->
    <select id="findOrdersList" resultType="cn.itcast.mybatis.po.OrdersCustom">
        SELECT
        orders.*,
        user.username,
        user.address
        FROM
        orders, user
        WHERE orders.user_id = user.id 
    </select>


resultMap配置:
<!-- 查询订单关联用户信息使用resultmap -->
    <resultMap type="Orders" id="orderUserResultMap">
        <id column="id" property="id"/>
        <result column="user_id" property="userId"/>
        <result column="number" property="number"/>
        <result column="createtime" property="createtime"/>
        <result column="note" property="note"/>
        <!-- 一对一关联映射 -->
        <!-- 
        property:Orders对象的user属性
        javaType:user属性对应 的类型
         -->
        <association property="user" javaType="cn.itcast.po.User">
            <!-- column:user表的主键对应的列  property:user对象中id属性-->
            <id column="user_id" property="id"/>
            <result column="username" property="username"/>
            <result column="address" property="address"/>
        </association>
    </resultMap>
    <select id="findOrdersWithUserResultMap" resultMap="orderUserResultMap">
        SELECT
            o.id,
            o.user_id,
            o.number,
            o.createtime,
            o.note,
            u.username,
            u.address
        FROM
            orders o
        JOIN `user` u ON u.id = o.user_id
    </select>
这里resultMap指定orderUserResultMap。
association:表示进行关联查询单条记录
property:表示关联查询的结果存储在cn.itcast.mybatis.po.Orders的user属性中
javaType:表示关联查询的结果类型
<id property="id" column="user_id"/>:查询结果的user_id列对应关联对象的id属性,这里是<id />表示user_id是关联查询对象的唯一标识。
<result property="username" column="username"/>:查询结果的username列对应关联对象的username属性。

二. 一对多查询
一对多查询使用resultMap实现
也是在在User类中加入List<Orders> orders属性
public class Orders {
    private Integer id;

    private Integer userId;

    private String number;

    private Date createtime;

    private String note;

    private List<User> user;//添加List<User>

 }


mapper.xml配置
<resultMap type="user" id="userOrderResultMap">
        <!-- 用户信息映射 -->
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="birthday" column="birthday"/>
        <result property="sex" column="sex"/>
        <result property="address" column="address"/>
        <!-- 一对多关联映射 -->
        <collection property="orders" ofType="orders">
            <id property="id" column="oid"/>    
              <!--用户id已经在user对象中存在,此处可以不设置-->
            <!-- <result property="userId" column="id"/> -->
            <result property="number" column="number"/>
            <result property="createtime" column="createtime"/>
            <result property="note" column="note"/>
        </collection>
    </resultMap>
    <select id="getUserOrderList" resultMap="userOrderResultMap">
        SELECT
        u.*, o.id oid,
        o.number,
        o.createtime,
        o.note
        FROM
        `user` u
        LEFT JOIN orders o ON u.id = o.user_id
    </select>

    collection部分定义了用户关联的订单信息。表示关联查询结果集
property="orders":关联查询的结果集存储在User对象的上哪个属性。
ofType="orders":指定关联查询的结果集中的对象类型即List中的对象类型。此处可以使用别名,也可以使用全限定名。
<id />及<result/>的意义同一对一查询。

Spring整合MyBatis

1.导jar包
    1、spring的jar包
    2、Mybatis的jar包
    3、Spring+mybatis的整合包。
    4、Mysql的数据库驱动jar包。
    5、数据库连接池的jar包。

2.SqlMapConfig.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>
    <typeAliases>
        <package name="cn.itcast.mybatis.pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="sqlmap/User.xml"/>
    </mappers>
</configuration>

3.applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"                   xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd                                        http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
    </bean>
</beans>

4.db.properties配置文件
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
    jdbc.username=root
    jdbc.password=root

传统dao

传统dao的开发方式
接口+实现类来完成。需要dao实现类需要继承SqlsessionDaoSupport类

Dao实现类

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

    @Override
    public User findUserById(int id) throws Exception {
        SqlSession session = getSqlSession();
        User user = session.selectOne("test.findUserById", id);
        //不能关闭SqlSession,让spring容器来完成
        //session.close();
        return user;
    }

    @Override
    public void insertUser(User user) throws Exception {
        SqlSession session = getSqlSession();
        session.insert("test.insertUser", user);
        session.commit();
        //session.close();
    }

}

配置dao
把dao实现类配置到spring容器中
<!-- 配置UserDao实现类 -->
    <bean id="userDao" class="cn.itcast.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
测试方法
@Test
    public void testFindUserById() throws Exception {
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");
        User user = userDao.findUserById(1);
        System.out.println(user);
    }

Mapper代理形式开发dao(常用)


配置mapper代理

第一种方法:
<!-- 配置mapper代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
第二种方法:
<!-- 使用扫描包的形式来创建mapper代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.itcast.mybatis.mapper"></property>
</bean>

测试方法:
public class UserMapperTest {

    private ApplicationContext applicationContext;

    @Before
    public void setUp() throws Exception {
        applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }

    @Test
    public void testGetUserById() {
        UserMapper userMapper = applicationContext.getBean(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println(user);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值