我使用带弹簧启动的hibernate和PostgreSQL作为数据库。当我在平板电脑中保存实体时,与hibernate返回相比,保存的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
}
重建接口
@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不一样了。这是什么原因?
答案 0 :(得分:0)
如果你在postgreSQL中使用“serial”作为genration类型,那么在我们使用JPA时应该遵循一些限制。有关限制,请参阅here。
注意:强> 身份排序要求在分配id之前进行插入,因此不像其他类型的排序那样在持久化上分配。您必须在当前事务上调用commit(),或者在EntityManager上调用flush()。也可能是您没有将表中的主键列设置为标识类型。