[英]Is it possible to map JPA entity to stored procedure (function)?
I need to map JPA entity to Postgres function which returns table. 我需要将JPA实体映射到返回表的Postgres函数。 So each time when I query for this entity, it will automatically invoke this function. 因此,每次我查询该实体时,它将自动调用此函数。 Is it possible? 可能吗? Maybe @NamedNativeQuery can help? 也许@NamedNativeQuery可以提供帮助?
If your function don't have any arguments you can encapsulate it on a view: 如果您的函数没有任何参数,则可以将其封装在视图上:
CREATE VIEW my_entity_procedure AS
SELECT 'Id:' || i AS some_field, i FROM generate_series(0, 100) i;
And then map it to a read-only entity ( @Immutable
). 然后将其映射到只读实体( @Immutable
)。
I agree, that's weird and I don't recommend this approach. 我同意,那很奇怪,我不推荐这种方法。 Remember that you can use a ResultTransformer
to transform a raw ResultSet in a list of objects (DTO in this case). 请记住,您可以使用ResultTransformer
在对象列表(本例中为DTO)中转换原始 ResultSet。 Something like below must works: 像下面这样的东西必须工作:
public List<MyFunctionDTO> getAllFromMyFunction() {
StringBuilder sql = new StringBuilder("SELECT i FROM generate_series(0, 100) i");
Query query = getHibernate().getSession().createSQLQuery(sql.toString());
query.setResultTransformer(Transformers.aliasToBean(MyFunctionDTO.class));
return query.list();
}
I don't know the limitations on Postgres but the general rule for mapping an Entity to an stored procedure using JPA is here : 我不知道的Postgres但限制映射实体使用 JPA 的存储过程,总的原则是在这里 :
@Entity
@NamedStoredProcedureQueries({
@NamedStoredProcedureQuery(
name = "myNamedProcedure",
procedureName = "SP_NAME",
resultClasses = { MyEntity.class },
parameters = {
@StoredProcedureParameter(
name = "parameter1",
type = Integer.class,
mode = ParameterMode.IN) ... })
})
public class MyEntity {...}
You can use CallableStatement 您可以使用CallableStatement
con is your Connection object con是您的Connection对象
CallableStatement cs = con.prepareCall("{call your_procedure()}");
if you have parameters : 如果您有参数:
CallableStatement cs = con.prepareCall("{call your_procedure(?,?)}");
EXAMPLE 例
cs.setString(1,your_param);
if you wanna get result : 如果您想得到结果:
EXAMPLE 例
cs.registerOutParameter(2, Types.INTEGER);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.