今天在写学校的实训项目时,遇到如下问题,一个实体类与另一个实体类是多对多的关系,且有个实体类中所存储的是另一个实体类的集合,所以在进行插入操作是,要同时向两张表中插入数据,现在已经得到解决办法。
Student类:
public class Student implements Serializable {
private Integer id;
private String name;
private Integer age;
private String bir;
private String phone;
private String qq;
private String attr;
private String starts;
private String mark;
private Integer cityId;
private Integer clazzId;
private Integer groupId;
private String cityName;
private String clazzName;
private String groupName;
private List<Tag> tagList;
}
Tag表
public class Tag implements Serializable {
private Integer id;
private String name;
private String type;
private Date createtime;
}
有如下需求,在插入学生时,学生会有很多的标签(tag),在页面传回数据是,用了一个tagList集合来接收,现在要将学生的信息插入到学生表中,然后将学生的标签放在另一张关联表中。
插入步骤:
步骤一:
- 先插入学生信息:
<insert id="save" useGeneratedKeys="true" keyProperty="id" keyColumn="id" > insert into t_student(name, age, bir, phone, qq, attr, starts, mark, cityid, clazzid, groupid) values(#{name}, #{age}, #{bir},#{phone},#{qq},#{attr},#{starts},#{mark},#{cityId},#{clazzId},#{groupId}) </insert> // useGeneratedKeys 是否以jdbc的方式将插入后的自增主键又返回个实体类 // keyProperty 实体类中对应的主键属性名 // keyCloumn 数据库中对应的主键属性名
2.插入关联表数据
<insert id="saveStudentTag" parameterType="com.lbw.ems.entity.Student">
insert into t_student_tag(studentid, tagid) values
<foreach collection="tagList" item="tag" separator=",">
(#{id}, #{tag.id})
</foreach>
</insert>
// 因为此时我们需要当前的学生的Id,所以我们的参数类型还是一个Student类,在插入是,我们需要的是Student类中tagList集合中所有的id
所以使用了foreach标签
// foreach标签 遍历array、list、map(我只用过list)
// collection 填你想要遍历的集合在实体类中对应的属性名
// item 将每次遍历出来的对象取一个名字,不然不好取值,尤其是在两个实体类的字段名相同的时候,真的难顶
// sparator="," 每遍历一次后,在后面加上你所填的符
结果测试