0
点赞
收藏
分享

微信扫一扫

Mybatis如何实现一对多或多对一的ORM映射呢?


​​精选30+云产品,助力企业轻松上云!>>>

Mybatis如何实现一对多或多对一的ORM映射呢?_hibernate

​​

1.我们准备两个实体类,一个是Blog类,另一个是Comment类,通过对比实体关系,我们知道,一篇博客可以有多条评论,所以是一对多的关系,所以评论对于博客是多对一的关系。

我们可以通过外键约束来简历实体之间的联系,如简历评论中的一个blog_id字段对应博客的主键字段。

2.Blog.java,通过JPA的注解来实现数据库表的映射。

@Entity
@Table(name = "t_blog")
public class Blog {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

private String title;

@Basic(fetch = FetchType.LAZY) //可以没有
@Lob
private String content;
private String firstPicture;
private String flag;
private Integer views;
private boolean appreciation;
private boolean shareStatement;
private boolean commentabled;
private boolean published;
private boolean recommend;
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;

@ManyToOne
private Type type;

@ManyToMany(cascade = {CascadeType.PERSIST})
private List<Tag> tags = new ArrayList<>();


@ManyToOne
private User user;

@OneToMany(mappedBy = "blog")
private List<Comment> comments = new ArrayList<>();

@Transient
private String tagIds;

private String description;

//省略 对外方法 getter setter 构造 toString
}

3.Comment.java,评论的实体类

@Entity
@Table(name = "t_comment")
public class Comment {

@Id
@GeneratedValue
private Long id;
private String nickname;
private String email;
private String content;
private String avatar;
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;

@ManyToOne
private Blog blog;

@OneToMany(mappedBy = "parentComment")
private List<Comment> replyComments = new ArrayList<>();

@ManyToOne
private Comment parentComment;

private boolean adminComment;

//省略对外方法
}

4.Mybatis的mapper接口

/**
* @author 王一宁
* @date 2020/3/11 15:30
*/
@Mapper
public interface CommentMapper {
/*查询所有的评论信息*/
//@Select("SELECT a.content,a.email,a.nickname,a.create_time,b.title from t_comment a,t_blog b WHERE a.blog_id=b.id ORDER BY a.create_time DESC LIMIT 30;")
List<Comment> findAll();
}

5.CommentMapper.xml 为实现sql的文件

<?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.wang.springboot.mapper.CommentMapper">

<!-- 一对多 级联查询的第一种方法(嵌套查询) -->
<resultMap type="com.wang.springboot.pojo.Comment" id="blogAndComments1">
<id property="content" column="content" />
<result property="email" column="email" />
<result property="nickname" column="nickname" />
<result property="createTime" column="create_time" />
<collection property="blog" ofType="com.wang.springboot.pojo.Blog">
<result column="title" property="title"/>
</collection>
</resultMap>
<!-- 这里我们还可以通过左外连接的方式进行查询,这里不做展示,直接通过关联查询 -->
<select id="findAll" resultMap="blogAndComments1">
SELECT a.content,a.email,a.nickname,a.create_time,b.title from t_comment a,t_blog b WHERE a.blog_id=b.id ORDER BY a.create_time DESC LIMIT 30
</select>

</mapper>

举报

相关推荐

0 条评论