[学习小结]Mybaits的解决字段名与实体类属性名不相同的冲突

时间:2022-02-27 05:08:22

前提:

以这边博客为基础:http://blog.csdn.net/u011487470/article/details/42488131

在sql映射文件中需要编写SQL语句中需要传进来的参数(例如:select * from users where id=#{id})中的id必须数据表中id字段和实体类中id属性同名才可以,不然就会报异常。未解决这种情况,我们可以通过设置对“sql映射文件”的一些改动就能解决这个情况

优化过程

准备表和数据

<span style="font-size:12px;">CREATE TABLE orders(
order_id INT PRIMARY KEY AUTO_INCREMENT,
order_no VARCHAR(20),
order_price FLOAT
);
INSERT INTO orders(order_no, order_price) VALUES('aaaa', 23);
INSERT INTO orders(order_no, order_price) VALUES('bbbb', 33);
INSERT INTO orders(order_no, order_price) VALUES('cccc', 22);</span>

定义实体类

<span style="font-size:12px;">public class Order {

private int id;
private String orderNo;
private float price;

public Order(int id, String orderNo, float price) {
super();
this.id = id;
this.orderNo = orderNo;
this.price = price;
}

public Order() {
super();
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getOrderNo() {
return orderNo;
}

public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}

public float getPrice() {
return price;
}

public void setPrice(float price) {
this.price = price;
}

@Override
public String toString() {
return "Order [id=" + id + ", orderNo=" + orderNo + ", price=" + price
+ "]";
}

}</span>

实现getOrderById(id)的查询的映射文件的编写

orderMapper.xml:

<span style="font-size:12px;"><?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.atguigu.day03_mybaits.test4.orderMapper">
<!--
根据id查询orders表得到一个order对象
-->
<!-- 方式一: 通过在sql语句中定义别名 -->
<select id="getOrder" parameterType="int" resultType="Order">
SELECT order_id id, order_no orderNo, order_price price FROM orders WHERE order_id=#{id}
</select>
<!-- 方式二: 通过<resultMap> -->
<select id="getOrder2" parameterType="int" resultMap="getOrder2Map">
SELECT * FROM orders WHERE order_id=#{id}
</select>

<!--
resultMap : 封装一些映射关系
id : 专门针对主键
result : 针对一般字段
-->
<resultMap type="Order" id="getOrder2Map">

<id property="id" column="order_id"/>
<result property="orderNo" column="order_no"/>
<result property="price" column="order_price"/>
</resultMap>
</mapper></span>

测试代码

<span style="font-size:12px;">import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.atguigu.day03_mybaits.bean.Order;
import com.atguigu.day03_mybaits.util.MybatisUtils;

/*
* 测试: 解决字段名与实体类属性名不相同的冲突
*/
public class Test4 {

public static void main(String[] args) {
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession();
//第一种方式测试
String statement = "com.atguigu.day03_mybaits.test4.orderMapper.getOrder";
//第二种方式测试
statement = "com.atguigu.day03_mybaits.test4.orderMapper.getOrder2";
Order order = session.selectOne(statement , 2);
System.out.println(order);
}
}</span>