0
我使用hibernate與spring引導和postgerSQL作爲分貝。當我在tablet中保存一個實體時,保存的id與通過休眠返回相比是不同的。由hibernate Id返回不同於保存在postgerSQL表中的ID
我創建表以下查詢:
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
)
我的表實體類是:
@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接口
@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);
}
和下面是節省了實體到
代碼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());
現在當我種入db時,id不一樣。這是什麼原因?
請告訴我們關於notificationInstance的更多信息。它是一個新的,你想創建它,或者它是一個現有的,你想更新它?在調用save(notificationInstance)之前它是通知Id? –
@LukasRisko我更新了問題。是的,我正在嘗試創建一個新的。 –
我想你應該閱讀http://stackoverflow.com/questions/8625150/why-to-use-returned-instance-after-save-on-spring-data-jpa-repository。它會向您解釋爲什麼以及何時使用保存方法的返回對象而不是傳入的對象。 –