Strong Coupling between DAOClasses, getting references result in StackOverflow - java

I've been dealing with DAOClasses and I've come accross a serious problem which forces me to reorganize my entire project. However I have no clue on how to solve this problem.
Suppose I have 3 Entities:
public class User {
private int id;
private int cfu;
private String name;
private String surname;
}
public class Project {
private int ID;
private String info;
private Doc doc;
}
public class Doc {
private int id;
private String name;
private String surname;
private ArrayList<Project> projects;
}
Each of this classes has its own DAO and its own table (regarding Doc the table does not keep reference of Projects IDs);
Among their various methods, DAOClasses uses these 2 methods:
read allows to create a element of type T given the ID
readAll allows to recover all elements of type T given a filter
When I call readmethod for DocDAO it is necessary to verify whether Project table contains Doc elements, if so create those elements thanks to ProjectDAO readAll and add them to its ArrayList. But also ProjectDAO need to read a Doc element, which again needs ProjectDAO, causing a circular dependency (therefore a StackOverflow):
DocDAO.read(int id) --calls--> ProjectDAO.readAll(Doc d) --calls-> DocDAO.read(int id) --calls--> ProjectDAO.readAll(Doc d)...
readAll allows to recover all elements of type T given a filter
create allows to create an element of type T in database
how can I decouple these functionality without changing base classes (but just DAO)?
I would skip giving more code since it is very long.

Related

Spring Requestmapping nested complex objects

So I am aware that Spring automatically maps complex objects correctly when provided like:
#PostMapping("/foo")
public String insertObject(#ModelAttribute MyComplexObject bar) {
//do something
return "redirect:baz";
}
given that MyComplexObject has "mappable" attributes, for instance something similar to:
public class MyComplexObject {
private long id;
private String name;
public MyComplexObject(long id, String name) {
this.id = id;
this.name = name;
}
// setters & getters etc
}
However, what if the required object in turn has other complex objects as attributes, e.g. MyComplexObject keeps a list of MyOtherObject which again could reference another one and so on.
A possible solution I found was creating a form object for the required class which translates all attributes to mappable types, but even then it'd be rather tedious and messy depending on complexity.
Every suggestion is much appreciated!

Serialization problems: objects that depend on each other and ArrayLists

I have to serialize a project and it's the first time I use serialization. After getting informed about it, I thought of two possible problems: my classes have atributes which type is another different class that has atributes which type is the first class (explained poorly, but can see in the code) and the fact that I use ArrayLists (which I've read can't be serialized). So I decided to try with a very simplified version of the project:
A group, this containts an ArrayList of Person:
public class Group implements Serializable {
private static final long serialVersionUID = 1L;
private Person leader;
private List<Person> members;
private int number;
public Group(Person leader, int number) {
this.leader = leader;
this.number = number;
this.members = new ArrayList<Person>();
this.members.add(leader);
}
public void addMember(Person p) {
this.members.add(p);
}
public int getNumber() {
return number;
}
}
A person, this contains an ArrayList of Groups:
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private List<Group> groups;
private String name;
public Person(String name) {
this.name = name;
this.groups = new ArrayList<Group>();
}
public Group createGroup(int number) {
Group g = new Group(this, number);
this.groups.add(g);
return g;
}
public void joinGroup(Group g) {
this.groups.add(g);
g.addMember(this);
}
}
And a main method which creates a few groups and people and uses writeObject() to write them into a file, plus another main that uses readObject() to get the objects back (it only uses readObject() and prints them).
I didn't expect this to work for the reasons mentioned above, but it worked perfectly, so I tried to serialize my main project (way more complex) but it didn't work (huge stack trace, simply saying "User", which is the equivalent to person, is not serializable).
Is there any reason for this or any major flaw that I should take into account?
I apologize for not including the two main methods I use, as well as none of the stacktrace or the main project, but I didn't want to make this question extremely long.
my classes have atributes which type is another different class that has atributes which type is the first class (explained poorly, but can see in the code)
Incomprehensible. Both Java and Serialization handle circular dependencies, if that's what you're talking about.
and the fact that I use ArrayLists (which I've read can't be serialized)
Wrong.
simply saying "User", which is the equivalent to person, is not serializable
So User doesn't implement Serializable.
Is there any reason for this or any major flaw that I should take into account?
Make User implement Serializable.Same for any other class that gives you the same message.
You need to read the Object Serialization Specification and the relevant Javadoc, and stop relying on arbitrary Internet rubbish.

Should I create new class or use the existing one

I have the following BO which is already there in the system
public class userBO
{
private String userId;
private String password;
private String firstName;
private String midName;
private String lastName;
private String userType;
private String userDepartment;
private String userAuthority;
//There are some more fields
//getter and setter
}
Now I want to built a dropdown in which I will display Name (firstName + lastName) and will use userId as value. So for that I will make a list of object.
So my question is should I use the existing userBO class or should I create new class something like below
public class userDropDwonBO
{
private String userId;
private String firstName;
private String lastName;
//getter and setter
}
I want to know the answer from Good Architect point of view and also performance point of view, Will there be any better performance if I user new userDropDownBO
userDropDownBO object will definitely use less memory than the above class.
It is because all your members are private intance variable, everytime a constructor is invoked, a set of all private variables will be created on stack and will be initialized to their default values so will consume more memory and initialization time.
But it solely depend on your requirement:
If other fields are required other than these three fields go for the userBO class.
If other fields are unnecessary but no of objects to be created are small in number, go for userBO.
If other fields are unnecessary but no of objects to be created are very large in number, go for userDropDownBO.
Its a personal opinion and rest is your choice.
If you are going to create a new class beside the existing one named UserBO just for the sake of binding it to the JComboBox, that will definitely be a waste of memory and waste of time as well and also you will need to provide an additional logic to map your original object of type UserBO to the the object of type UserDropDownBO.
I would say that your approach maybe applicable in case the BO itself is so complex in dealing with, so that you need to create a separate model to be used in the drop down box.

Is it possible to create "List<SomeClass> obj" with in class name "SomeClass"

class SomeClass{
List<Someclass> list=new ArrayList<SomeClass>();//getter and setters
}
In above class, i have created the List object of same class objects. I want to know the impact of above code and if it is ok to have, I have doubt about its recursion impact ?
The definition of List<T> is not dependent on the structure of T. The information is used by the compiler to only allow adding objects of type T and when you retrieve it automatically convert the return value to the appropriate type. So it is fine to have the List definition in the same class.
The list only contains references to objects of type T. If the complete object were to be allocated and stored as part of the list it would have caused problems.
There is a subtle problem that can cause baffling errors if you do the wrong thing, however. Suppose you try to design a class so it keeps track of all objects in that class:
public class Book {
private static final List<Book> LIBRARY = new ArrayList<>();
private String dewey;
private String isbn;
private String author;
private String title;
public Book(String dewey, String isbn, String author, String title) {
this.dewey = dewey;
this.isbn = isbn;
this.author = author;
this.title = title;
LIBRARY.add(this);
}
public static final List<Book> getLibrary() {
return LIBRARY;
}
}
This class is dangerous, as it allows a reference to this to escape the object before the constructor completes.
The compiler is allowed to reorder the statements in the constructor as it wishes, since they are all independent.
Somebody could have grabbed a copy of LIBRARY before you call the constructor, and a getLibrary call may get access to LIBRARY before the Book object is fully usable. Anything can happen then.
Also, the Composite pattern is similar to your idea.
Yes you can do it no problem.
There is no recursion problem because none of your class instances are created when the List is created - using your class name is only the type of the List.
simply use....
class SimpleClass
{
String var1;
int var2;
double var3;
}
implement all getter and setter for these variable so its will become a datatype for your list object.
now for storing object of this class use SimpleClassMgr
class SimpleClassMgr
{
//this is your list where you will store object
List<Someclass> list=new ArrayList<SomeClass>();
make methods for add().delete(),update(),get() to insert and alter your records
for example
public void add()
{
list.add(simpleclassobject);
}
}
This will create a tree of SomeClass objects. As long as you are OK with having leafs with empty lists it is no problem. You might want to look into having null instead of the list for better memory efficiency.

which java collection object is best when persisting entities using jpa

I am writing an application that parses n number of records each with m number of fields. It is similar to parsing header information out of ip packets. One difference is that the records I'm working with have arrays of fields for optional user comments. My question is, what is the best java.util.collection object for persisting a collection of fields? A set is probably best for what I'm trying to do, because of multiple 'comment' fields that must be unique, but are there any performance or serialization concerns when choosing one collection type over another? Below is psedo-code for what I'm trying to do:
#Entity
public class MyRecord implements Serializable{
#Id
private int id;
private String filename;
#OneToMany(targetEntity=MyField.class, mappedBy="filename")
private Set<MyField> field;
}
public class MyField implements Serializable{
private int id;
private String filename;
private String filePath;
private String fieldName;
private String fieldType;
private String fieldValue;
}
You can take control by yourself for ultimate serialization performance, have a look at the Externalizable interface ( http://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html )
You can use Collection to be prepared for future changes. Maybe someday MyField is allowed to be not unique.

Categories

Resources