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

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

问题描述

我在person类和car类之间有一对多的关系.一个人可以拥有多辆汽车,反之亦然.我正在使用restful API 来发布数据.我的注释和获取服务工作正常,但我的后期服务在我尝试插入新数据时抛出java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL"错误.子表 foreign key 被插入为 null.

I have one to many relationships 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;
 }

汽车.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 是关系的拥有方.这意味着每当你想在 CarPerson 之间建立关系时,你需要通过设置 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.person 属性集的 Car 实体上调用 Session.save()适当地.

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

解决方案:要么更改关系的拥有方(请注意,如果您不想要额外的数据库,则在 Person.cars 上还需要一个 @JoinColumn要创建的表)或循环遍历 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天全站免登陆