简体   繁体   中英

Child entity elements not persisting in one to many mapping with hibernate and spring data jpa

I have used spring boot with hibernate. And swagger to generate the dtos and the api interface. There are two entities. The project entity is the parent and application entity is the child. Have create a onetomany relationship. But when i try to persist. I see not applications getting added for a project.

Project Entity:

@Entity
@Table(name="ProjectEntity")
public class ProjectEntity  {

    @Id
    @Column(name = "ProjectGuid", length = 36, nullable = false, unique = true)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long  id;

    @Column(name = "Name")
    private String name;

    @OneToMany(mappedBy="projectApp", cascade = CascadeType.ALL)
    private List<ApplicationEntity> apps=new ArrayList<>();

    public ProjectEntity() {
    }

    public ProjectEntity(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<ApplicationEntity> getApps() {
        return apps;
    }

    public void setApps(List<ApplicationEntity> apps) {
        this.apps = apps;
    }
}

Application Entity:

@Entity
@Table(name="ApplicationEntity")
public class ApplicationEntity   {
    @Id
    @Column(name = "Name", length = 36, nullable = false, unique = true)
    private String name;

    private String repositoryUrl;

    @ManyToOne
    @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
    @JoinColumn(name = "ProjectGuid")
    private ProjectEntity projectApp;

    public ApplicationEntity() {
    }

    public ApplicationEntity(String name, String repositoryUrl) {
        this.name = name;
        this.repositoryUrl = repositoryUrl;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRepositoryUrl() {
        return repositoryUrl;
    }

    public void setRepositoryUrl(String repositoryUrl) {
        this.repositoryUrl = repositoryUrl;
    }

    public ProjectEntity getProjectApp() {
        return projectApp;
    }

    public void setProjectApp(ProjectEntity projectApp) {
        this.projectApp = projectApp;
    }
}

Controller operation:

ProjectEntity project = projectService.getProject(projectName);
List<ApplicationEntity> appList = new ArrayList<>();
ApplicationEntity appEntity = new ApplicationEntity(app.getName(), app.getRepositoryUrl());
applicationRepository.save(appEntity);
appList.add(appEntity);
project.setApps(appList);
projectRepository.save(project);

You need to set the id of the ProjectEntity on the owning side (which is the ApplicationEntity )

appEntity.setProjectApp(project);

Otherwise hibernate (and your database) does not know to which parent a ApplicationEntity belongs.

Here is an example many to one relation with spring data jpa :

@Data
@MappedSuperclass
public class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
}

@Data
@Entity
public class Question extends BaseEntity{
    private String questionText;
    private int anketId;
    private int subjectId;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "question")
    List<Answer> answers;
}

@Data
@Entity
public class Answer extends BaseEntity{
    private String answerText;
    private String code;
    private int score;
    private int priority;

    private boolean isValidAnswer;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "question_id", referencedColumnName = "id", insertable = false, updatable = false)
    private Question question;
}

@DataJpaTest
public class QuestionRepositoryTest {

@Autowired
TestEntityManager entityManager;

@Autowired
QuestionRepository sut;

@Test
public void it_should_create_question_wiht_answers() {

    Question question = new Question();
    question.setSubjectId(1);
    question.setAnketId(1);
    question.setQuestionText("test question");

    Answer answer = new Answer();
    answer.setAnswerText("answer");
    answer.setCode("1a");
    answer.setPriority(0);
    answer.setValidAnswer(true);

    question.setAnswers(Arrays.asList(answer));

    entityManager.persistAndFlush(question);

    List<Question> questionList = sut.findAll();

    assertThat(questionList).containsExactly(question);
    assertThat(questionList.get(0).getAnswers().size()).isGreaterThan(0);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM