4.1準(zhǔn)備數(shù)據(jù)表和簡(jiǎn)單數(shù)據(jù)
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定義實(shí)體類
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解決字段名和實(shí)體類屬性名的兩種不同配置方式
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">
<!-- 方式一: 通過(guò)在 sql 語(yǔ)句中定義別名 <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> -->
<!-- 方式二: 通過(guò)<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測(cè)試方法
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 {
//測(cè)試查詢
@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);
}
}