dev*_*150 5 java jpa spring-data-jpa spring-boot spring-repositories
我有一个使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)
这是两个实体和存储库:
@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> {
}
Run Code Online (Sandbox Code Playgroud)
我从客户端调用 ControllerA.changeEntity,一旦返回,我再次调用 ControllerB.getEntity。我在第一次调用中所做的更改不会在第二次调用中显示(如果我直接使用 sql 查询,它们也不在数据库中) int 属性具有旧值。即使我只在实体上而不是在链接实体上进行保存,也CascadeType.ALL应该使链接实体也更新,对吗?
我尝试entityRepository.flush()在ControllerA中保存后添加一个,但问题仍然出现。我能做些什么?如何让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
Run Code Online (Sandbox Code Playgroud)
    您应该@Transactional向您的方法添加注释,以便 spring 将处理事务并提交您的更改。
这通常出现在@Service类上,但我在你的示例中看到你没有,所以将它放在控制器上(或添加服务层,我认为更好)
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           32298 次  |  
        
|   最近记录:  |