错误-对象引用了未保存的瞬态实例

时间:2019-05-12 11:01:23

标签: java hibernate

我正在尝试保留以下两个实体PersonCompany
当我有CascadeType.PERSIST时遇到以下错误。但是,当我将其更改为CascadeType.ALL时,错误消失了。 CascadeType.PERSIST是否应达到目的?

我在many-to-onePerson之间有Company关系

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

编辑:

人员

@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;
    }

公司

@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 个答案:

没有答案