简体   繁体   中英

Save Nested POJO class Objects using hibernate

Class1:

int field2
Class2 field1

Class2:

Class3 field3

Class3:

String field4
String field5

Class1 domain class:

@Table(name = "class1_details")
@Entity
public class Class1Details {
  @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Column(name = "class2_fields")
    private Class2 fields;

     // respective getters and setters

}

I am using springboot. I am extending JPARepository for my repo interface. I want to save class1 in db. I am getting below exception:

org.springframework.orm.jpa.JpaSystemException: could not serialize; nested exception is org.hibernate.type.SerializationException: could not serialize ...

Caused by: org.hibernate.type.SerializationException: could not serialize ....

Caused by: java.io.NotSerializableException: com.model.Class3 ...

Tried @ElementCollection but of no use. Please help with this.

You should make nested classes @Embeddable :

@Entity
@Table(name = "my_entities")
public class MyEntity {
    //...

    private MyData data;
}

@Embeddable
public class MyData {
    private String value;
}

Then Hibernate will deal with the following table:

create table my_entities (
  -- MyEntity stuff
  --
  value varchar(255)
);

Another an interesting approach is storing nested class in DB as JSON , see my related answer ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM