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

Time:02-11

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>{
}

CodePudding user response:

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.

CodePudding user response:

In your ProductRepository, when you are extending the JpaRepository<EntityName,EntityId Type>. In your case, you are using the field id as string but extending the type as Long. To solve your problem, either take the input in the form of Long number or convert the primary key type to String.

CodePudding user response:

The primary key type is wrong, should be ‘String’, not ‘Long’:

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