YunVN网友
发表于 2016-11-24 09:07:25
| 阅读模式
MyBatis多表连接
这是一个用来说明如何使用MyBatis、Java和MySQL实现多表连接的例子。
三个表:
address
address_type
address_mapping
id address_id address_type_id
这样一个设计使得对于一个特定的用户而言有多个类型的地址,如有一个工作地址,一个家庭地址、一个度假家庭地址等。
得到所有地址及其关联类型的SQL语句类似如下:
select * from address a
left outer join address_mapping am on a.id = am.address_id
left outer join address_type at on at.id = am.address_type_id
此时Java模型只有两个Address和AddressType,分别映射前两个表。
Integer Address.getId()
String Address.getData()
AddressType Address.getType()
Integer AddressType.getId()
String AddressType.getType()
如果你已为AddressMapping创建POJO对象,那么现在就删除它。你并不需要这个对象,因为映射表address_mapping仅在连接中使用。
下面的代码应是MyBatis映射文件的一部分。
首先定义获取所有地址的查询语句,需要上述三张表的连接。
<select id="getAddress" resultMap="addressResultMap">
select
a.id as "a_id",
a.address_data as "a_data",
at.id as "at_id",
at.type as "at_type",
am.id as "am_id",
am.address_id as "am_address_id",
am.address_type_id as "am_address_type_id"
left outer join address_mapping am on a.id = am.address_id
left outer join address_type at on at.id = am.address_type_id
</select>
接下来我们需要为AddressType定义一个resultMap。
<!-- simple result map -->
<resultMap id="addressTypeResultMap" type="AddressType">
<id property="id" column="at_id" />
<result property="type" column="at_type" />
</resultMap>
最后,我们需要为Address定义一个resultMap。它有一个AddressType对象的引用。因为这是一个1:1的关联,我们在resultmap中只需要一个association元素。
<!-- complex result map -->
<resultMap id="addressResultMap" type="Address">
<id property="id" column="a_id" />
<result property="data" column="a_data" />
<association property="type" column="at_id" javaType="AddressType" resultMap="addressTypeResultMap"/>
OR
<association property="type" column="am_address_type_id" javaType="AddressType" resultMap="addressTypeResultMap"/>
</resultMap>
注:association元素的column属性使用at_id还是am_address_type_id关系不大,只要是join on的字段之一,在本例中是at_id和am_address_type_id。
注:这里我们使用了MyBatis提供的resultMap链功能。链意味着一个resultMap可以引用另一个resultMap,使得能把表数据拉到复杂对象的引用中。
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com