在Mybatis中表之间的映射关系
- idea
- maven
- mybatis
一、创建工程
http://www.cnblogs.com/xiaohai0630/p/7658094.html
二、一对一的关系
- 两张表:
team
address
- team中有一列address_id,对应address表中的id
1、在查询team表的同时查询关联的address表
- 建立实体类--bean这个package下
Team
类
public class Team {
private Integer id;
private String name;
private Integer aid;
// 作为关联的值
private Address address;
// 省略get、set、toString方法
}
Address
类
public class Address {
private Integer id;
private String name;
// 省略get、set、toString方法
}
- 建立接口--mapper这个package下
TeamMapper
接口
public interface TeamMapper {
List<Team> findAllTeam();
List<Team> findTeamById(@Param("tid") Integer id);
}
AddressMapper
接口
public interface AddressMapper {
List<Address> findAllAddress();
List<Address> findAddressById(@Param("aid") Integer id);
}
-
每个接口中都可以定义各种方法
-
如果有的方法需要参数,有两种方式添加参数:
- 1、直接添加一个类
- 2、用@Param注解,注解中的参数名是写在sql语句中的条件
-
建立接口对应的xml文件--mapper这个package下,用来写sql语句
- 配置
TeamMapper.xml
xml文件<?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"> <!--namespace指向对应的接口,一定要写!!!--> <mapper namespace="com.lanou.team.mapper.TeamMapper"> <!--type指向对应的类,这个类用来和数据库中的表对应,其中参数的个数和类型要匹配, 参数的名称可以不同,不同的时候就在下面写出它们的对应关系--> <resultMap id="BaseMap" type="com.lanou.team.bean.Team"> <!--类中属性和表的列名的对应关系,id是需要特殊指明的,其它的都用result标签就可以--> <id column="id" property="id"/> <result column="name" property="name"/> <result column="address_id" property="aid"/> <!--需要一对一的查询时的标签--> <association property="参数1" column="参数2" javaType="参数3" select="参数4"/> </resultMap> <select id="findAllTeam" resultMap="BaseMap"> SELECT *FROM team </select> </mapper>
-
想要在查询team的同时把team关联的address也查出来
- 1、在team这个类中加入对应的
private Address address;
- 2、在TeamMapper.xml中的resultMap标签中添加一个association标签
- 3、association的四个属性:
- (1)参数1:team这个类中关联想要查询的类的那个属性(例如想要通过team查询address,这里填的就是
private Address address;
中的address(小写) - (2)参数2:当前这个类中有的可以关联另一个表的参数(在team表中有一个address_id,它对应着address表中的主键id,所以这里写address_id)
- (3)参数3:返回值的类型,是一个类的时候直接写类名,是一个List集合的时候写ArrayList
- (4)参数4:想要查询的Mapper中的sql语句,前面加上命名空间,最后
.方法名
- 1、在team这个类中加入对应的
AddressMapper.xml
xml文件
<?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.lanou.team.mapper.AddressMapper">
<!--类中属性和表的列名的对应关系,id是需要特殊指明的,其它的都用result标签就可以-->
<resultMap id="BaseMap" type="Address">
<id column="id" property="id"/>
<result column="name" property="name"/>
</resultMap>
<select id="findById" resultMap="BaseMap">
SELECT *FROM address WHERE id=#{aid}
</select>
</mapper>
- 这里只需要写需要的sql语句就可以