-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: One to many mapping and database constraints
PostPosted: Tue Dec 02, 2008 2:27 am 
Newbie

Joined: Tue Dec 02, 2008 1:38 am
Posts: 1
I am using Hibernate 3.2.6 with the entities configured using annotations. DB is PostgreSQL.

I want to persist an object which has a collection associated with it. The collection should also be persisted when the parent object is persisted.

Say the parent object is foo and the collection objects are bar, the table structure is as below

Foo table:

CREATE SEQUENCE foo_id_seq;

CREATE TABLE foo
(
id integer primary key default nextval('foo_id_seq'),
<other fields>
)

Bar table:

CREATE SEQUENCE bar_id_seq;

CREATE TABLE bar
(
id integer primary key default nextval('bar_seq'),
foo_id integer,
<other fields>,
CONSTRAINT bar_has_foo_id FOREIGN KEY (foo_id)
REFERENCES foo (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)

The entity mapping:

Foo:

@Entity(name = "foo")
public class Foo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "foo_id")
@OrderBy("id")
private List<Bar> barList;
<getters and setters>
}

Bar:

@Entity(name = "bar")
public class Bar {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(targetEntity = Foo.class)
@JoinColumn(name = "foo_id")
private Foo foo;
<getters and setters>
}

Now when I try to store a Foo object with associated Bar objects I want the Foo as well as Bar objects to be saved. The code for this would be as below:

Foo foo = new Foo();
Bar bar0 = new Bar();
Bar bar1 = new Bar();
List<Bar> barList = new ArrayList<Bar>();
barList.add(bar0);
barList.add(bar1);
foo.setBarList(barList);
<persist foo>

This works fine. Both my Foo as well as Bar objects get saved.

Now if I add a constraint to the Bar table that foo_id foreign key is not null i.e
foo_id integer not null, then the above code ceases to work and I get an exception saying

2140 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: null value in column "foo_id" violates not-null constraint

org.springframework.dao.DataIntegrityViolationException: could not insert: [Bar]; nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [Bar]


I can guess as to what is happening. When I try to store a foo object with associated bar objects then the bar table is populated first with foo_id as null. Then the foo table is populated. Now the foo_id column of bar table is updated with the stored foo id. But when I add a not null constraint the above sequence of events causes a DB error.

My question is how do I maintain my not null constraint and also save the foo object and it's associated bar object collection in one go?


Top
 Profile  
 
 Post subject:
PostPosted: Tue Dec 02, 2008 3:45 am 
Beginner
Beginner

Joined: Wed Nov 19, 2008 8:25 am
Posts: 46
Location: Saint Petersburg, Russian Federation
You didn't provide Foo.setBarList() implementation but I believe that you just have a one like

Code:
    public void setBarList(List<Bar> barList) {
        this.barList = barList;
    }


I.e. 'Bar.foo' property is uninitialized.

The proper way to implement the method is below:
Code:
    public void setBarList(List<Bar> barList) {
        this.barList = barList;
        for (Bar bar : barList) {
            bar.setFoo(this);
        }
    }


Also you should specify one end of your bidirectional association as inverse and add not-null constraint. I.e. the mappings look as follows:

Code:
@Entity(name = "foo")
public class Foo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
   
    @OneToMany(mappedBy = "foo", cascade = CascadeType.ALL)
    @JoinColumn(name = "foo_id", nullable = false)
    @OrderBy("id")
    private List<Bar> barList;

    public void setBarList(List<Bar> barList) {
        this.barList = barList;
        for (Bar bar : barList) {
            bar.setFoo(this);
        }
    }

    public List<Bar> getBarList() {
        return barList;
    }
}


Code:
@Entity(name = "bar")
public class Bar {
   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(targetEntity = Foo.class)
    @JoinColumn(name = "foo_id")
    private Foo foo;

    public Foo getFoo() {
        return foo;
    }

    public void setFoo(Foo foo) {
        this.foo = foo;
    }
}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.