Mybatis 中一对多,多对一的配置

现在有很多电商平台,就拿这个来说吧。顾客跟订单的关系,一个顾客可以有多张订单,但是一个订单只能对应一个顾客。

  一对多的顾客

<?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.zdp.domain.Person"> <resultMap type="Person" id="personBean">
<id column="personId" property="id"/>
<result column="personName" property="name"/>
<result column="personAddress" property="address"/>
<result column="personTel" property="tel"/> <!-- 一对多的关系 -->
<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
<collection property="orders" ofType="Order">
<id column="orderId" property="id"/>
<result column="orderNumber" property="number"/>
<result column="orderPrice" property="price"/>
</collection>
</resultMap> <!-- 根据id查询Person, 关联将Orders查询出来 -->
<select id="selectPersonById" parameterType="string" resultMap="personBean">
select p.*, o.* from person p, orders o where p.personId = o.pid and p.personId = #{id}
</select> </mapper> 多对一的订单
<?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.zdp.domain.Order">
<resultMap type="Order" id="orderBean">
<id column="orderId" property="id"/>
<result column="orderNumber" property="number"/>
<result column="orderPrice" property="price"/> <!-- 多对一的关系 -->
<!-- property: 指的是属性的值, javaType:指的是属性的类型-->
<association property="person" javaType="Person">
<id column="personId" property="id"/>
<result column="personName" property="name"/>
<result column="personAddress" property="address"/>
<result column="personTel" property="tel"/>
</association>
</resultMap>
<!-- 根据id查询Order, 关联将Person查询出来 -->
<select id="selectOrderById" parameterType="string" resultMap="orderBean">
select p.*, o.* from person p, orders o where p.personId = o.pid and o.orderId = #{id}
</select>
</mapper> 总配置: sqlMapConfig.xml
<?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>
     //这块儿做了别名的配置所以上面两个配置文件中可以使用Person和Order直接去代表类的全名
<typeAliases>
  <typeAlias type="com.zdp.domain.Person" alias="Person"/>
  <typeAlias type="com.zdp.domain.Order" alias="Order"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射文件的位置 -->
<mapper resource="com/zdp/domain/Person.xml" />
<mapper resource="com/zdp/domain/Order.xml" />
</mappers>
</configuration>
上一篇:ORACLE 查询一个数据表后通过遍历再插入另一个表中的两种写法


下一篇:jQueryUI Datepicker的使用