I am trying to calculate sum of amount in sql.I am using java POJO classes.Now i am writing query like this
"SELECT SUM(amount) FROM fundraisingusers ";
But it is displaying error as Could not find setter for SUM(amount) on class com.lh.alumni.dto.FundraisingUsers.How to add getter and setter for SUM in my Java pojo class?
Here is my pojo class
public class FundraisingUsers implements Serializable{
private Integer fundraisinguserId;
private BigDecimal amount;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "fundraisinguserId")
public Integer getFundraisinguserId() {
return fundraisinguserId;
}
public void setFundraisinguserId(Integer fundraisinguserId) {
this.fundraisinguserId = fundraisinguserId;
}
#Column(name = "amount")
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
I guess what you are trying to do is, you want to get the sum of all users amount.
The problem here is, you try to get a fundraisingusers-object and assign the amount to the sum of all users amounts to each user. This is wrong.
What you can do is:
SELECT amount FROM fundraisingusers;
and for all models you get you can then build the sum on code-side.
or you could try building a pojo with getter/setter like
private BigDecimal sumamount;
#Column(name = "sumamount")
public BigDecimal getSumAmount() {
return this.sumamount;
}
public void setSumAmount(BigDecimal amount) {
this.sumamount= sumamount;
}
and the query is
SELECT sum(amount) as SumAmount FROM fundraisingusers;
Related
I'm trying to build simple REST for purchases I need 2 methods. The first method should show all purchases sorted by date. The second one removes all purchases for specified date I made a method to add and to get all purchases. Now I'm stuck.
#Entity
#Table (name="purchase")
public class Purchase {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#CreationTimestamp
#Temporal(TemporalType.DATE)
#Column(name="createat")
private Date created;
#Column(name="price")
private BigDecimal price;
#Column(name="currency")
private String currency;
#Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long>
{
}
#Service
public class PurchaseService {
#Autowired
private PurchaseRepository purchaseRepository;
public void addPurchase(Purchase purchase) {
purchaseRepository.save(purchase);
}
public List<Purchase> getAllPurchase() {
List<Purchase> purchase = new ArrayList<>();
purchaseRepository.findAll().forEach(purchase::add);
return purchase;
}
}
#RestController
public class PurchaseController {
#Autowired
private PurchaseService purchaseService;
#PostMapping("/purchase")
public void addPurchase(#RequestBody Purchase purchase) {
purchaseService.addPurchase(purchase);
}
#RequestMapping("/purchase")
public List<Purchase> getAllTopics() {
return purchaseService.getAllPurchase();
}
}
What I need:
1. method to sort my List sorted by date
2. method that removes all purchases for specified date
You can use Spring Data JPA features in these cases.
Add the following methods to PurchaseRepository:
List<Purchase> findAllByOrderByCreatedAsc();
long deleteByCreated(Date created);
And after all, Spring is going to generate an appropriate query based on a method name.
I got it
long deleteByCreated(Date date);
#Transactional
public long deleteAllByDate(Date date){
return purchaseRepository.deleteByCreated(date);
}
#RequestMapping(method=RequestMethod.DELETE, value="/purchasess/{date}")
public long findAllByCreatedBetween(#DateTimeFormat(pattern="yyyy-MM-dd")
#PathVariable Date date){
return purchaseService.deleteAllByDate(date);
}
I am new to REST API, so I am not sure whether I have phrased the question correctly.
I have a Java class with two attributes.
class TestClass {
private double rate;
private double quantity;
#ApiModelProperty
getRate() {
return rate;
}
#ApiModelProperty
getQuantity() {
return quantity;
}
}
I have an API, which when i call, fetches data from an SQL table and returns a JSON object as shown(I have used examples):
{
rate = 5;
quantity = 10;
}
I want to modify the output so that only either rate or quantity would be displayed depending on the condition. How do i do it?
You can have two API methods that each returns different object
class TestClassRate {
private double rate;
#ApiModelProperty
getRate() {
return rate;
}
}
class TestClassQuantity {
private double quantity;
#ApiModelProperty
getQuantity() {
return quantity;
}
}
what is the condition? if you want to show only not null field, you have to make the correct configuration of your json provider.
For example, if you're using Jackson :
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
How to pick up data from one field based on the condition of another field?
As shown below, I want to populate the class 'simulation' with the data from the class 'salary', the condition is like:
simulation.id = salary.id;
Some id has simulatedSalary, some id has notsimulatedSalary, some id has both of simulated and notsimulated Salary;
if(salary.simulated == true) then simulation.simulatedSalary = salary.salary, else simulation.simulatedSalary == 0;
if(salary.simulated == false) then simulation.notsimulatedSalary = salary.salary, else simulation.notsimulatedSalary == 0;
simulation.totalSalary = sum(simulation.simulatedSalary + simulation.notsimulatedSalary).
How to implement the above condition?
to populate List<simulation> simulationList from List<salary> salaryList:
public class salary {
private Integer id;
private Boolean simulated;
private Double salary;
}
public class simulation {
private Integer id;
private Double simulatedSalary;
private Double notsimulatedSalary;
private Double totalSalary;
}
if you want to implement the above code you should use inheritance also you should use protected data fields and not private for both of your class
sample usage of inheritances: in this code, your parent class is Salary and your child class is Simulation then you must set your data fields to be protected instead of private so that the child class can use its parent class variable directly
in inheritance child class can use all the methods and fields that are public or protected by the parent class
public class Salary
{
protected Integer id;
protected Boolean simulated;
protected Double salary;
}
public class Simulation extends Salary
{
//you do not need Integer id here
private Double simulatedSalary;
private Double notsimulatedSalary;
private Double totalSalary;
}
I am implementing a banking application and have three tables in my database (User, Account and AccountActivity):
The implementation of the Account and AccountActivity classes look like this:
#MappedSuperclass public abstract class AbstractDomain implements Serializable {
#Id #GeneratedValue
private long id = NEW_ID;
public static long NEW_ID = -1;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isNew() {
return id==NEW_ID;
}
}
#Table(name="ACCOUNT_ACTIVITY")
#Entity
public class AccountActivity extends AbstractDomain {
#Column(name="NAME")
private String Name;
#Column(name="XDATE")
private Date Date;
#Column(name="VALUE")
private double Value;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="ACCOUNTID")
private Account ACCOUNT;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="OTHERACCOUNTID")
private Account OTHERACCOUNT;
public String getName() {
return Name;
}
// ...
}
And:
#Table(name="ACCOUNT")
#Entity
public class Account extends AbstractDomain {
#Column(name="NAME")
private String Name;
#Column(name="XDATE")
private Date Date;
#Column(name="VALUE")
private double Value;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="USERID")
private User USER;
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<AccountActivity> AccountActivity = new ArrayList<AccountActivity>();
// ...
}
To store new accounts in my database I use this:
public Account storeAccount(Account ac) {
User x = ac.getUser();
x = em.merge(x);
ac = em.merge(ac);
return ac;
}
which works to just store new accounts in my database. I wanted to implement the functionality that when account activity information is added to an already saved account,
that account will be updated and the added information (account activity) is cascaded to the
AccountActivity table using this piece of code:
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<AccountActivity> AccountActivity = new ArrayList<AccountActivity>();
When I test this code I get the error:
java.sql.SQLException: Integrity constraint violation -no parent
FK670B7D019607336A table: ACCOUNT_ACTIVITY in statement
Can anybody help me with this problem?
update
I test with this piece of junit code:
public void testAddAccountActivities() {
User user = dummyPersistedUser();
User user2 = dummyPersistedUser();
Account account = getTestUtils().dummyEmptyAccount(user);
Account account2 = getTestUtils().dummyEmptyAccount(user2);
account=accountManager.storeAccount(account);
account2=accountManager.storeAccount(account2);
getTestUtils().fillAccounts(account, account2);
accountManager.storeAccount(account);
accountManager.storeAccount(account2);
assertEquals(2,accountManager.getAccount4Name(account.getName()).getAccountActivity().size());
assertEquals(2,accountManager.getAccount4Name(account2.getName()).getAccountActivity().size());
}
where fillAccounts(account, account2) just inserts some AccountActivities that should be added to the graph.:
AccountActivity aa = new AccountActivity();
aa.setDate(new Date());
aa.setName("test activity");
aa.setAccount(a1);
aa.setValue(value);
aa.setOtherAccount(a2);
account.addAccountActivity(aa)
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinColumn(name ="accountid") // you have several references from AccountActivity to Account. You need to specify the join column in this case.
private List<AccountActivity> AccountActivity = new ArrayList<AccountActivity>();
As a first observation, I think you shouldn't have the variable name the same as the class. So, instead of this private List <AccountActivity> AccountActivity, you can write something like private List <AccountActivity> accountActivity.
I have table /entity called SaleRecord with fields such as
#Entity
public class SaleRecord {
private Long id;
private String type;
private Double amount;
//Getter and Setter and more fields
}
I want to write below query using Criteria
SELECT s.type AS accountName, SUM(s.amount) AS amount
FROM salerecord s
GROUP BY s.type
I have written using plain SQL in Hibernate as (Its working)
String sql = " SELECT s.type AS accountName, SUM(s.amount) AS amount ";
sql += " FROM salerecord s ";
sql += " GROUP BY s.type ";
List<CollectionDO> incomeList = (List<CollectionDO>) getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(CollectionDO.class)).list();
CollectionDO is another POJO class in which I want to populate the result.
But want to write using criteria, So how to write this query and transform result into CollectionDO class.
I have tried following but not working
Criteria criteria = getSession().createCriteria(SaleRecord.class).setResultTransformer(Transformers.aliasToBean(CollectionDO.class));
criteria.setProjection(Projections.property("type"));
criteria.setProjection(Projections.sum("amount"));
criteria.setProjection(Projections.groupProperty("type"));
return (List<CollectionDO>) criteria.list();
CollectionDO.java
public class CollectionDO {
private Double amount;
private String accountName;
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
}
I think it is not able to Transform. as in Criteria column name is "type" but CollectionDO.java has field as "accountName"
Try it as follows (using this version of add to specify the alias name):
Criteria criteria =
getSession()
.createCriteria(SaleRecord.class)
.add(Restrictions.between("date",
reportForm.getFromDate(),
reportForm.getToDate()));
.setProjection(Projections.projectionList()
.add(Projections.property("type"), "accountName")
.add(Projections.sum("amount"))
.add(Projections.groupProperty("type")));
.setResultTransformer(Transformers.aliasToBean(CollectionDO.class))
return (List<CollectionDO>) criteria.list();