I using hibernate with spring boot and PostgreSQL as database. When I am saving an entity in tablethe saved id is different as compare to return by hibernate.
I created table with following query:
Create table notification_Instances(
notification_id serial primary key,
notification_text text,
target_type text,
target text,
notification_status text,
created_at text,
updated_at text,
retries text,
subject text
)
my table entity class is:
@Entity
@Table(name="notification_instances")
public class NotificationInstance implements Serializable {
private static final long serialVersionUID = 2825168659954221851L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="notification_id")
long notificationId;
@Column(name="notification_text")
String notificationText;
@Column(name="target_type")
String targetType;
@Column(name="target")
String target;
@Column(name="notification_status")
String status;
@Column(name="created_at")
String createdAt;
@Column(name="updated_at")
String updatedAt;
@Column(name="retries")
int retries;
@Column(name="subject")
String subject;
//getters and setters excluded
}
Repositry interface
@org.springframework.stereotype.Repository
public interface NotificationInstanceRepo extends JpaRepository<NotificationInstance, Long>
{
@Query("Select n.status from NotificationInstance n where n.notificationId= :id")
String getStatusById(@Param("id") long id);
@Modifying
@Transactional
@Query("UPDATE NotificationInstance SET status= :updatedStatus, retries= :totalRetries, updatedAt= :updatedOn WHERE notificationId= :id")
public void updateStatus(@Param("id") long id, @Param("updatedStatus") String updatedStatus, @Param("totalRetries") int totalRetries, @Param("updatedOn") String updatedOn);
}
and following is the code which saves entity into
NotificationInstance notificationInstance = new NotificationInstance();
notificationInstance.setNotificationText("Test body");
notificationInstance.setTargetType("Some channel"); notificationInstance.setStatus("Queued");
notificationInstance.setTarget("target");
notificationInstance.setTargetType("");
notificationInstance.setCreatedAt(dateFormat.format(date)); notificationInstance.setSubject("Test subject");
notificationInstance.setRetries(0);
logger.info("Saving the notification to database.");
notificationInstanceRepo.save(notificationInstance);
System.out.println(notificationInstance.getNotificationId());
Now when I seed into db the id is not the same. What is the reason for this?