• This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts

  • kevin
    Keymaster
    Postcount 39

    Dear all, please give me sample code use Sum in Query in Spring Boot JPA. Thanks all


    kevin
    Keymaster
    Postcount 39

    You can see my sample code as below:

    1. Declare Entity:

    package com.demo.entities;

    import java.io.Serializable;

    import java.math.BigDecimal;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name = “product”)
    public class Product implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String name;

    private BigDecimal price;

    private int quantity;

    private String description;

    private String photo;

    private boolean featured;

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public BigDecimal getPrice() {
    return price;
    }

    public void setPrice(BigDecimal price) {
    this.price = price;
    }

    public int getQuantity() {
    return quantity;
    }

    public void setQuantity(int quantity) {
    this.quantity = quantity;
    }

    public String getDescription() {
    return description;
    }

    public void setDescription(String description) {
    this.description = description;
    }

    public String getPhoto() {
    return photo;
    }

    public void setPhoto(String photo) {
    this.photo = photo;
    }

    public boolean isFeatured() {
    return featured;
    }

    public void setFeatured(boolean featured) {
    this.featured = featured;
    }

    }

    2. Create Repository:

    package com.demo.repositories;

    import java.math.BigDecimal;
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.CrudRepository;
    import org.springframework.stereotype.Repository;
    import com.demo.entities.Product;

    @Repository(“productRepository”)
    public interface ProductRepository extends CrudRepository<Product, Integer> {

    @Query(value = “SELECT sum(quantity) FROM Product”)
    public Long sumQuantities();

    @Query(value = “SELECT sum(quantity * price) FROM Product”)
    public BigDecimal total();

    }

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.
Top