【问题标题】:How to use deleteById jpa repository if my id is a String?如果我的 id 是字符串,如何使用 deleteById jpa 存储库?
【发布时间】:2022-08-12 21:00:27
【问题描述】:

我需要使用其 ID 删除实体,尝试使用 JPA 存储库 delete by id 方法

 productRepository.deleteById(id); 

其中 \"id\" 应该是 Long- 如果传递的字符串值将给出错误:Long expected

Sample id= \"402880f17ebd7e44017ebd7fe9ee0000\"

因此我不能将字符串转换为长

实体类

@Entity
@Table(name = \"products\")
public class Product {

@Id @GeneratedValue(generator = \"system-uuid\")
@GenericGenerator(name=\"system-uuid\",strategy = \"uuid\")
@Column(name=\"product_id\")
private String id;

@Column(name=\"price\")
@NotNull
private float productPrice;

@Column(name=\"product_name\")
@NotNull
private String productName;

@Column(name=\"description\")
private String productDesc;

@Column(name=\"stock_available\")
private int productStock;

@ManyToOne(optional = false)
@JoinColumn(name = \"shop_id\")
private Shop shop;

public Product(){
}

public Product(String id, float productPrice, String productName, String productDesc, int productStock, Shop shop) {
    this.id = id;
    this.productPrice = productPrice;
    this.productName = productName;
    this.productDesc = productDesc;
    this.productStock = productStock;
    this.shop = shop;
}
}

存储库类:

@Repository
public interface ProductRepository extends JpaRepository<Product,Long>{
}
  • 添加有关您的实体和回购的问题详细信息
  • 出色地?如何您应该将该字符串转换为整数值吗?那是十六进制字符串吗?

标签: java spring-boot jpa spring-data-jpa spring-repositories


【解决方案1】:

在您的 productRepository 中,将接口上的第二个泛型类型从 long 更改为 string。所以改变你的代码sn-p

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

至:

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

此外,对于 Spring 数据 JPA 接口,您不需要 @Repository

【讨论】:

  • 你能详细说明一下吗?
  • @ShashankPrasad Daniel 可能的意思是,您从JpaRepository&lt;Product, Long&gt; 扩展,其中Product 是您的实体类,Long 是id 的类型。由于您使用 String 作为 id 而不是 Long,因此您应该从 JpaRepository&lt;Product, String&gt; 扩展。
  • 为了更清楚,我更新了我的答案。
【解决方案2】:

在您的 ProductRepository 中,当您扩展 JpaRepository&lt;EntityName,EntityId Type&gt;. 在您的情况下,您将字段 id 用作字符串,但将类型扩展为 Long。 要解决您的问题,请以 Long 数字形式输入或将主键类型转换为 String。

【讨论】:

    【解决方案3】:

    主键类型错误,应该是“String”,而不是“Long”:

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

    【讨论】:

      【解决方案4】:
      public interface ProductRepository extends JpaRepository<Product,String> {}
      

      只需使用 String 而没有 @Repository 写上面的行

      解释:

      • JpaRepository 的第二个参数是该 dto 的 Id 类型
      • 任何与组件相关的注释在接口上都是无用的,它只需要在类上,所以@Repository 应该只在你编写 ProductRepository 接口的实现类时应用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-13
        • 2020-02-29
        • 1970-01-01
        • 2021-01-17
        • 2018-08-20
        • 1970-01-01
        • 2013-09-08
        相关资源
        最近更新 更多