如何从 MessagingGateway 设置 Jpa 查询参数?

How do I set the Jpa Query parameter from MessagingGateway?

我正在使用 Java 实现交易发件箱模式。消息中继服务将轮询发件箱 table 以查找条目,在找到并处理发件箱消息后,它将更新发件箱条目。

问题是,如何将 MessagingGateway 的参数设置为 Jpa 查询?

@Bean
public JpaExecutor jpaUpdateStateExecutor() {
    JpaExecutor jpaExecutor = new JpaExecutor(this.entityManagerFactory);
    jpaExecutor.setNamedQuery("myQuery");
    jpaExecutor.setUsePayloadAsParameterSource(true);
    jpaExecutor.setExpectSingleResult(true);
    return jpaExecutor;
}

@Bean
@ServiceActivator(inputChannel = "jpaChannel")
public MessageHandler jpaOutbound() {
    JpaOutboundGateway gateway = new JpaOutboundGateway(jpaUpdateStateExecutor());
    gateway.setGatewayType(OutboundGatewayType.UPDATING);
    return gateway;
}

我的网关:

@MessagingGateway
public interface MyGateway {
    @Gateway(requestChannel = "jpaChannel")
    @Transactional
    void jpaActions(Long idOfEntity);
}

我的域对象:

@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@Table
@NamedQuery(name = "myQuery", query = "UPDATE MyTable SET state = 'PROCESSED' WHERE id = :id")
public class Outbox {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    private String state;
}

很高兴看到您的查询以及您希望如何将 Long idOfEntity 映射到某个查询参数。

setUsePayloadAsParameterSource 的文档如下所示:

use-payload-as-parameter-source

If set to true, the payload of the Message is used as a source for parameters. If set to false, the entire Message is available as a source for parameters. If no JPA Parameters are passed in, this property defaults to true. This means that, if you use a default BeanPropertyParameterSourceFactory, the bean properties of the payload are used as a source for parameter values for the JPA query. However, if JPA Parameters are passed in, this property, by default, evaluates to false. The reason is that JPA Parameters let you provide SpEL Expressions. Therefore, it is highly beneficial to have access to the entire Message, including the headers. Optional.

https://docs.spring.io/spring-integration/docs/current/reference/html/jpa.html#jpa-outbound-gateway-common-parameters

也许您更愿意将该选项设置为 false,然后在您的查询中您可以使用 idOfEntity 的参数作为 :payload 占位符。