Hibernate保存对象(一对多关系)外键为空 [英] Hibernate save object (one to many relationship) foreign key is null

查看:238
本文介绍了Hibernate保存对象(一对多关系)外键为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在班级和汽车班之间有一对多的关系。一个人可以拥有许多汽车,反之亦然。我使用restful API发布数据。我的注释和获取服务工作正常但我的帖子服务抛出java.sql.SQLIntegrityConstraintViolationException:ORA-01400:无法插入NULL错误,每当我尝试插入新数据。子表外键正在插入为null。

I have one to many relationship between person class and car class. A person can own many cars and vice versa. I am using restful API to post data. My annotations and Get service is working fine but my post service throws " java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL" error whenever I try to insert new data. Child table foreign key is being inserted as null.

这是我的代码的一部分。

Here is part of my code.

Person.java

Person.java

 private List<Car> cars = new ArrayList<Car>();

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="person")    
@JsonManagedReference
public List<Car> getCars() {
  return cars;
 }

Car.java

private Person person;  

    @ManyToOne
    @JoinColumn(name = "PERSON_ID", nullable = false, updatable = true, insertable = true)
    @JsonBackReference
    public Person getPerson() {
        return person;
    }

我的服务类:

@POST
        @Path("/PersonRegistration")
        @Consumes(MediaType.APPLICATION_JSON)
        public Response postPersonCars(Person person) throws Exception{

            Session session = null;     
            ObjectMapper mapper = new ObjectMapper();   
            //Person per = new Person();
            //Car cars = new Car();
            try{
                session = HibernateUtil.getSessionFactory().openSession();
                session.beginTransaction(); 
                //per.setCars(person.getCars());
                session.save(person);
                session.getTransaction().commit();

            }catch(Exception e){
                e.printStackTrace();
                throw e;
            }finally{
                if(null != session){
                    session.close();
                }
            }

            return Response.status(201).entity(mapper.writeValueAsString(person)).build();
        }


推荐答案

此注释:

@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="person")

有两个后果:


  1. mappedBy 暗示 Car 是关系的拥有方。这意味着每当你想在 Car Person 之间建立关系,你需要通过将 Car.person 属性设置为适当的值。 Hibernate将忽略对 Person.cars 的更改。

  2. cascade = CascadeType.ALL 表示无论何时保存 Person , Hibernate还将对 Person.cars

  1. mappedBy implies that Car is the owning side of the relationship. This means that whenever you want to establish a relationship between Car and Person, you need to do it by setting the Car.person property to the appropriate value. Changes to Person.cars will be ignored by Hibernate.
  2. cascade=CascadeType.ALL means that whenever you save a Person, Hibernate will also invoke the save operation on all entities contained in Person.cars



结果:您在一堆没有<$的 Car 实体上调用 Session.save() c $ c> Car.person 属性设置正确。

Result: you are calling Session.save() on a bunch of Car entities that do not have the Car.person property set properly.

解决方案:要么改变关系的拥有方(要知道你还需要一个 @JoinColumn Person.cars 如果您不想创建额外的数据库表)或循环 Person.cars 并设置每个人都正确地使用 Car.person 属性。

Solution: either change the owning side of the relationship (be aware that you will also need a @JoinColumn on Person.cars if you do not want an extra database table to be created) or loop through Person.cars and set the Car.person property properly in each of them.

cascade = CascadeType.ALL 建议第一个解决方案更适合您的用例。

cascade=CascadeType.ALL suggests the first solution fits your use case better.

这篇关于Hibernate保存对象(一对多关系)外键为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆