I am creating a web application that has a User object and each User object has an ArrayList of objects (Food) that need to be stored into a table in a mySQL database. I want to store the entire ArrayList into a single column. Would it be better to store it as a Json? Or should I just create a table for each User that stores the individual items of the ArrayList? The only problem I have is that the data would edited quite frequently.
EDIT: I have tables for both Users and Food. The idea is that Users add from the Foods from the Food table to their ArrayList and then I want to store that ArrayList in something.
public class User{
private int id;
private String username;
private List<Food> FoodList = new ArrayList<Food>();
}
public class Food{
private int id;
private String name;
private double protein;
private int calories;
...
}
As #ayrton mentions, creating (at least) two tables is a good idea (one for Users and one for Foods).
Definitely don't create a table per User
As #NeplatnyUdaj mentioned, a join table (where you map Foods to Users) might be warranted (or it could be overkill, depending on your needs).
Given the details you've described, JSON is almost certainly not the best approach (this isn't true in all situations, but if you were in such a situation, I'd probably suggest you consider a different type of database).
(Welcome to SO, btw!)
Related
I have a situation to deliver solution for functionality of update one property of many objects. The point is that is possible to update any property. For example
class Book {
private String name;
private Long number;
private LocalDate date;
private SomeEnum name;
private boolean someFlag;
}
Possible is to update only one field at a time, but each field is available to update.
Of course I can create new filter class with each field and send it with given parameter I'd like to update, but I thinking about more elegant solution. More generic.
I have to List get objects by ids from database, update and save all with updated field.
What do You think this could be done. Is possible to create filter class with one generic field depend on what variable user give to update? What is the best practice to do something like that ? What is you experience ?
For example, I have two entities:
#Entity
class A
long made;
long modi;
#Entity
class B extands A
String name;
In this case, will this data be written in Room as single Table or separately?
And another example:
#Entity
Class A
long made;
#Entity
Class B
String name;
#Embedded Class A
In this case - in single table? or separately?
I guess if I use Foreign Key, then it means I will take out data from another table.
But I want data to be written in separate tables, but retrieve them into single ArrayList<<'type'>>.
Because I want to make a single RecyclerView for all datas.
For example, Zoo:
Animal datas:names, ethnic things, color, age........
Personal datas: who works therein like names, age, gender, hair color...........
Zoo's assets: like cars, buildings, lands..........
I want to show all of them into single RecyclerView,
and I use all 3 data in different ArrayList<'Animals'>, ArrayList<'Persons'>, ArrayList<'Assets'>.
I want compare them with made date, modified date and name and then make another ArrayList<'type'>, which will indicate which data I should use from those 3 lists in order and RecyclerView.Adapter will use data from those 3 different lists in made order or modified order or name order.
Sorry for my ignorance of English,but i hope you could understand what i am trying to anwser.
Your question is the entity for the item is not a single class?
if it is,use a Field in single class as a tag, it not well be work?
There are 3 entities (which matches tables):
public class Enterprise{
private long id;
private String name;
private List<Department> departments;
//getters()/setters()
}
public class Department{
private long id;
private String name;
private List<Employee> employees;
//getters()/setters()
}
public class Employee{
private long id;
private String name;
private List<Department> departments;
//getters()/setters()
}
ENTERPRISE---|OneToMany|---DEPARTMENT---|ManyToMany|---EMPLOYEE
Can someone write method on JDBC :
List<Enterprise> findAll();
The connection, statements, queries, etc. can be ignored. The main difficulty is to set all references on the correct objects (for example, to avoid:
enterprise.getDepartments().get(1).getEmployees().get(1).getDepartments() == NULL) .
EXAMPLE (The beginning of method):
List<Enterprise> findAll(){
ResultSet rs = executeQuery(SELECT_ALL_ENTERPRISES);
List<Enterprise> ents = createEnterprises(rs);
.........
Mapping objects to relations is not as easy as it would seem. They have been working on it for decades now, with decent results only in some scenarios. The good news is that the scenarios that work can accommodate most programs.
I suggest that you take a different approach, but first I'll give you an example that will help you understand why I suggest the different approach.
Imagine a person who wants to look up all Departments, which will require a look up of all Employees (as they are part of a Department object). Which will require that for each employee, a list of departments would need to be looked up, which would require that those departments would need a list of employees, which would ....
Perhaps now you get the idea.
So many systems that are structured like yours don't actually return full Employees when looking up departments. They return "Employee identifiers". This allows one to look up all the Departments, but it guarantees that no Employees are going to be returned, preventing an infinite loop. Then, if a person is interested enough, they can use the employee identifiers to look up individual employees, which would of course contain department identifiers.
In short, I recommend that you don't really rebuild the association at this level. I suggest that you build disconnected graphs of the object mesh, such that one can easily navigate the disconnected graph at a later time. Then, if you really must connect them, you will at least have all the data loaded without recursion before you start knitting together references.
Many ORM libraries enable you to define one to many relationships as you described. Sormula can do this. See one to many example.
What I like about Sormula is that if you name the foreign key field on the "many side" the same as the field "one side", then Sormula will deduce the relationship and no annotations are necessary.
I have the following Student class.
public class Student implements Serializable {
private int contestantId;
private String email;
private String password;
private String firstName;
private String lastName;
private String contact;
private String country;
private String countryCode;
private String school;
...
A couple more properties as well as getters and setters...
...
}
My business logic requires that the email and contact number be unique. In the case of a traditional RDMS, I can easily accomplish this by setting the column to UNIQUE and handling any Constraint Exceptions that arises.
Due to our hosting environment (OpenShift doesn't scale the database), I would like to convert my existing application from storing data directly in PostgreSQL to using Infinispan's distributed data grid. However, the main issue I have now is that I cannot figure out how to enforce the UNIQUE constraints for both the email and contact.
Is there a workaround for my problem or do I have to conclude that Infinispan isn't suited for my particular set of requirements?
A datagrid can deliver impressive scalability features because every entry is strictly independent. So it doesn't even make sense to think about a "unique" validation, but there are options by reformulating the problem.
You could use a Cache in which you store your Student data keyed by email, and a second Cache using a key by contact number. Before creating a new entry, you verify it's not existing already. Optionally you could wrap both operations in a transaction, or use putIfAbsent operations. In one cache you store the data, in the second cache you could store a copy (if that's useful) or just a marker token, or the key for the other Cache to easily find Students from different properties.
You could use indexing, so you can search for Students by email / contacts / etc..
You could use a combination. I would likely use indexing to check before attempting to insert, so I have flexibility on accessing any fields, and don't need to duplicate data or make too unusual mappings, but then at insertion time I would still use a transaction with a putIfAbsent operation to make sure a concurrent thread won't attempt to create the same student at the same time.
I am trying to decide which annotation to use. Can you offer your opinion?
What I have now:
#Entity
public class Balance {
#Embedded
private Amount amountAtm;
#Embedded
private Amount amountBranch;
#Embedded
private Amount amountVault;
}
#Embeddable
public Amount {
private BigDecimal debit;
private BigDecimal credit;
}
What I want to change it to:
#Entity
public class Balance {
#ElementCollection
private Map<AmountType, Amount> amounts;
}
public enum AmountType {
ATM, BRANCH, VAULT;
}
The Amount would stay the same.
The reason for this change, is because the amounts inside the balance are conceptually a collection. I either display/change all of them at the same time, or none at all. So, I treat them as a group.
Questions:
Right now the amounts are stored in the same table as the balances (I override column names, this is not shown in the code). However, if I make this change there is NO WAY I can store all this data in one table. I would have to store amounts in a separate table. Is this correct?
Considering that now I will have to make JOINs in SQL, etc. How will this affect the performance? Let's say I am using Oracle 11g and I have 100,000 balance records (and therefore 300,000 amounts). Will I notice the slowdown in the application after the change?
Yes, it's correct.
Impossible to say without testing. I don't see how it could be faster than storing the six fields in the table directly.
What I don't understand is why you're not satisfied with your three fields. If you want to be able to have a Map<AmountType, Amount> getAmounts() method (and the corresponding setter) in your entity, nothing prevents you from adding it and implementing it yourself:
public Map<AmountType, Amount> getAmounts() {
Map<AmountType, Amount> result = new HashMap<AmountType, Amount>(3);
result.put(AmountType.ATM, amountAtm);
result.put(AmountType.BRANCH, amountBranch);
result.put(AmountType.VAULT, amountVault);
return result;
}