标签:
主要是在配置文件中,配置好所要包含的字段。
类关系:account----role,1对1
account包含role类
java类:
public class Account{ private Integer accountId; private String username; private String password; private Role role; }
public class Role { private Integer id; private Integer leave; private String name; }
数据库表:
-- -- 表的结构 `account` -- CREATE TABLE IF NOT EXISTS `account` ( `accountId` int(32) NOT NULL AUTO_INCREMENT, `userName` varchar(32) COLLATE utf8_bin NOT NULL, `password` varchar(32) COLLATE utf8_bin NOT NULL, `roleId` int(32) NOT NULL,PRIMARY KEY (`accountId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1005 ;
-- -- 表的结构 `role` -- CREATE TABLE IF NOT EXISTS `role` ( `id` int(21) NOT NULL AUTO_INCREMENT, `r_leave` int(11) NOT NULL, `name` varchar(32) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=12 ;
因为我是分开的,所有有两个配置文件。可以写在一个配置文件中
account-resultmap.xml设置,在配置文件中,也包含了role类的所有对应:
<mapper namespace="accountMap"> <!-- id 用于*-mapper.xml 中进行自动填值 ,--> <resultMap type="com.hoo.entity.Account" id="accountResultMap"> <id property="accountId" column="accountId"/> <result property="username" column="userName"/> <result property="password" column="password"/> <association property="role" javaType="com.hoo.entity.Role"> <id property="id" column="id"/> <result property="leave" column="r_leave"/> <result property="name" column="name"/> </association> </resultMap> </mapper>
mapper.xml设置,查的时候,直接查两表,mybatis自动对应数据:
<select id="getAllAccount" resultType="list" resultMap="accountMap.accountResultMap"> <![CDATA[ select * from account a,role r where a.roleId=r.id ]]> </select> <!-- accountResultMap是account-resultmap.xml中定义的resultmap --> <select id="getAccountById" parameterType="string" resultType="com.hoo.entity.Account" resultMap="accountMap.accountResultMap"> <![CDATA[ select * from account a,role r where a.accountId = #{id} and a.roleId=r.id ]]> </select> <!-- 自动生成id策略 --> <insert id="addAccount" useGeneratedKeys="true" keyProperty="accountId" parameterType="account"> insert into account(accountId, status, username, password,phone,email,roleId) values(#{accountId}, #{status}, #{username}, #{password},#{phone},#{email},#{role.id}) </insert>
标签:
原文地址:http://www.cnblogs.com/v-weiwang/p/4789083.html