SpringData JPA - 为类提供了错误类型的id。预期:类java.lang.Integer,得到类java.lang.Long

时间:2017-10-26 17:14:07

标签: mysql spring-data-jpa

我在使用Spring JPA并尝试检索对象列表时遇到此问题。

这是我试图检索的课程

Object

@Entity public class Object { @Column(name="OBJECTID") @Id @JsonProperty("OBJECTID") private int objectId; .... 类将MySQL上的主键存储为Integer,实际上这是Object

@Override
    public List<TermicObject> findAll() {

        return repository.findAll();
    }

所以,没有任何地方设置长...

现在,我只需要在服务类中调用

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TypeMismatchException: Provided id of the wrong type for class it.besmart.db_eipo.persistence.model.Object. Expected: class java.lang.Integer, got class java.lang.Long; nested exception is java.lang.IllegalArgumentException: org.hibernate.TypeMismatchException: Provided id of the wrong type for class it.besmart.db_eipo.persistence.model.Object. Expected: class java.lang.Integer, got class java.lang.Long

并得到了这个例外

if let data = characteristic.value {
    var dataArray = [Int16](repeating: 0, count: data.count/MemoryLayout<Int16>.stride)
    dataArray.withUnsafeMutableBufferPointer {
        _ = data.copyBytes(to: $0)
    }
    let finalAnswer = Double(dataArray[1])/128
}

在哪里设置Object Id应该是Long?

4 个答案:

答案 0 :(得分:1)

按照@Lubo的回答,就我而言,我遇到了String和Long类型之间的兼容性问题,并且由于我的模型需要一个Long自动生成的ID,因此我不得不更改存储库

public interface ProductRepository extends JpaRepository<Product, String> {
}

public interface ProductRepository extends JpaRepository<Product, Long> {
}

还有我的控制器

@RequestMapping(path = "/products/delete/{id}", method = RequestMethod.DELETE)
public void deleteProduct(@PathVariable(name = "id") String id) {
    productRepository.deleteById(id);
}

@RequestMapping(path = "/products/delete/{id}", method = RequestMethod.DELETE)
public void deleteProduct(@PathVariable(name = "id") Long id) {
    productRepository.deleteById(id);
}

答案 1 :(得分:0)

不完全确定,但我认为这种映射

@Id
@Column(name="TERMICID")
private long termicId;

@MapsId
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="OBJECTID",columnDefinition="INTEGER")
private Object object;

使Object的ID与termicId的值匹配,这是一个很长的。

答案 2 :(得分:0)

查看存储库的定义。它具有正确的泛型类型吗?您是否将Integer作为第二个参数?恕我直言,这可能是根本原因。请参阅建议的正确版本:

@RepositoryRestResource
public interface TermicObjectRepository extends JpaRepository<TermicObject, Integer> {
    public Optional<TermicObject> findById(Integer id);
    public List<TermicObject> findAll()
}

答案 3 :(得分:0)

您必须将 id 定义为 Long 数据类型。

@Id
@Column(name="TERMICID")
private Long termicId;

还要对您的存储库界面进行更改:

public interface ProductRepository extends JpaRepository<Product, Long> {
}