一对一(user表和card表 身份证对应关系)
数据库:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `card` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`num` varchar(32) DEFAULT NULL,
`per_fk` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
查询每个人对应的user表中全部信息和card表中的身份证号num
- 表与表关系---->实体与实体
- 在其中一方加入另一方的实体属性(在User 类加Card实体属性,set,get方法)
- 编写User的自定义结果类型resultMap(这是都是手动映射)
id设为reuse,下面要重复使用
column:数据库中字段
property:实体类中属性
<resultMap type="user" id="reuse">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="birthday" property="birthday"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
</resultMap>
- 第一种查询方式
property:自定义类型的属性名(User中的card)
javaType:指定属性的类型com.yx.bean.Card
如果property中为自定义类型,要用association和javaType
<resultMap id="u_c1" type="user" extends="reuse">
<!--
property:自定义类型的属性名(User中的card)
javaType:指定属性的类型com.yx.bean.Card
-->
<!--如果property中为自定义类型,要用association和javaType-->
<association property="card" javaType="card">
<!--
column:数据库中字段
property:实体类中属性
-->
<result column="num" property="num"/>
</association>
</resultMap>
<select id="one2one1" resultMap="u_c1"