javaspring-bootjpaspring-data-jpaspring-repositories

How to use deleteById jpa repository if my id is a String?


I need to delete an entity using its ID, tried using JPA repository delete by id method

 productRepository.deleteById(id); 

Where "id" is supposed to be Long- If passed string value will give an error: Long expected

Sample id= "402880f17ebd7e44017ebd7fe9ee0000"

Hence I can't convert the String to Long

Entity class

@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 Class:

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

Solution

  • In your productRepository change the second generic type on the interface from long to string. So Change your code snippet

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

    to:

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

    Also, you don't need @Repository for Spring data JPA interfaces.