为什么java定义的是int显示的却是string

Python013

为什么java定义的是int显示的却是string,第1张

登录

首页

学习

实践

活动

工具

TVP

Java返回错误:应为int,但得到的是字符串

原文

Rhadamez Gindri Hercilio修改于2021-08-30

spring

rest

与这个错误作斗争,但找不到明显的数据类型错误,通常会导致它,我附上了相关的代码。

错误:

TypeMismatchException: id of the wrong type com.example.demo.models.Hires. Expected: class java.lang.Integer, got class java.lang.String

复制

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private int id

@Column(unique = true)

private String hid

复制

@GetMapping(path = "/{hid}")

public Hires getHires(@PathVariable String hid) {

return hs.getHireById(hid).get()

复制

public Optional<Hires>getHireById(String hid) {

return hr.findById(hid)

复制

如果有人能找出可能导致这种情况的原因,我将不胜感激。

浏览 29关注 0得票数 1

原文

英文原版

Struggling with this error but cant find the obvious datatype mistakes that would usually cause it I have attached the relevant code.

The error:

TypeMismatchException: id of the wrong type com.example.demo.models.Hires. Expected: class java.lang.Integer, got class java.lang.String

复制

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private int id

@Column(unique = true)

private String hid

复制

@GetMapping(path = "/{hid}")

public Hires getHires(@PathVariable String hid) {

return hs.getHireById(hid).get()

复制

public Optional<Hires>getHireById(String hid) {

return hr.findById(hid)

复制

If anyone can spot what might be causing this it would be extremely appreciated.

1 个回答

高票数

操作

Rhadamez Gindri Hercilio

修改于2021-08-26

得票数 0

我认为您的问题在于字符串参数hid,请参见:

方法

public Optional<Hires>getHireById(String hid) {

return hr.findById(hid)

}

复制

它正在接收一个字符串hid,它应该是int hid,因为您是通过id查找的,而id是int。

但是您想通过hid查找,所以您必须在存储库中创建一个方法,如下所示:

public Optional<Hires>findByHid(String hid)

复制

然后,您可以像这样使用:

public Optional<Hires>getHireById(String hid) {

return hr.findByHid(hid)

}

复制

1、String在Java中属于关键字。String类名即Class java.lang.String 。

2、String 类是不可改变的,所以你一旦创建了 String 对象,那它的值就无法改变了。

3、用于获取有关对象的信息的方法称为访问器方法。String 类的一个访问器方法是 length() 方法,它返回字符串对象包含的字符数。

4、返回 string2 连接 string1 的新字符串。也可以对字符串常量使用 concat() 方法。

5、String 类使用静态方法 format() 返回一个String 对象而不是 PrintStream 对象。String 类的静态方法 format() 能用来创建可复用的格式化字符串,而不仅仅是用于一次打印输出。