janusz j
janusz j

Reputation: 329

JPA repository table is not saving new id's but overriding or modifing

I have A.class:

@Entity
@Data
public class A {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    Integer id;

    String someStringInAclass;

    @OneToMany(cascade = CascadeType.ALL)
    List<SomeObject> someObjectsList;
}

I have SomeObject.class:

@Entity
@Data
public class SomeObject {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    Integer id;
    String someString;
    Integer someInteger;
}

I save A object in database:

SomeRepository.save(A);

And tables look like this:

enter image description here

Then I save A object again with different values in B object:

SomeRepository.save(A);

Then tables look like this:

enter image description here

Table B has extended correctly, but table A_B just overrode the B_id instead putting the new one 4 rows.

Then when I retrieve the object A from database I obtain only last 4 values from B object.

How to make it work with saving new values (adding new rows to A_B) without overriding?

EDIT:

I added A_id as a foreign key to B table. Again - first save is stored properly:

enter image description here

Then after second save with different values for B, it modifies values for A_id column for firstable inserted 4 values (to null). So the table looks like this:

enter image description here

Upvotes: 0

Views: 1307

Answers (3)

janusz j
janusz j

Reputation: 329

I added: (nullable = false) parameter for @JoinColumn the problem is solved.

So above the list there is now:

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(nullable = false)
List<SomeObject> someObjectsList;

Upvotes: 0

Datta Diware
Datta Diware

Reputation: 602

Hibernate handle unidirectional relationships very inefficiently please try to use bidirectional relationship.

Regarding above issue, you don't need third table here, you can avoid creation of third table by adding @JoinColumn as below :

     @OneToMany(cascade = CascadeType.ALL)   
     @JoinColumn(name = "fk_a_id")
     List<SomeObject> someObjectsList;

this will add column "fk_a_id" in SOME_OBJECT table.

Upvotes: 1

Ralph L&#246;we
Ralph L&#246;we

Reputation: 424

Since the object is already saved and has an assigned id, JPA assumes you mean the same entry in the database. You need to clone the object:

@Entity
@Data
public class A {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    Integer id;

    String someStringInAclass;

    @OneToMany(cascade = CascadeType.ALL)
    List<SomeObject> someObjectsList;

    public A(A source) {
        this.someStringInAclass = source.someStringInAClass;
        this.someObjectsList = new ArrayList<SomeObject>();

        for (SomeObject o : source.someObjectsList) {
            this.someObjectsList.add(new SomeObject(o));
        }
    }
}

Use it as follows:

SomeRepository.save(a);
A aClone = new A(a);
SomeRepository.save(aClone);

Upvotes: 0

Related Questions