@Data @AllArgsConstructor @NoArgsConstructor @Builder @Table(name = "advert") public class Advert { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "广告唯一id") private Integer id; @ApiModelProperty(value = "广告名称") @NotBlank(message = "广告名称不可为空", groups = {AddGroup.class, UpdateGroup.class}) private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "position_id") private AdPosition position; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "media_id") private MediaFile media; } @Data @AllArgsConstructor @NoArgsConstructor @Builder @Table(name = "ad_position") public class AdPosition { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @ApiModelProperty(value = "位置名称") @NotBlank(message = "位置名称不可为空", groups = {AddGroup.class}) private String name; @OneToMany(mappedBy = "AdPosition", cascade = CascadeType.ALL) private List<Advert> adverts = new ArrayList<>(); } @Data @AllArgsConstructor @NoArgsConstructor @Builder @Table(name = "media_file") public class MediaFile { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @ApiModelProperty(value = "媒体文件名称") private String fileName; @ApiModelProperty(value = "媒体文件类型") private Integer fileType; @ApiModelProperty(value = "媒体文件URL地址") private String fileUrl; @OneToMany(mappedBy = "MediaFile", cascade = CascadeType.ALL) private List<Advert> adverts = new ArrayList<>(); } public interface MyBaseMapper<T> extends Mapper<T>, MySqlMapper<T>,MyInsertListMapper<T> {} public interface AdvertMapper extends MyBaseMapper<Advert> {}如何在查询Advert表数据时,将关联的ad_position和media_file表中的数据一并查询
时间: 2024-03-02 08:51:21 浏览: 77
可以使用MyBatis的XML配置文件实现关联查询。以下是一个简单的示例,假设我们要查询Advert表中的数据,并将关联的AdPosition和MediaFile表中的数据一并查询出来。
首先,在AdvertMapper.xml中定义一个查询语句,使用左连接将Advert表和AdPosition表、MediaFile表关联起来,并使用resultMap将查询结果映射到Advert对象中:
```
<select id="findAdverts" resultMap="advertMap">
SELECT a.*, p.id AS position_id, p.name AS position_name, m.id AS media_id, m.file_name, m.file_type, m.file_url
FROM advert a
LEFT JOIN ad_position p ON a.position_id = p.id
LEFT JOIN media_file m ON a.media_id = m.id
</select>
<resultMap id="advertMap" type="Advert">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="position" javaType="AdPosition">
<id property="id" column="position_id"/>
<result property="name" column="position_name"/>
</association>
<association property="media" javaType="MediaFile">
<id property="id" column="media_id"/>
<result property="fileName" column="file_name"/>
<result property="fileType" column="file_type"/>
<result property="fileUrl" column="file_url"/>
</association>
</resultMap>
```
接下来,在AdvertMapper接口中定义一个findAdverts方法,用于调用上面定义的查询语句:
```
List<Advert> findAdverts();
```
最后,在需要使用的地方调用findAdverts方法即可查询出Advert表中的数据,并将关联的AdPosition和MediaFile表中的数据一并查询出来。
阅读全文