How can I execute a stored procedure with JPA & Spring Data?

后端 未结 2 426
情书的邮戳
情书的邮戳 2021-01-17 10:59

I am trying to call the Terminal_GetTicket stored procedure in my database but keep getting the following exception:

PropertyReferenceException:         


        
2条回答
  •  悲&欢浪女
    2021-01-17 11:51

    I followed SirKometas advice but I could not get it to work so I came up with something that worked for me and I think from syntax point of view is better. First create your entity class like below.

    @NamedStoredProcedureQueries({//
        @NamedStoredProcedureQuery(//
                name = "MySP"//
                , procedureName = "my_sp"//
                , parameters = { //
                        @StoredProcedureParameter(mode = ParameterMode.IN, name = "arg", type = String.class)}//
                , resultClasses = Foo.class)//})
    @Entity
    public class Foo {
    

    Then the Implementation class of the repository would be:

    @Component
    public class FooRepositoryImpl implements FooCustomRepository {
    
        @PersistenceContext
        EntityManager entityManager;
    
        @Override
        public List foo(String arg) {
            Query query = entityManager.createNamedStoredProcedureQuery("MySP");
            query.setParameter("arg", arg);
            return query.getResultList();
        }
    }
    

    The rest of the implementation is like the answer from SirKometa above. Think also that you have to create a EntityManager bean in your application for this to work.

提交回复
热议问题