【问题标题】:IllegalArgumentException: NamedQuery using Spring JPAIllegalArgumentException:使用 Spring JPA 的 NamedQuery
【发布时间】:2016-12-26 02:10:09
【问题描述】:

我正在使用 Spring JPA 为 rest api 使用 namedquery。命名查询在我的实体类中实现:

@Entity
@Table(name="SPECIMEN_TB")
@NamedQueries({
    @NamedQuery(name="SpecimenTb.findBySpecimenNo", query="select s from SpecimenTb s where s.specimenNo = :specimenNo"),
})

public class SpecimenTb implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SPECIMEN_TB_ROWID_GENERATOR")
    @Column(name="ROW_ID")
    private long rowId;

    @Column(name="SPECIMEN_NO", unique = true)
    private String specimenNo;

我的控制器如下所示:

@RestController
public class RistoreController {
    @Autowired
    private RistoreService ristoreService;

    @RequestMapping(
            value = "/ristore/foundation/{specno}",
            method = RequestMethod.GET,
            produces = "application/json")
    public ResponseEntity<SpecimenTb> getFmSpecimen(@PathVariable("specno") String specno) {
        List<SpecimenTb> specimens = ristoreService.findBySpecimenNo(specno);
        if (specimens == null) {
            return new ResponseEntity<SpecimenTb>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<SpecimenTb>(specimens.get(0), HttpStatus.OK);
    }

我有一个调用 JPA 存储库 findBySpecimenNo 方法的服务 bean。

@Service
public class RistoreServiceBean implements RistoreService {

    @Autowired
    private SpecimenRepository specimenRepository;

    @Override
    public List<SpecimenTb> findAll() {
        List<SpecimenTb> specimens = specimenRepository.findAll();
        return specimens;
    }

    @Override
    public List<SpecimenTb> findBySpecimenNo(String specimenNo) {
        List<SpecimenTb> specimens = specimenRepository.findBySpecimenNo(specimenNo);
        return specimens;
    }

当我启动 Spring Boot 应用程序并输入 url“http://localhost:8080/ristore/foundation/SKM1”时,出现以下错误:

java.lang.IllegalArgumentException: Parameter with that position [1] did not exist

我做错了什么?

【问题讨论】:

    标签: rest jpa spring-boot named-query


    【解决方案1】:

    根据我阅读的文档,您似乎不能将命名参数与 @NamedQuery 一起使用。你试过用?1 代替吗?

    命名参数不起作用的原因是您还必须在方法参数上添加注释,以便 Spring 知道哪个参数与查询中的占位符匹配。

    【讨论】:

    • 它现在可以工作了,如果我想让命名参数工作,我应该在哪里“在方法参数上添加注释”?
    • 我没有看到您的存储库接口/类,但这就是它可以完成的地方。查看 @Query 周围的 spring-data-jpa 文档
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    相关资源
    最近更新 更多