4

I know this has been asked a lot of times before, I know it because I've searched for every related question to my problem to try to find a solution, however, none of the proposed solutions are working for me and I'm pretty sure that I have to be missing something.

Person Class:

@Entity
@Table(name = "person", schema = "test")
public class PersonEntity {
    @Id
    @Column(name = "id")
    private long id;
    @Basic
    @Column(name = "name")
    private String name;
    @Basic
    @Column(name = "age")
    private int age;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "personid")
    private List<ProjectEntity> projects;

}

Project Class:

@Entity
@Table(name = "project", schema = "test")
public class ProjectEntity {
    @Id
    @Column(name = "id")
    private long id;
    @Basic
    @Column(name = "name")
    private String name;
    @Basic
    @Column(name = "budget")
    private int budget;
    @JoinColumn(name = "personid", referencedColumnName = "id")
    @ManyToOne(cascade = CascadeType.ALL)
    private PersonEntity personid;
}

I have a bidirectional OneToMany/ManyToOne relationship, I have tried changing the cascade type to PERSIST, adding 'optional=false' and way more things but nothing seems to work.

I read that I have to 'join' manually the entities before the persist, and that's what I did:

    em = JPAUtility.getEntityManager();
    em.getTransaction().begin();

    PersonEntity personTest = new PersonEntity();
    personTest.setName("Test");
    personTest.setAge(23);

    ProjectEntity projectTest = new ProjectEntity();
    projectTest.setName("hello");
    projectTest.setBudget(232);

    projectTest.setPersonid(personTest);

    List<ProjectEntity> projects = new ArrayList<ProjectEntity>();
    projects.add(projectTest);

    personTest.setProjects(projects);

    em.persist(personTest);
    em.getTransaction().commit();
    em.close();

    return personTest;

But I still get this:

Caused by: 
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 
Cannot add or update a child row: a foreign key constraint fails 
(`test`.`project`, CONSTRAINT `FK_Personid` FOREIGN KEY (`personid`) REFERENCES
 `person` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

I honestly don't know what I'm missing, if anyone has any suggestion I'll be more than happy to try it.

Thank you so much!


SOLUTION

I managed to solve the problem thanks to all the suggestions, basically, I was missing the @GeneratedValue(strategy=GenerationType.AUTO) annotation which I removed because I thought it didn't work but, it wasn't working because I was missing a property on the persistence.xml:

<property name="hibernate.id.new_generator_mappings" value="false" />

I found this info here

You also need a method to add the relationship in the objects:

public void addToProjects(ProjectEntity project){ project.setPersonid(this); this.projects.add(project); }

To make this work you need to initialize the List when you declare the variable:

private List<ProjectEntity> projects = new ArrayList<ProjectEntity>();

And that's it!

This is the final working code in case anyone can find it useful :):

Person Class:

@Entity
@Table(name = "person", schema = "test")
public class PersonEntity {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long id;
    @Basic
    @Column(name = "name")
    private String name;
    @Basic
    @Column(name = "age")
    private int age;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "personid")
    private List<ProjectEntity> projects = new ArrayList<ProjectEntity>();

    public void addToProjects(ProjectEntity project) {
     project.setPersonid(this);
     this.projects.add(project);
    }
}

Project Class:

@Entity
@Table(name = "project", schema = "test")
public class ProjectEntity {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long id;
    @Basic
    @Column(name = "name")
    private String name;
    @Basic
    @Column(name = "budget")
    private int budget;
    @JoinColumn(name = "personid", referencedColumnName = "id")
    @ManyToOne(cascade = CascadeType.PERSIST)
    private PersonEntity personid;

    public void setPersonid(PersonEntity personid) {
       this.personid = personid;
    }
}

Make sure you add the Children to their Parent and vice-versa (addToProjects())

    em = JPAUtility.getEntityManager();
    em.getTransaction().begin();

    PersonEntity personTest = new PersonEntity();
    personTest.setName("Butters");
    personTest.setAge(10);

    ProjectEntity projectTest = new ProjectEntity();
    projectTest.setName("Hanks");
    projectTest.setBudget(10000);

    ProjectEntity projectTest2 = new ProjectEntity();
    projectTest2.setName("X");
    projectTest2.setBudget(100);

    personTest.addToProjects(projectTest);
    personTest.addToProjects(projectTest2);

    em.persist(personTest);

    em.getTransaction().commit();
    em.close();

Hope it helps! Thank you so much.

4
  • 1
    Save the PersonEntity first, then add the saved entity to ProjectEntity and after that save the ProjectEntity. Project requires Person before persist.
    – Pallav Jha
    Mar 29, 2018 at 11:12
  • "I've searched for every related question to my problem to try to find a solution, however, none of the proposed solutions are working for me ..." I think you are doing this the wrong way. I would advise to read the related Q&A to gain insight into / understanding of problems like yours. Then use that knowledge to solve your particular.
    – Stephen C
    Mar 29, 2018 at 11:23
  • @ObiWan-PallavJha Thank you for your suggestion! Unfortunately, it doesn't seem to work :/. I added em.persist(personTest); before project.setPersonId(personTest) and then: em.persist(projectTest). Did I make any mistake? Mar 29, 2018 at 11:35
  • @StephenC You are 101% right, I didn't explain myself properly. It's not like I'm just looking for the solutions and trying to apply them just for the sake of it. I have read a lot of Q&A trying to understand what I'm doing wrong, I have seen tutorials, read the documentation, etc. Still, I can't make it work, I'm kinda desperate and that's why I'm trying anything right now. Thank you so much for your advice. Mar 29, 2018 at 11:49

3 Answers 3

0

The main thing that you will want to watch out for is to define the owning side of the relation correctly. As far as I remember, my takeaway from the (sometimes difficult to understand) official documentation was that the owning side is pretty much the one that will by default trigger cascades and transparent deletions.

For example, in the above, you have defined the owning side as ProjectEntity, so the most important step for cascaded persistence to work is to add the project to PersonEntity.projects.

You will then want to call persist on the owning side of the relation, i.e.

em.persist(projectTest);

If this doesn't help, I would suggest that you enable SQL logging in your JPA provider to find out what statements it is trying to execute, and especially in what order these entities are being inserted.

Also try, as per existing comments, to persist person first. If you do this, I believe the correct way is to add the persisted entity to the relationship, i.e:

PersonEntity persistedPerson = em.persist(personTest);
projectTest.setPersonId(persistedPerson);
em.persist(projectTest);
3
  • I tried em.persist(projectTest); after adding the project to the PersonEntity, however, it only inserts the project and with personid = null. But, if I do this: personTest.getProjects().add(projectTest); em.persist(personTest); Both of them get inserted into the database! Unfortunately, the project is still with personid = null; but I'm getting close haha. em.persist returns void. I also thought that it would return the persisted entity but I was wrong :). Thank you so much! Mar 29, 2018 at 15:24
  • I had a thought - have you tried manually assigning the ID field? Otherwise maybe adding @Generated will help. However, I would have expected a primary key constraint failure unless there isn't a PK defined on the database itself... Mar 30, 2018 at 13:11
  • Thank you so much for your suggestion! I tried assigning the ID field manually and it didn't work. Then I tried adding again the @GeneratedValue(strategy=GenerationType.AUTO) I removed this before because it wasn't working, however, it wasn't working because I was missing this property on the persistence.xml:<property name="hibernate.id.new_generator_mappings" value="false" />. I can now insert Parent objects with its Children and they have the parentid correctly set :)! Thank you so much, I don't know if I would have figured it out without your help! Mar 30, 2018 at 19:10
0

A couple of leads I can think of, because I crossed more than once this kind of problems:

Unless you want a cascade operation from Project to update your Person, you should remove @ManyToOne(cascade = CascadeType.ALL) from your personid attribute

Try updating your projects collection instead of creating a new one, because if it's already managed by Hibernate (which doesn't need to be , the persist/merge operation will be executed on the old one and the new one.

Person Class:

private List<ProjectEntity> projects = new ArrayList<>();

your code :

 personTest.getProjects().addAll(projects);

I usually prefer merge instead of persist, because I find it more 'natural', and sometimes, the output is clearly not the same.

3
  • I just changed the cascade type to PERSIST, better than ALL. I couldn't add a project to the 'original' list because it wasn't initialized. private List<ProjectEntity> projects = new ArrayList<>(); This solved the problem, I don't know why I didn't think of initializing the variable there. Merge gives me the same result(in this case). Now I have this: personTest.getProjects().add(projectTest); em.persist(personTest); This inserts the Person and the Project but with personid = null. Progress! Thank you so much you have helped me a lot! Mar 29, 2018 at 15:15
  • I'm confused: are you saying that your personid object is null, or the associated row in database is? And is it null when you insert it or after a get query?
    – HBo
    Mar 30, 2018 at 6:49
  • I'm sorry, I'm really bad at explaining things. The associated row in the database was null when I did the insert :). But it doesn't matter, I finally made it work! I can finally persist the Parent object and its Children! I was missing the @GeneratedValue(strategy=GenerationType.AUTO) annotation which I removed because it didn't work, but it didn't work because it needed this property on the persistence.xml:<property name="hibernate.id.new_generator_mappings" value="false" /> Thank you so much for your help! You really helped me! Mar 30, 2018 at 19:02
0

I had the same problem. A @ManyToOne that was not working for no reason and 2 classes. I added @GeneratedValue(strategy=GenerationType.AUTO), but it didn't fix my problem.

I also tried to rename the classes, clean, close project, restart, etc., but none worked. At the end, I deleted the files (made a copy before) and recreated them from new and that fixed my problem. I was on Eclipse 4.8, Spring 2.5, Groovy 2.5, Java 1.8

UPDATE: Not really sure what was the problem, anyway (for groovy) check your save method: myUserRepo(new MyUser("username")), check as well your xxxxRepo< MyUser, Integer> and also check that your file is .groovy (last one shouldn't be a problem)

Other UPDATE: If you're creating a relational between 2 tables and use the save result, be sure to use @Transactional on a Service and link the relation field, for example:

@Transactional
UserAccount save(UserAccount userAccount) {
    User user = userRepo.save(new User(userAccount))
    UserAccount.setUser(user)
    userAccountRepo.save(userAccount)
}
1
  • Also i used CrudRepo, anyway all classes that where in relation, deleted and recreated
    – rweiller
    Jun 23, 2019 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.