I am trying to persist the below 2 entities Person and Company
and getting the below error when I have CascadeType.PERSIST in Person. However when I change it to CascadeType.ALL the error disappears. Shouldn't the CascadeType.PERSIST serve the purpose?

I have many-to-one relationship between Person and Company

Person p1= new Person("GuyOne");
Company c1 = new Company("Amazon");
p1.setcompany(c1);
session.save(p1);

EDIT:

Person

@Entity

public class Person {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    int id;


    String name;

    @ManyToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="company_id")
    Company company;

    public Person()
    {}

    public Person(String name) {
        super();
        this.name = name;

    }




    public int getId() {
        return id;
    }


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


    public String getName() {
        return name;
    }


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


    public Company getcompany() {
        return company;
    }


    public void setcompany(Company c) {
        this.company = c;
    }

Company

@Entity
public class Company {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    int id;

    String name;

    @OneToMany(mappedBy="company")
    List<Person> persons= new ArrayList<Person>();

public Company()
    {}


    public Company(String name) {
        super();
        this.name = name;
    }

    public List<Person> getPersons() {
        return persons;
    }

    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }



    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

0 Answers