【问题标题】:Call SQL server stored procedure with JPA 2.1 annotations使用 JPA 2.1 注释调用 SQL 服务器存储过程
【发布时间】:2015-09-07 18:56:09
【问题描述】:

我正在尝试调用 MS SQL 服务器存储过程。我使用spring-boot,JPA 2.1,休眠。

数据库有一个包含 isbn、标题、作者、描述的表,我试图调用的存储过程将参数 (isbn) 中的一个作为字符串并仅返回标题。

我收到以下错误:

org.hibernate.procedure.ParameterStrategyException: 
Attempt to access positional parameter [2] but ProcedureCall using named parameters

有人对此有解决方案或知道错误的含义吗?我也尝试过其他的注释组合。

Book.java

@Entity
@NamedStoredProcedureQuery(
        name = "bookList", 
        resultClasses=Book.class,
        procedureName = "dbo.list_books", 
        parameters = {
          @StoredProcedureParameter(mode = ParameterMode.IN, name = "isbn", type = String.class)
          })
public class Book {

    @Id
    private String title;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
     }    
}

BookRepository.java

@Repository
public interface BookRepository extends CrudRepository<Book, Long> {

    @Procedure
    Iterable<Book> list_books(String arg);  
}

BookService.java

@RestController
@RequestMapping(value = "/books", produces = MediaType.APPLICATION_JSON_VALUE)
public class BookService {

    @Autowired
    protected BookRepository bookRepository;

    @RequestMapping
    public Iterable<Book> books(){
        return bookRepository.getBooks("1111111");
    }

【问题讨论】:

    标签: java sql-server jpa stored-procedures spring-boot


    【解决方案1】:

    我没有解决注释问题,我使用 EntityManager 和 StoredProcedureQuery 解决了这个问题。

    Book.java 是相同的,但没有@NamedStoredProcedureQuery。我删除了存储库并像这样重写了服务:

    @RestController
    @RequestMapping("/api")
    public class BookService {
    
        @RequestMapping(value = "/books",
                params = {"isbn"},
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
        public  List<Book> getByIsbn(@RequestParam(value = "isbn") String isbn){
            StoredProcedureQuery sp = em.createStoredProcedureQuery("name.of.stored.procedure", Book.class);               
            sp.registerStoredProcedureParameter("isbn", String.class, ParameterMode.IN);
            sp.setParameter("isbn", isbn);
    
            boolean result = sp.execute();
            if (result == true) {
                return sp.getResultList();
            } else {
                // Handle the false for no result set returned, e.g.
                throw new RuntimeException("No result set(s) returned from the stored procedure"); 
            }
    }
    
    }
    

    现在可以使用如下字符串查询调用此端点:http://localhost/api/books?isbn=1111111

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-26
      • 2020-01-23
      • 2015-08-26
      • 2018-11-13
      • 2014-12-14
      • 2014-11-30
      • 1970-01-01
      • 2021-03-15
      相关资源
      最近更新 更多