保存后刷新并获取实体(JPA/Spring Data/Hibernate)

我有这两个简单的实体和.该实体与 具有多对一关系,因此当我创建新行时,我会分配一个现有的 .SomethingPropertySomethingPropertySomethingProperty

东西:

@Entity
@Table(name = "something")
public class Something implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @Column(name = "owner")
    private String owner;

    @ManyToOne
    private Property property;

    // getters and setters

    @Override
    public String toString() {
        return "Something{" +
            "id=" + getId() +
            ", name='" + getName() + "'" +
            ", owner='" + getOwner() + "'" +
            ", property=" + getProperty() +
            "}";
    }

财产:

@Entity
@Table(name = "property")
public class Property implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "shape")
    private String shape;

    @Column(name = "color")
    private String color;

    @Column(name = "dimension")
    private Integer dimension;

    // getters and setters

    @Override
    public String toString() {
        return "Property{" +
            "id=" + getId() +
            ", shape='" + getShape() + "'" +
            ", color='" + getColor() + "'" +
            ", dimension='" + getDimension() + "'" +
            "}";
    }
}

这是(春天):SomethingRepository

@SuppressWarnings("unused")
@Repository
public interface SomethingRepository extends JpaRepository<Something,Long> {
    
}

通过REST控制器和JSON,我想创建一个新的:Something

@RestController
@RequestMapping("/api")
public class SomethingResource {

    private final SomethingRepository somethingRepository;

    public SomethingResource(SomethingRepository somethingRepository) {
        this.somethingRepository = somethingRepository;
    }

    @PostMapping("/somethings")
    public Something createSomething(@RequestBody Something something) throws URISyntaxException {
        Something result = somethingRepository.save(something);
        return result;
    }
}

这是输入中的 JSON(1 是数据库中的现有行):propertyid

{
  "name": "MyName",
  "owner": "MySelf",
  "property": {
    "id": 1
  }

}

问题是:在方法之后,变量包含持久化实体,但没有字段的字段,已验证(它们是):.save(something)resultpropertynull

输出 JSON:

{
  "id": 1,
  "name": "MyName",
  "owner": "MySelf",
  "property": {
    "id": 1,
    "shape": null,
    "color": null,
    "dimension": null
  }
}

我希望它们在保存操作后被验证/返回。

为了解决这个问题,我必须在REST控制器中注入/声明,并调用该方法(或者我必须调用一个方法才能获得完整的持久化实体):EntityManagerEntityManager.refresh(something).findOne(something.getId())

@RestController
@RequestMapping("/api")
@Transactional
public class SomethingResource {

    private final SomethingRepository somethingRepository;
    
    private final EntityManager em;

    public SomethingResource(SomethingRepository somethingRepository, EntityManager em) {
        this.somethingRepository = somethingRepository;
        this.em = em;
    }

    @PostMapping("/somethings")
    public Something createSomething(@RequestBody Something something) throws URISyntaxException {
        Something result = somethingRepository.save(something);
        em.refresh(result);
        return result;
    }
}

有了这个解决方法,我得到了预期的保存(使用正确的JSON):

{
  "id": 4,
  "name": "MyName",
  "owner": "MySelf",
  "property": {
    "id": 1,
    "shape": "Rectangle",
    "color": "Red",
    "dimension": 50
  }
}

有没有一个自动的方法/注释,JPA或Spring或Hibernate,以便拥有“完整”的持久化实体?

我希望避免在每个 REST 或 Service 类中声明 the,或者我想避免每次需要新的刷新持久化实体时调用该方法。EntityManager.findOne(Long)


答案 1

您可以通过创建自定义 Jpa 存储库来定义它,而不是在每个资源中定义它。参考EntityManager

然后直接在每个存储库中使用 您的 。refreshEntityManager

请参考以下示例:

自定义存储库界面

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

import java.io.Serializable;

@NoRepositoryBean
public interface CustomRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
  void refresh(T t);
}

自定义存储库实现

import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.io.Serializable;

public class CustomRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
    implements CustomRepository<T, ID> {

  private final EntityManager entityManager;

  public CustomRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) {
    super(entityInformation, entityManager);
    this.entityManager = entityManager;
  }

  @Override
  @Transactional
  public void refresh(T t) {
    entityManager.refresh(t);
  }
}

在 Spring Boot Application Class 中启用自定义 JPA 存储库

@SpringBootApplication
@EnableJpaRepositories (repositoryBaseClass = CustomRepositoryImpl.class)
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

您的知识库

public interface SomethingRepository extends CustomRepository<Something, Long> {

}

直接在 SomethingResource 中使用 Refresh(假设 Something 是一个实体)

@RestController
@RequestMapping("/api")
@Transactional
public class SomethingResource {

    private final SomethingRepository somethingRepository;

    public SomethingResource(SomethingRepository somethingRepository) {
        this.somethingRepository = somethingRepository;
    }

    @PostMapping("/somethings")
    public Something createSomething(@RequestBody Something something) throws URISyntaxException {
        Something result = somethingRepository.save(something);
        somethingRepository.refresh(result);
        return result;
    }
}

答案 2

这还不够:

Something result = somethingRepository.save(something);

您需要手动合并传入实体:

Something dbSomething = somethingRepository.findOne(
    Something.class, something.getId()
);
dbSomething.setName(something.getName());
dbSomething.setOwner(something.getOwner());

somethingRepository.save(dbSomething);

由于该属性使用默认的 FetchType.EAGER,因此实体应初始化该属性。propertyproperty

但是,从 REST 控制器调用存储库两次很奇怪。您应该有一个在服务方法中完成所有这些操作的服务层。这样,您就不需要重新保存实体,因为它已经过管理。@Transactional

@Transactional
public Something mergeSomething(Something something) {
    Something dbSomething = somethingRepository.findOne(
        Something.class, something.getId()
    );
    dbSomething.setName(something.getName());
    dbSomething.setOwner(something.getOwner());

    return dbSomething;
}

现在,您需要仔细合并您发送的每个属性。在你的情况下,如果你发送,你应该决定你是否应该取消引用。因此,这取决于您当前的应用程序业务逻辑要求。nullproperty@ManyToOne

更新

如果您确保始终发回之前获取的同一实体,则可以使用 。merge

em.merge(result);

但是您的属性只是一个 id,而不是实际的子实体,因此您必须在服务层中自行解析。property


推荐