【发布时间】:2022-01-17 16:09:56
【问题描述】:
非常简单的情况,JPA 正在杀死我的脑细胞
@Entity
@Table(name = "food_entry")
@ublic class FoodEntry implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "product_name", nullable = false, unique = false, insertable = true, updatable = false, length = 256)
private String name;
@CreatedDate
@Column(name = "instant", updatable = false, unique = false, nullable = false, insertable = true)
private Instant instant = Instant.now();
@Min(value = 0, message = "calories must be positive")
@Column(name = "calories", updatable = false, insertable = true, nullable = false, unique = false)
private long calories;
}
@Transactional
public FoodEntry update(final FoodEntry newEntry, long id) {
final User loggedUser = SecurityUtils.getCurrentLoggedUser();
if (loggedUser == null || !loggedUser.getAuthorities().contains(Authority.ADMIN))
throw new AccessDeniedException("You dont have authorization to perform this action");
FoodEntry current = this.repository.findById(id).orElseThrow(() -> new NotFoundException("Not found FoodEntry with specified id: " + id));
current.setCalories(newEntry.getCalories());
current.setInstant(newEntry.getInstant());
current.setName(newEntry.getName());
try {
this.repository.save(current);
this.repository.flush();
return null;
}
catch (Exception e) {
throw e;
}
}
@Repository
public interface FoodRepository extends JpaRepository<FoodEntry, Long> {}
代码运行,从数据库中查询食物条目,但是当我调用保存时,什么都没有发生, JPA 简单返回与我作为参数传递的完全相同的对象,并且没有在数据库上运行查询...稍后获取该实体将返回过时的值
为什么?这么简单我错过了什么?
相同的 CREATE 代码可以正常工作...但是当我尝试更新时,save 方法什么也不做
【问题讨论】:
-
请同时添加所有调用
update方法的相关代码
标签: spring-boot jpa spring-data-jpa