【发布时间】:2019-10-12 19:31:39
【问题描述】:
我有一个使用 spring boot 和 spring data jpa 的服务器。
我的服务器中有两个用@RestController 注释的类。其中一个可能会更改实体,而另一个不会。
@RestController
@Slf4j
public class ControllerA {
private EntityRepository entityRepository;
public ControllerA(EntityRepository entityRepository) {
this.entityRepository = entityRepository;
}
@PostMapping("/pathStr")
public void changeEntity(@RequestParam("entityId") Long entityId) {
// init
Entity entity = entityRepository.findById(entityId);
// make changes to entity
entity.getOneToOneLinkedEntity().setIntProperty(0);
// save entity
entityRepository.save(entity);
}
}
@RestController
@Slf4j
public class ControllerB {
private Entity cachedEntity;
private EntityRepository entityRepository;
public ControllerB(EntityRepository entityRepository) {
this.entityRepository = entityRepository;
}
@MessageMapping("/otherPath")
public void getEntity(ArgumentType argument) {
if (cachedEntity == null) {
cachedEntity = entityRepository.save(new Entity());
}
Entity entity = entityRepository.findById(cachedEntity.getId()).orElse(null);
int properyValue = entity.getOneToOneLinkedEntity().getIntProperty(); // this is not zero
}
}
这是两个实体和存储库:
@Entity
public class Entity implements Serializable {
@Id
@GeneratedValue private Long id;
@NotNull
@OneToOne(cascade=CascadeType.ALL)
private OneToOneLinkedEntity linkedEntity;
}
@Entity
public class OneToOneLinkedEntity implements Serializable {
@Id
@GeneratedValue private Long id;
@NotNull
private int intProperty = 0;
}
public interface EntityRepository extends JpaRepository<Entity, Long> {
}
我从客户端调用 ControllerA.changeEntity,一旦返回,我再调用 ControllerB.getEntity。我在第一次调用中所做的更改未显示在第二次调用中,(如果我直接使用 sql 查询,它们也不在数据库中)int 属性具有旧值。即使我只在实体上而不是在linkedEntity上进行保存,CascadeType.ALL 也应该使链接实体更新,对吧?
我尝试在 ControllerA 中保存后添加entityRepository.flush(),但问题仍然存在。我能做些什么?如何让 ControllerB 获得正确的 intProperty 值?
这就是我在 application.properties 中的内容:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=user
spring.datasource.password=pass
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.DefaultComponentSafeNamingStrategy
【问题讨论】:
-
带有级联的 OneToOne 注释应该足以完成这项工作。您能解释一下“cachedEntity”值的来源吗?
-
@Raphael 它是在第一次调用 ControllerB.getEntity() 时创建的。类似于:if (cachedEntity == null) {cachedEntity = entityRepository.save(new Entity());}。我将代码添加到问题中
标签: java spring-boot jpa spring-data-jpa spring-repositories