1 Preparing tables and data
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 Defining Entity classes: Table fields and entity properties are inconsistent
public class Order {
private int id;
private String orderNo;
private float price;
}
3 Workaround 3.1 Alias by query
<!-- 通过查询字段的别名来对应 -->
<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
@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 by 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: Encapsulating Some mapping relationships
- ID: specifically for primary key
- Result: For general fields
Test
@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);
}
Donate US
The Mentor Studio has been working to help programmers learn to program more quickly and easily, and if you agree with our results and feel helpful, you are welcome to donate ^_^ to us.
04_ Resolving conflicts where field names differ from entity class property names