[Java] 纯文本查看 复制代码
public class Customer {
private Integer cid ;
private String cname;
//省略get/set/toString
}
/**
一个订单属于一个客户,在订单方创建客户引用
注意.客户引用的对象名字很重要
*/
public class Orders {
private Integer oid ;
private String orderName;
private String cid;
private Customer c;
//省略get/set/toString
}
[Java] 纯文本查看 复制代码
public interface OrdersMapper {
List<Orders> findAllInfo();
}
<?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.b3a4a.maybatis.mapper.OrdersMapper">
<resultMap id="order_customer" type="orders">
<id property="oid" column="oid"/>
<result property="orderName" column="oname" />
<result property="cid" column="customer_id" />
<association property="c" javaType="customer">
<id property="cid" column="cid"/>
<id property="cname" column="cname"/>
</association>
</resultMap>
<select id="findAllInfo" resultMap="order_customer">
SELECT customer.*,orders.oid,orders.oname,orders.cid AS customer_id
FROM orders
JOIN customer ON customer.cid=orders.cid
</select>
</mapper>
[Java] 纯文本查看 复制代码
@Test
public void testFindAll() throws IOException {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSession session = new SqlSessionFactoryBuilder().build(is).openSession();
OrdersMapper mapper = session.getMapper(OrdersMapper.class);
List<Orders> orders = mapper.findAllInfo();
for (Orders order : orders) {
System.out.println(order);
System.out.println(order.getCustomer());
}
session.close();
is.close();
}
[Java] 纯文本查看 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbcConfig.properties"></properties>
<typeAliases>
<package name="com.b3a4a.maybatis.domain" />
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.b3a4a.maybatis.mapper"/>
</mappers>
</configuration>