解决spring-data-jpa 级联添加时,主表放弃对外键维护时外键字段为null

问题:

在spring-data-jpa中使用级联添加,一次添加多条数据时,在主表上放弃对外键维护时,添加数据到数据库,从表的外键字段为null值,当不放弃主表对外键的维护时,又正常添加。
解决spring-data-jpa 级联添加时,主表放弃对外键维护时外键字段为null_第1张图片

主表对应实体类(Team,一的一方)
@Entity
@Table(name = "team")
public class Team implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "t_id")
    private Integer tId;
    @Column(name = "t_name")
    private String tName;
    /*@OneToMany(targetEntity = Student.class,cascade = CascadeType.ALL)
    @JoinColumn(name = "link_t_id",referencedColumnName = "t_id")*/
    //主表放弃对外键的维护,mappedBy属性声明从表所对应的属性名
    @OneToMany(mappedBy = "team",cascade = CascadeType.ALL)
    private Set studentSet=new HashSet();
    ...
从表对应实体类(Student,多的一方)
@Entity
@Table(name = "student")
public class Student implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "s_id")
    private Integer sId;//学生id,主键
    @Column(name = "s_name")
    private String sName;//学生姓名
    @Column(name = "s_age")
    private Integer sAge;//学生年龄
    @Column(name = "s_sex")
    private String sSex;//学生性别
    @ManyToOne(targetEntity = Team.class)
    @JoinColumn(name = "link_t_id",referencedColumnName = "t_id")
    private Team team;//team对象
    ...
级联添加测试
@Test
    @Transactional
    @Rollback(value = false)
    public void testSave(){
        //创建一个团队
        Team team = new Team();
        team.settName("会员系统team");
        //创建学生1
        Student student = new Student();
        student.setsName("张三");
        student.setsAge(20);
        student.setsSex("男");
        student.setTeam(team);//多对一(必须要加)
        //创建学生2
        Student student1 = new Student();
        student1.setsName("小丽");
        student1.setsAge(20);
        student1.setsSex("女");
        student1.setTeam(team);//多对一(必须要加)
        //将这两个学生添加到会员系统里面
        Set studentSet = team.getStudentSet();//一对多
        studentSet.add(student);
        studentSet.add(student1);
        teamDao.save(team);
    }
解决:在主表放弃维护外键时,在测试的时候没有添加这个声明多对一的关系,相当于两张表没有关系了,所以添加的从表中的外键字段一直显示为null.

解决spring-data-jpa 级联添加时,主表放弃对外键维护时外键字段为null_第2张图片
添加上之后就能够正常保存了。
解决spring-data-jpa 级联添加时,主表放弃对外键维护时外键字段为null_第3张图片

你可能感兴趣的:(SpringDataJpa)