I'm using hibernate-types-52 by Vlad Mihalcea together with Spring JPA to insert a POJO as a Json value into my Postgresql database.
My entity is defined this way:
@Entity
@Table(name = "hoshin_kanri")
@TypeDef(
name = "jsonb",
typeClass = JsonBinaryType.class
)
public class HKEntity {
@Id
@Column(name = "id_ai", columnDefinition = "bigint")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id_ai;
@Column(name = "id_hk", columnDefinition = "bigint")
private Integer id_hk;
@Type(type = "jsonb")
@Column(name = "hk_data", columnDefinition = "jsonb")
private HKData hk_data;
public HKEntity(Integer id_hk, HKData hk_data) {
this.id_hk = id_hk;
this.hk_data = hk_data;
}
And this is the POJO:
public class HKData {
private String name;
private Year targetYear;
private String description;
public HKData(String name, Year targetYear, String description) {
this.name = name;
this.targetYear = targetYear;
this.description = description;
}
I've defined a Repository interface to query the objects into the database:
public interface HKRepository extends CrudRepository<HKEntity, Integer> {
@Query(value = "INSERT INTO 'hk_data' VALUES :Entity", nativeQuery = true)
void test_json(@Param("Entity") HKEntity e);
}
and a test Service just to see if it's working properly:
@Service
public class HKService {
@Autowired
HKRepository hk_repository;
public String json_test() {
HKData d = new HKData("Prova", Year.now(), "Descrizione");
HKEntity e = new HKEntity(1,d);
hk_repository.test_json(e);
return "Value created";
}
}
However, i keep getting the following exception:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.ehk.rest.entity.HKEntity
I've tried many fixes suggested for this error, but i cannot understand the nature of the error itself. What is wrong with this approach? Beside a tip for fixing this, i would like to understand why this error is originated.