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

时间:2017-08-03 18:04:55

标签: java hibernate jpa spring-data-jpa persistence

我有两个简单的实体SomethingPropertySomething实体与Property具有多对一关系,因此当我创建新的Something行时,我会分配一个现有的Property

东西:

@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(property id 1是数据库中的现有行):

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

}

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

输出JSON:

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

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

要解决此问题,我必须在REST控制器中注入/声明EntityManager,并调用方法EntityManager.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;
    }
}

通过这种解决方法,我得到了预期的保存的entith(使用正确的JSON):

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

是否有自动方法/注释,使用JPA或Spring或Hibernate,以获得“完整”持久化实体?

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

非常感谢, 安德烈

4 个答案:

答案 0 :(得分:11)

您可以通过创建自定义 JpaRepository来定义一次,而不是在每个资源中定义EntityManagerReference

然后直接在您的每个存储库中使用refresh的{​​{1}}。

参考以下示例:

CustomRepository接口

EntityManager

CustomRepository实施

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);
}

在Spring Boot Application Class中启用自定义JPARepository

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);
  }
}

您的东西存储库

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

直接在SomethingResource中使用Refresh (假设某事是实体)

public interface SomethingRepository extends CustomRepository<Something, Long> {

}

答案 1 :(得分: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);

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

但是,从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;
}

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

更新

如果您确定始终发送回先前提取的同一实体,则可以使用merge

em.refresh(result);

但是你的property属性只是一个id,而不是一个真正的子实体,所以你必须自己在服务层解决这个问题。

答案 2 :(得分:0)

当您持久保存实体时,它将处于托管状态,因此如果您只是调用something.getProperty();,它将从数据库加载并填充property实体的something

public Something save(Something something) {
    em.persist(something);
    something.getProperty();
    return something;
}

通常情况下,当你有多对一的关系时,应该自动获取。如果没有调用实体中对象的getter,也会通过触发新的DB Find请求来填充它们。

答案 3 :(得分:0)

在Spring Boot JpaRepository中:

如果我们的修改查询更改了持久性上下文中包含的实体,则该上下文将过时。

为了从数据库中获取具有最新记录的实体。

使用@Modifying(clearAutomatically = true)

@Modifying批注具有clearAutomatically属性,该属性定义执行修改查询后是否应清除基础持久性上下文。

示例:

@Modifying(clearAutomatically = true)
@Query("UPDATE NetworkEntity n SET n.network_status = :network_status WHERE n.network_id = :network_id")
        int expireNetwork(@Param("network_id") Integer network_id,  @Param("network_status") String network_status);