使用 POST 方法在保存前加入实体

Join entities before save using POST method

我有两个实体,User 和 Operation,两个实体之间都有一个连接:

@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;

    @Basic
    private String username;

    private String password;

    //Getters and Setters
}

@Entity
public class Operation implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;

    @ManyToOne
    @JoinColumn(name = "user_id")
    User user;

    //Getters and Setters

}

两个实体也都有一个存储库。

在我的上下文中,当用户(操作员)被记录时,用户实体被加载到会话范围(HttpSession)中。 对于用户在系统上的每个操作,应用程序都会通过操作存储库注册该操作。

我的问题是:如何将用户实体(进入会话)设置为在数据库中注册之前运行?

是否可以覆盖 Repository 方法?

编辑 1:

使用 HTTP POST 方法通过 Web 界面保存操作。我需要继续使用 URI 来保存。喜欢:

URI:http://localhost:9874/操作 数据:{“名称”:“操作名称”}

谢谢!

创建自定义存储库接口并为其编写实现。例如。

public interface OperationRepositoryCustom {

  <T extends Operation> T saveCustomized(Operation operation);
}

您的实施 class 将如下所示。

public class OperationRepositoryImpl implements OperationRepositoryCustom{
  //You can autowire OperationRepository and other dependencies 

  @Autowired
  OperationRepository operationRepository;  

  @Override
  public Operation saveCustomized(Operation operation) {
      //put your code to update operation with user and save it by calling operationRepository.save(). 
  }
}

请注意命名约定,您的自定义实现需要与您的存储库 + Impl 具有相同的名称。因此,如果您的存储库接口称为 OperationRepository,则您的自定义存储库接口应为 OperationRepositoryCustom,impl 应命名为 OperationRepositoryImpl

希望对您有所帮助

您可以创建一个预保存事件处理程序,您可以在其中设置关联:然后您可以制作一个标准的 Spring 数据休息 post 到 http://localhost:9874/operations 并且没有必要对于自定义存储库或控制器。

http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_writing_an_annotated_handler

@RepositoryEventHandler 
public class OperationEventHandler {

  @HandleBeforeSave
  public void handleOperationSave(Operation operation) {

  }
}

你说用户存储在会话中。我看你是不是用了Spring 安全?如果是,则可以使用静态调用获取当前用户:

SecurityContextHolder.getContext().getAuthentication();

否则,您需要尝试将 HttpServletRequest 连接到您的事件处理程序,或者使用这些问题的答案中概述的静态包装器调用:

从这里你可以获得HttpSession。

下面显示了在这种情况下在 HttpServletRequest 中的连接

所以你的处理程序看起来像:

@RepositoryEventHandler 
public class OperationEventHandler {

  @Autowired
  private HttPServletRequest request;

  @HandleBeforeSave
  public void handleOperationSave(Operation operation) {

      User user = (User)request.getSession().getAttribute("userKey");
      operation.setUser(user); 
  }
}