多对一
多个Blog对应一个Type
Blog类
public class Blog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String content;
private String firstPicture;
private String flag;
private Integer views;
private boolean appreciation;
private boolean shareStatement;
private boolean commenttabled;
private boolean published;
private boolean recommend;
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;
@ManyToOne
private Type type;
Type类
public class Type {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message="分类名称不能为空")
private String name;
@OneToMany(mappedBy = "type")
private List<Blog> blogs = new ArrayList<>();
<!--定义Blog和Type的resultMap-->
<!--column代表数据库字段,property代表实体类字段-->
<resultMap id="blogtype" type="Blog">
<id column="id" property="id"/>
<result column="title" property="title"/>
<result column="recommend" property="recommend"/>
<result column="update_time" property="updateTime"/>
<!--配置封装type的内容-->
<!--此处的property代表Blog实体类中定义的Type,column代表数据库blog表中连接type表的外键type_id-->
<association property="type" column="type_id" javaType="Type">
<result column="name" property="name"/>
</association>
</resultMap>
<!--查询语句如下-->
<select id="findAll" resultMap="blogtype">
select b.*,t.name from t_blog b,t_type t where b.type_id=t.id and 1=1
<if test="title!=null">
and title like '%' #{title} '%'
</if>
<if test="typeId!=null">
and type_id = #{typeId}
</if>
<if test="recommend!=null">
and recommend = #{recommend}
</if>
</select>