4.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);
4.2定义实体类
Orders.java
package com.entity;
public class Orders {
private int id;
private String name;
private int price;
public Orders()
{
}
public Orders(int id, String name, int price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Orders [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
4.3解决字段名和实体类属性名的两种不同配置方式
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.config.ordersMapper">
<!-- 方式一: 通过在 sql 语句中定义别名 <select id="selectOrder" parameterType="int" resultType="com.entity.Orders">
select order_id id, order_no name,order_price price from orders where order_id=#{id}
</select> -->
<!-- 方式二: 通过<resultMap> -->
<select id="selectOrderResultMap" parameterType="int" resultMap="orderResultMap">
select * from orders where order_id=#{id}
</select>
<resultMap id="orderResultMap" type="com.entity.Orders">
<id property="id" column="order_id" />
<result property="name" column="order_no" />
<result property="price" column="order_price" />
</resultMap>
</mapper>
4.4测试方法
Test3.java
package com.test;
import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.entity.Orders;
import com.inter.UserMapper;
import com.util.MybatisUtil;
public class Test3 {
//测试查询
@Test
public void testGetOrders() throws IOException
{
SqlSession session=MybatisUtil.getSession();
String statement="com.config.ordersMapper.selectOrderResultMap";
Orders orders=session.selectOne(statement, 1);
session.close();
System.out.println(orders);
}
}
网友评论