当前位置: 首页 > 知识库问答 >
问题:

使用SPRING DATA JPA在保存/更新期间刷新实体

申浩广
2023-03-14

我在Spring Boot中使用Spring Data JPA。

在使用Spring Data Jpa存储库将一个实体保存到数据库后,我不会得到整个实体。即只获取我传递给save()的值。

@Entity
@Table(name = "enterprise")
public class Enterprise extends BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "enterprise_id")
    private Long enterpriseId;
    @Column(name = "enterprise_external_name", length = 150, unique = true)
    @NotNull
    private String enterpriseExternalName;
    @Column(name = "enterprise_internal_name", length = 150, unique = true)
    @NotNull
    private String enterpriseInternalName;
    @OneToMany(mappedBy = "enterprise")
    @JsonIgnoreProperties(allowSetters = true, value = { "enterprise" })
    private Set<Organization> organizations;
    //getter and setters
}

组织实体:

@Entity
@Table(name = "organization")
public class Organization extends BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "organization_id")
    private Long organizationId;
    @Column(name = "organization_name", length = 150, unique = true)
    @NotBlank(message = "OrganizationName can't be empty !")
    private String organizationName;
    @ManyToOne
    @JoinTable(name = "enterprise_organization", joinColumns = {
            @JoinColumn(name = "organization_id") }, inverseJoinColumns = { @JoinColumn(name = "enterprise_id") })
    @JsonIgnoreProperties(allowSetters = true, value = { "organizations" })
    private Enterprise enterprise;
    //getters and setters
}

控制器类:

@PostMapping
public ResponseEntity<ValidationResponse> addOrganization(@Valid @RequestBody Organization organization)
{
    ValidationResponse response = new ValidationResponse();
    response.setMessage(organizationService.addOrganization(organization));

    return new ResponseEntity<ValidationResponse>(response, HttpStatus.CREATED);
}

服务类别:

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class OrganizationServiceImpl implements OrganizationService {
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private OrganizationRepository organizationRepository;      
    public Organization addOrganization(Organization organization) {
        organization.setCreatedDate(Calendar.getInstance());
        organizationRepository.save(organization);
        entityManager.refresh(organization);
        return organization;
    }
}
@Repository
public interface OrganizationRepository extends JpaRepository<Organization, Long> {
}
{
    "organizationName":"org5",
    "enterprise":{
        "enterpriseId":2
    }
}
{
    "success": true,
    "message": {
        "createdBy": 0,
        "updatedBy": 0,
        "createdDate": 1510140158654,
        "updatedDate": null,
        "organizationId": 14,
        "organizationName": "org5",
        "enterprise": {
            "createdBy": 0,
            "updatedBy": 0,
            "createdDate": null,
            "updatedDate": null,
            "enterpriseId": 2,            
            "enterpriseName": null,
            "active": true
        },
        "active": true
    },
    "errors": null
}

共有1个答案

贲培
2023-03-14

你在哪里创建你的“组织”对象?。如果您在addOrganization()方法中创建或检索,然后执行save,那么您应该没有问题。作为最佳实践,服务层应该处理域对象而不是控制器,除非您使用OpenSessionInViewFilter将域传递给controller和View。

 类似资料:
  • 如何使用Spring Rest Controller和Spring Data JPA仅更新从@刚体传递的实体属性? 员工实体: 服务类方法: 请求体: Hibernate更新查询: Spring Data JPA正在尝试将company_id设置为空以进行更新,即使我没有将其传递给请求体?但是如果我从数据库中得到实体,使用employee_id传递,然后如果我试图保存(),那么它的工作正常。 我想

  • 对Powershell很陌生,希望有人能给我指明正确的方向。我想知道是否有一个更干净的方法来完成我下面的工作?如果我对第一次Get-ChildItem调用时返回的文件(存储在$items变量中)做了一些更改,那么有没有一种方法可以刷新到Get-ChildItem的内容? 在第一个foreach语句中,我为返回的所有文件创建一个日志签名。一旦那样做了,我需要做的是;再次获取列表(因为路径中的项已经更

  • 我有一个Spring应用程序,其中Domain Object标识符不是由数据库分配的,而是由应用程序生成的。标识符是在BeforeSave回调期间生成并添加到Domain Object中的。保存域对象(插入)后,当尝试保存具有相同标识符的域对象(更新)时,我收到以下错误 原因:组织。springframework。道。Incorrectupdatesemanticdataaccessexcepti

  • 将数据保存到数据库时,我收到异常 org.hibernate.TransientObjectException:对象引用未保存的瞬态实例 - 在刷新之前保存瞬态实例:com.example.api.entity.Product 我有两个实体。 用户.java 产品.java 我有一个JSON需要添加数据。 } 我阅读了这个ex的内容,并试图将Casca eType更改为另一个,但没有帮助。

  • 我有两个例子。一个是项目,一个是模块。< code >一对多关系。 我将模块设置到项目中。然后使用。第一次,因为数据库中没有记录,所以项目和模块可以保存到数据库中。然而,第二次,因为我不需要创建新项目,我只创建新模块,然后将模块设置回项目。 发生异常。 对象引用未保存的瞬态实例 - 在刷新之前保存瞬态实例。 有什么办法可以解决这个问题吗谢谢

  • 错误是:by:javax.el.elexception://jsf/submit.xhtml@20,76 listener=“#{banklocationmb.savelocation}”对象引用了一个未保存的瞬态实例-在刷新之前保存瞬态实例 尝试添加级联持久化,我收到以下错误 org.springframework.orm.jpa.jpasystemexception:org.hibernate