Mybatis 输入映射和输出映射

1.如何使 Mapper.xml 文件和 Mapper 接口进行匹配 ?
(1) 接口的全类名要和 Mapper.xml 文件中的 namespace 对应 ! 默认Mapper.xml 文件和 Maper 接口需要在同一个包下。
<!--
namespace: 名称空间. 是对当前 Mapper 文件的唯一标示.通常以 (实体类类名 + Mapper)结尾 
-->
< mapper namespace ="com.guigu.mybits.mapper.StudentMapper">......</ mapper>
(2)  接口中的方法名和所对应XML文件中的id相一致。
public interface StudentMapper {  
    Student selectStudent(@Param("id") Integer StudentId);  
}
<!--
          映射一个查询语句
          1. id 唯一标识改查询语句. 可以通过当前映射文件的 namespace 和 id 来唯一的定位到当前的 select.
          2. resultType 指定返回值的类型. 通常为全类名.
          3. 注意: 若类的属性名和数据表的列名不一致, 则可以使用别名
-->
<select id="selectStudent" resultType="com.guigu.mybits.beans.Student" >
     select StudentId,Student_Name AS "StudentName",birth from students where StudentId = #{id}
</select >
2. 关于为 Mapper 的方法传递参数
(1) 若传递一个参数, 则可以什么多不做. 在 Mapper.xml 文件中的参数名可以随便写.
     建议使用 @Param 注解进行对应
在studentMapper.java中
Student selectStudent(@Param("id") Integer id);
在StudentMapper.xml中
<select id="selectStudent" resultType="com.atguigu.mybatis.beans.Student">
     select id, last_name AS "lastName", birth from students where id = #{id}
</select>
(2) 若传递多个参数, 则有 3 种方式.
    ① 传递一个对象. 然后使对象的 get方法对应的属性和 SQL 语句中的变量名相对应
void save(Student student);
<insert id="save">
     INSERT INTO students (last_name, birth)
     VALUES  (#{lastName},  #{birth} )
</insert>
public class MyBitsTest {
     private ApplicationContext ctx = null;
     private StudentMapper studentMapper=null ;

     {
           ctx = new ClassPathXmlApplicationContext("beans.xml" );
           studentMapper =ctx .getBean(StudentMapper.class);
     }

@Test
     public void save1(){
          Student student = new Student();
          student.setStudentName( "hahah");
          student.setBirth( new Date());
          studentMapper.save(student);
     }
}
    ② 传递一个 Map 类型的参数, 在具体使用参数时会调用 Map 的 get(参数名) 方法
void save3(Map<String, Object> params);
<insert id="save3">
     INSERT INTO students(last_name, birth)
     VALUES(#{lastName}, #{birth})
</insert>
 @Test
     public void save3(){
          Map<String,Object> params = new HashMap<>();
          params.put( "StudentName","lmk" );
          params.put( "birth",new Date());
           studentMapper.save3(params);
     }
    ③ 使用多个 @Param 注解. 使变量名和 SQL 语句中变量名对应
void save2(@Param("lastName") String lastName,@Param("birth") Date birth);
<insert id="save2">
     INSERT INTO students(last_name, birth)
     VALUES(#{lastName}, #{birth})
</insert>
@Test
     public void save2(){
           studentMapper.save2("abcd" ,new Date());
     }
    注意: 以上 3 种传递参数的方式不能混用.

3.parameterType(输入类型)
(1) 传递简单类型
    参考上面的代码:使用#{}占位符,或者${}进行sql拼接。
(2) 传递pojo对象
    参考上面的代码:Mybatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称。
(3) 传递pojo包装对象
    查询条件可能是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如查询用户信息的时候,将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
    包装对象:Pojo类中的一个属性是另外一个pojo。

4.resultType(输出类型)
(1) 输出简单类型
(2) 输出pojo对象
(3) 输出pojo列表

5.resultMap
    resultType可以指定将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。
    如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。
    resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。
需求:查询订单表order的所有数据
(1) 数据库
CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '下单用户id',
  `number` varchar(32) NOT NULL COMMENT '订单号',
  `createtime` datetime NOT NULL COMMENT '创建订单时间',
  `note` varchar(100) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`),
  KEY `FK_orders_1` (`user_id`),
  CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
(2) Order对象:
package com.itheima.mybatis.pojo;
import java.io.Serializable;
import java.util.Date;
public class Orders  implements Serializable{
    @Override
    public String toString() {
        return "Orders [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime
                + ", note=" + note + "]";
    }
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private Integer id;
    private Integer userId;
    private String number;
    private Date createtime;
    private String note;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number == null ? null : number.trim();
    }
    public Date getCreatetime() {
        return createtime;
    }
    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
    public String getNote() {
        return note;
    }
    public void setNote(String note) {
        this.note = note == null ? null : note.trim();
    }
}
(3)Mapper.xml文件:创建OrderMapper.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";>
<mapper namespace="com.itheima.mybatis.mapper.OrderMapper">
    <resultMap type="Orders" id="orders">
         <result column="user_id" property="userId"/>
    </resultMap>
    
    <select id="selectOrdersList" resultMap="orders">
         SELECT id, user_id, number, createtime, note FROM orders
    </select>
</mapper>
(4) 编写接口如下:
public interface OrderMapper {
    //  查询订单表order的所有数据
    public List<Orders> selectOrdersList();
}
(5) 测试方法
public class MybatisMapperTest {
//  查询订单表order的所有数据
    @Test
    public void testOrderList() throws Exception {
         //加载核心配置文件
         String resource = "sqlMapConfig.xml";
         InputStream in = Resources.getResourceAsStream(resource);
         //创建SqlSessionFactory
         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
         //创建SqlSession
         SqlSession sqlSession = sqlSessionFactory.openSession();
         
         OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
         
         List<Orders> ordersList = mapper.selectOrdersList();
         for (Orders orders : ordersList) {
             System.out.println(orders);
         }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员学习圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值