The project stopped running (started using Spring Boot) after I added JpaRepository with an error:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: ru.cadmy.finance.model.User 

There are two entities.

User:

 @Entity @Builder @NoArgsConstructor @AllArgsConstructor @Table(name = "USER") public @Data class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "username", unique = true, nullable = false, length = 500) private String username; @Column(name = "password", nullable = false, length = 500) private String password; } 

And a balance sheet:

 @Entity @Builder @NoArgsConstructor @AllArgsConstructor @Table(name = "BALANCE") public @Data class BalanceRecord { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne(cascade = {CascadeType.ALL}) @JoinColumn(name = "user") private User user; @Column(name = "date") @DateTimeFormat(pattern = "yyyy-MM-dd") @Type(type = "date") private Date date; @Column(name = "value", nullable = false) private Integer value; @Column(name = "title", nullable = true, length = 500) private String title; } 

The project started without errors until I added the JpaRepository for the balance line:

 @Repository @Transactional public interface BalanceRecordRepository extends JpaRepository<BalanceRecord, Long> { @Query("from BalanceRecord b where b.user = :user and b.date >= :dateFrom and b.date < :dateTo") List<BalanceRecord> getBalanceRecordsForPeriod(@Param("user") User user, @Param("dateFrom") Date dateFrom, @Param("dateTo") Date dateTo); } 

What is the problem?

  • What do you have in the database? - barmaglott

1 answer 1

This error occurs due to CascadeType.ALL - now it’s likely that you will try to save a BalanceRecord with a link to a user who does not have an ID . Install CascadeType.NONE .