【问题标题】:After save my data, one object return from memory not fetching from database,保存我的数据后,一个对象从内存中返回,而不是从数据库中获取,
【发布时间】:2020-07-14 14:12:35
【问题描述】:

我正在为我的数据库使用 Spring JPA。更新数据库中的数据后,从数据库中获取所有数据,但我已更新该记录的一条记录从内存返回。

控制器

@RestController
@Slf4j
public class DepartmentController {
@PutMapping("${service.deptupdate.url}")
    @ApiOperation(value = "Update existing department by deptId and clientId", response = Boolean.class)
    public ResponseEntity<List<DepartmentDTO>> updateDept(@RequestBody DepartmentDTO deptDTO)
            throws DepartmentException {
        log.info("DepartmentController : updateDept: saving the department {} for {} client", deptDTO.getDeptId(),
                deptDTO.getClientId());
        deptDTO = departmentService.saveOrUpdateDept(deptDTO);
        log.info("DepartmentController : updateDept: Successfully updated department {} for clinet{}",
                deptDTO.getDeptId(), deptDTO.getClientId()); 

        return new ResponseEntity<List<DepartmentDTO>>(departmentService.findAllDepartment(deptDTO.getClientId()),
                HttpStatus.OK);
    }

}

服务

@Slf4j
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Override
    public DepartmentDTO saveOrUpdateDept(DepartmentDTO deptDTO) {
        log.info("Saving department for clientId{}", deptDTO.getClinicId());
        Department dept = DepartmentUtils.deptDetailsDTOTOEntity(deptDTO);
        dept = departmentRepository.saveAndFlush(dept);
        DepartmentDTO departmentDTO = DepartmentUtils.deptDetailsEntityTODTO(dept);
        if(null != departmentDTO.getDeptId())
        log.info("Successfully save/update department {} for client{}", departmentDTO.getDeptId()+":"+departmentDTO.getDeptName(), departmentDTO.getClientId());
        return departmentDTO;
    }

@Override
    public List<DepartmentDTO> findAllDepartment(Long clientId) {
        log.info("Getting all department list for clientId{}", clientId);
        List<Department> deptList = departmentRepository.findByClientId(clientId);
        List<DepartmentDTO> deptDTOList = DepartmentUtils.deptDetailsEntityTODTOList(deptList);
        log.info("Found {} department list for clientId{}", deptDTOList.size(), clientId);
        return deptDTOList;
    }
}

存储库

@Repository
public interface DepartmentRepository extends JpaRepository<Department, Long>{
          public List<Department> findByClientId(@Param("cliId")Long clientId);
}

实体

@Data
@Entity
@Table(name = "DEPARTMENT")
@DynamicUpdate(true)
@DynamicInsert(true)
@EqualsAndHashCode
public class Department implements Serializable{


    @Id
    @Column(name = "DEPT_ID", updatable=false, nullable=false)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long deptId;

    @Column(name = "CLIENT_ID", nullable = false, updatable = false)
    private Long clientId;

    @Column(name = "DEPT_NAME")
    private String deptName;

    @Column(name = "DEPT_CODE")
    private String deptCode;

    @Column(name = "STATUS")
    private Boolean status;

    @Column(name = "CREATED_BY", nullable = false, updatable = false)
    private String createdBy;

    @CreationTimestamp
    @Column(name = "CREATED_TIME", nullable = false, updatable = false)
    private LocalDateTime createdTime;

    @Column(name = "UPDATED_BY")
    private String updatedBy;

    @UpdateTimestamp
    @Column(name = "UPDATED_TIME", nullable = false)
    private LocalDateTime updatedTime;

}

下面是我在yml文件中的数据库配置

# Database Configuration    
spring:
   application:
      name: eclinic-queue-management
   profile:
      active: local   
   datasource:
      url: jdbc:mysql://localhost:3306/client?useSSL=false&serverTimezone=UTC
      username: root
      password: *****
      driver.class: com.mysql.cj.jdbc.Driver
   jpa:
      show-sql: true
      database-platform: org.hibernate.dialect.MySQL5Dialect
      hibernate.format_sql: true
      hibernate.ddl-auto: none  

通过 RESTAPI 更新以下数据 - 请求

{
    "deptId": 1,
    "clientId" : 2,
    "deptName" : "General",
    "deptCode" : "GGG",
    "status": true,
    "createdBy": "GULAB",
    "updatedBy": "GULAB"
}

来自数据库的响应返回

[
    {
        "deptId": 1,
        "clinicId": 2,
        "deptName": "General",
        "deptCode": "GGG",
        "deptDoctorId": "6",
        "tokenStartWith": "GGG",
        "status": true,
        "createdBy": "GULAB", // <-- this is not the value from the database
        "createdTime": null,  // <-- this is not the value from the database

        "updatedBy": "GULAB",
        "updatedTime": "2020-04-02T22:21:11.352"
    },
    {
        "deptId": 2,
        "clinicId": 2,
        "deptName": "General",
        "deptCode": "GEN",
        "deptDoctorId": "3",
        "tokenStartWith": "G",
        "status": true,
        "createdBy": "Jayesh",
        "createdTime": "2020-03-27T12:42:50.076",
        "updatedBy": "Jayesh",
        "updatedTime": "2020-03-27T12:42:50.077"
    }
]

但在数据库中createdBy 的值是JayeshcreatedTime 不是null

我不明白问题出在哪里。

【问题讨论】:

  • 我格式化并稍微编辑了您的问题。请确保我没有改变意思。

标签: hibernate spring-boot spring-data-jpa spring-data hibernate-mapping


【解决方案1】:

您将createdBycreatedTime 都映射到updatable = false,因此它们不会在数据库中更新。

另一方面,实体存储在EntityManager 中,因此它们不会被 JPA 重新加载,因为 JPA 保证具有给定类和 id 的实体在会话中只能存在一次。

如果您想从数据库中重新加载实体,请将它们从会话中逐出或使用新的EntityManger,即在新事务中执行它

【讨论】:

  • 感谢 Jens 的快速回复。我能理解的第一个,它不会更新,但必须从数据库中获取新值。如何调用新鲜EnitryManager。我在下面试过但没有用。 @Transactional public List&lt;Department&gt; findByClientId(@Param("cliId")Long clientId);
  • 再次感谢 Jens,仍然遇到同样的问题。 ` @Override @Transactional @Modifying(clearAutomatically = true) public DepartmentDTO saveOrUpdateDept(DepartmentDTO deptDTO) { } ` 还添加到邮件类 ` @SpringBootApplication @EnableEurekaClient @EnableConfigurationProperties @EnableTransactionManagement @Configuration public class MainApplication { } `
猜你喜欢
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多