I have an order collection. A user can request and cancel the order and receive the order.
There were three statuses here:
- Requested Order
- Canceled Order
- Received Order
I will explain the question with codes. as follows:
Order Model Class:
public class Order {
private String userId;
private String productId;
#OrderStatus
private int status;
#ServerTimestamp
private Date requestedAt;
private Date canceledAt;
private Date receivedAt;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getRequestedAt() {
return requestedAt;
}
public void setRequestedAt(Date requestedAt) {
this.requestedAt = requestedAt;
}
public Date getCanceledAt() {
return canceledAt;
}
public void setCanceledAt(Date canceledAt) {
this.canceledAt = canceledAt;
}
public Date getReceivedAt() {
return receivedAt;
}
public void setReceivedAt(Date receivedAt) {
this.receivedAt = receivedAt;
}
}
Status Enum:
public #interface OrderStatus {
int OS_REQUESTED = 0;
int OS_USER_CANCELED = 1;
int OS_RECEIVED = 2;
}
when the user requests an order:
public static void requestOrder(String userId, String productId) {
Order order = new Order();
order.setUserId(userId);
order.setProductId(productId);
order.setStatus(OrderStatus.OS_REQUESTED);
FirebaseFirestore.getInstance()
.collection("orders")
.add(order);
}
Up to now, the requestedDate has been successfully filled with the server timestamp.
But when the user cancels the order:
public static void cancelOrder(String orderId, #NonNull Order order) {
order.setStatus(OrderStatus.OS_CANCELED);
order.setCanceledAt(new Date()); // how to use FieldValue.serverTimestamp() here?
FirebaseFirestore.getInstance()
.collection("orders")
.document(orderId)
.set(order);
}
Of course I can do it using Update. in that:
public static void cancelOrder(String orderId) {
Map<String, Object> data = new HashMap<>();
data.put("status", OrderStatus.OS_CANCELED);
data.put("canceledAt", FieldValue.serverTimestamp());
FirebaseFirestore.getInstance()
.collection("orders")
.document(orderId)
.update(data);
}
But I want to use POJO/Model.
If i add #ServerTimetamp annotation to the CancelledAt property then it will be filled in when the order is requested. So:
public class Order {
...
#ServerTimestamp
private Date requestedAt;
#ServerTimestamp // <-- will be filled in the order request if added
private Date canceledAt;
#ServerTimestamp
private Date receivedAt;
...
}
If I change its type to Timestamp, how do I assign FieldValue.serverTimestamp()?
Thanks in advance.
If you want to use a server timestamp as the value of a POJO property, you will need to use the #ServerTimetamp annotation. I believe the value should be of Timestamp type.
Related
How can we delete the entire database from the code and not the commands??
For example, model class testapi:
public class testapi {
#Id
private int id;
private String status;
private ArrayList<SpotsStatus> cam_reports;
private long date;
// Constructors
public testapi(int id, String status, ArrayList<SpotsStatus> cam_reports, long date) {
this.id = id;
this.status = status;
this.cam_reports = cam_reports;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public ArrayList<SpotsStatus> getCam_reports() {
return cam_reports;
}
public void setCam_reports(ArrayList<SpotsStatus> cam_reports) {
this.cam_reports = cam_reports;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
}
This is my model class; my repository is:
public interface testRepository extends MongoRepository <testapi, Integer> {
}
In my controller, I have to write code to dump the database, restore a database and to delete the database.
My controller class is:
#Rest Controller
#Request Mapping("/testapi")
public class testapiController {
#Autowired
private testRepository repo;
#Request Mapping(value = "/", method = RequestMethod.GET)
public List<testapi> getAllspots() {
return repo.findAll();
How can I dump? What should be the code?
You can use the solutions discussed here:
Use MongoRepository's deleteAll() for remove all data: testRepository.deleteAll()
Use MongoRepository's dropCollection() and createCollection() for re-creating the whole collection:
testRepository.dropCollection(testapi.class);
testRepository.createCollection(testapi.class);
I have query:
public List<InvoiceItems> findAllBalance(String external_key) throws HibernateException {
return (List<InvoiceItems>) session.createQuery("select SUM(i.amount) as amount, t.record_id from Accounts a, InvoiceItems i, Tenant t WHERE a.record_id = i.account_record_id AND t.record_id=a.tenant_record_id AND a.external_key='"+external_key+"' group by i.tenant_record_id, t.record_id").list();
}
InvoiceItems.java:
package id.co.keriss.consolidate.ee;
import java.util.Date;
import org.jpos.ee.Accounts;
public class InvoiceItems {
private long record_id;
private String id;
private String type;
private String invoice_id;
private Accounts account_record_id;
private Tenant tenant_record_id;
private String description;
private long amount;
private Date created_date;
private String usage_name;
private String plan_name;
private String account_id;
public String getAccount_id() {
return account_id;
}
public void setAccount_id(String account_id) {
this.account_id = account_id;
}
public long getRecord_id() {
return record_id;
}
public void setRecord_id(long record_id) {
this.record_id = record_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getInvoice_id() {
return invoice_id;
}
public void setInvoice_id(String invoice_id) {
this.invoice_id = invoice_id;
}
public Accounts getAccount_record_id() {
return account_record_id;
}
public void setAccount_record_id(Accounts account_record_id) {
this.account_record_id = account_record_id;
}
public Tenant getTenant_record_id() {
return tenant_record_id;
}
public void setTenant_record_id(Tenant tenant_record_id) {
this.tenant_record_id = tenant_record_id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}
public String getUsage_name() {
return usage_name;
}
public void setUsage_name(String usage_name) {
this.usage_name = usage_name;
}
public String getPlan_name() {
return plan_name;
}
public void setPlan_name(String plan_name) {
this.plan_name = plan_name;
}
}
then set to an variable:
List<InvoiceItems> invoiceItems = invoiceItemsDao.findAllBalance(jsonRecv.getString("externalkey"));
I want to get the value from that query, what I try:
LogSystem.info(request, "List : " + invoiceItems.get(0).getId();
I got an error "can't cast to InvoiceItems"
then I try changing from List<InvoiceItems> to just List
get with this :
LogSystem.info(request, "List : " + invoiceItems.get(0);
but the output like this not the value:
[Ljava.lang.Object;#41ea9df8
any advice? final result what i want is calculate amount of tenant
session.createQuery take HQL (Hibernate query language) however I see you use native SQL. Try using createSQLQuery method.
public List<InvoiceItems> findAllBalance(String external_key) throws HibernateException {
Query query = session.createSQLQuery("select SUM(i.amount) as amount, t.record_id from Accounts a, InvoiceItems i, Tenant t WHERE a.record_id = i.account_record_id AND t.record_id=a.tenant_record_id AND a.external_key='"+external_key+"' group by i.tenant_record_id, t.record_id");
query.setResultTransformer(Transformers.aliasToBean(InvoiceItems.class));
List<InvoiceItems> list = query.list();
return list;
}
i have this function to query in hibernate:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id FROM TransactionQR").list();
}
then is success to show the data like this in html:
[2, 3]
but when i add more column in SELECT like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("SELECT id, codeqr FROM TransactionQR").list();
}
the result show like this:
[Ljava.lang.Object;#25026824, [Ljava.lang.Object;#170b75f9]
what is Ljava.lang.Object;#25026824 ? is return object, can i handle it to convert from list to json ?
i have model TransactionQR.java :
public class TransactionQR implements Serializable {
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
the result is i want to show all data from database in list
In second case, since you are selecting two attributes, that is why session.createQuery("").list returns a list of object array(List<Object[]>) . At each index of list you will find an object array. Each array will have two indexes. First index will provide id while the second one would provide codeqr. So, basically you need to iterate over the list. Then fetch each value individually like arr[0], arr[1]..
I've got the following question. I got a little application which saves payments, dates and persons inside a database. Now I got the following POJO class:
public class Payment implements Serializable {
private int id;
private double payment;
private Date datum;
private String usage;
private String category;
private int importance;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPayment() {
return payment;
}
public void setPayment(double payment) {
this.payment = payment;
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getImportance() {
return importance;
}
public void setImportance(int importance) {
this.importance = importance;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ID: ");
sb.append(id);
sb.append("\nPAYMENT: ");
sb.append(payment);
sb.append("\nDATE: ");
sb.append(datum);
sb.append("\nUSAGE: ");
sb.append(usage);
sb.append("\nCATEGORY: ");
sb.append(category);
sb.append("\nIMPORTANCE: ");
sb.append(importance);
return sb.toString();
}
}
So, I got also a class for my dates and persons. The question I've got is the following: Should I create for every Table in my database(in Java the Payment.class , Date.class and Person.class) a own transaction/access class which supports an .saveOrUpdate(), .list() or .delete() function?So maybe I got than a PaymentRansaction.class or an PersonTransaction.class.
Thanks for every help :)
It depends.
Do you have one table with transactions, then one model should be sufficient.
Create methods to create the transactions for you depending on Payment or Person.
BUT
If you have more then 1 table go for multiple classess, each table it's own class.
Gettin the child "sonyTV" in the Firebase Recycler View.
the problem : this child is not a direct child of "Users"
Got the name and the date ,but not "sonyTV"
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder usersViewHolder, int i, #NonNull ALL_USERS all_users) {
usersViewHolder.setName(all_users.getName());
usersViewHolder.setDate(all_users.getDate());
usersViewHolder.setUserSoldItems(all_users.getUserSoldItems());
setUserSoldItems method
public void setUserSoldItems(ALL_USERS.UserSoldItems userSoldItems) {
TextView SonyTvView = mView.findViewById(R.id.showTVsony);
SonyTvView.setText("Sony TV : "+userSoldItems);
}
ALL_USERS class
public class ALL_USERS {
private String name;
private long date;
private UserSoldItems userSoldItems;
public ALL_USERS() {}
public ALL_USERS(String name, long date, UserSoldItems userSoldItems) {
this.name = name;
this.date = date;
this.userSoldItems = userSoldItems;
}
public String getName() { return name; }
public long getDate() { return date; }
public UserSoldItems getUserSoldItems() { return userSoldItems; }
public class UserSoldItems {
private long sonyTV;
public UserSoldItems() {}
public UserSoldItems(long sonyTV) {
this.sonyTV = sonyTV;
}
public long getSonyTV() { return sonyTV; }
}
}
but it gives me null values, although you can check it in my database its not null
This is how i post to child("sonyTV")
users.child(user.getUid()).child("UserSoldItems").child("sonyTV").runTransaction(new Transaction.Handler() {
#NonNull
#Override
public Transaction.Result doTransaction(#NonNull MutableData mutableData) {
Long value = mutableData.getValue(Long.class);
if (value == null) {
mutableData.setValue(0);
}
else {
mutableData.setValue(value + 1);
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
}
});
According to your question:
Dear Alex i have one more thing i cant get the child sonyTV in the RecyclerView ,is it beacause its not a direct child of Users node ??!!!
Now seeing what you are trying to achieve, the simplest solution I can think of is to add an extra property of type UserSoldItems in your User class. So your User class should look like this:
public class ALL_USERS {
private String name;
private long date;
private UserSoldItems userSoldItems;
public ALL_USERS() {}
public ALL_USERS(String name, long date, UserSoldItems userSoldItems) {
this.name = name;
this.date = date;
this.userSoldItems = userSoldItems;
}
public String getName() { return name; }
public long getDate() { return date; }
public UserSoldItems getUserSoldItems { return userSoldItems; }
}
And the UserSoldItems should look like this:
public UserSoldItems {
private long sonyTV;
public UserSoldItems() {}
public UserSoldItems(int sonyTV) {
this.sonyTV = sonyTV;
}
public long getSonyTV() { return sonyTV; }
}
Or even simpler:
public UserSoldItems {
public long sonyTV;
}
And please note, the name of the node should be UserSoldItems and not User Sold Items in order to make it work. So it should not contains any spaces. So when adding data, please add it without any space. In the end, just clear the actual data from the database and add fresh one.
So we introduced a new UserSoldItems level in your JSON tree, so you we can ensure that your Java classes reflect that.