1 准备表和数据
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);
2 定义实体类:表的字段和实体的属性不一致
public class Order {
private int id;
private String orderNo;
private float price;
}
3 解决方法
3.1 通过查询的别名
<!-- 通过查询字段的别名来对应 -->
<select id="getOrder" parameterType="int" resultType="Order">
SELECT order_id id, order_no orderNo, order_price price FROM orders WHERE order_id=#{id}
</select>
测试
@Test
public void test1(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession();
String statement = "cn.imentors.mybatis.test4.orderMapper.getOrder";
Order order = session.selectOne(statement , 2);
System.out.println(order);
}
3.2 通过resultMap
<resultMap type="Order" id="getOrder2Map">
<id property="id" column="order_id"/>
<result property="orderNo" column="order_no"/>
<result property="price" column="order_price"/>
</resultMap>
<select id="getOrder2" parameterType="int" resultMap="getOrder2Map">
SELECT * FROM orders WHERE order_id=#{id}
</select>
- resultMap : 封装一些映射关系
- id : 专门针对主键
- result : 针对一般字段
测试
@Test
public void test2(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession();
String statement = "cn.imentors.mybatis.test4.orderMapper.getOrder2";
Order order = session.selectOne(statement , 2);
System.out.println(order);
}
捐赠我们
良师益友工作室一直在致力于帮助编程爱好更加快速方便地学习编程,如果您对我们的成果表示认同并且觉得对你有所帮助,欢迎您对我们捐赠^_^。
时间: 2024-10-12 08:50:40