Best Practice for Spring MVC form-backing object tree initialization - java

If I have a form-backing object that has a complicated object tree -- say a Person that has a Contact Info object that has an Address object that has a bunch of Strings -- it seems that the object needs to be fully populated with component objects before I can bind to it. So if I'm creating a new Person, I need to make sure it has all the component objects populated off the bat, and if I'm retrieving a Person from the database, I need to make sure that any objects that aren't populated from the database get populated with empty objects.
First question, of course -- am I correct in my assumptions above? It does seem that if I try to bind to person.contactInfo.homeAddress.street and there is no ContactInfo, I get a null pointer exception.
Second, what's the best way to initialize my object. I can think of a couple of approaches. One is to initialize all member objects at declaration:
public class Person {
String name;
ContactInfo contactInfo = new ContactInfo();
//getters, setters, etc.
}
public class ContactInfo {
String phone;
Address homeAddress = new Address();
}
and so forth.
Another approach is to have a PersonFactory that initializes everything (or to have a factory method Person.getInstance that initializes everything).
In the case of retrieving a Person from the database, the first approach will solve the issue (i.e. if this particular person doesn't have an address in the database, the object will still have an Address), but this will mean creating each object twice. Not sure how to handle this otherwise, except to make the DAO explicitly populate everything even if nothing has been retrieved from the database. Or to give the factory a method to go through the object and "fill in" anything that's missing.
Suggestions?

Call it overkill if you like, but what we actually ended up doing was to create a generic factory that will take any object and use reflection to (recursively) find all the null properties and instantiate an object of the correct type. I did this using Apache Commons BeanUtils.
This way you can take an object that you may have gotten from various sources (a DAO, deserialization from XML, whatever), pass it through this factory, and use it as a form-backing object without worrying that something you need for binding may be null.
Admittedly, this means instantiating properties that we may not need for a given form, but in our case that doesn't typically apply.

I would generally make sure objects are fully initialized - it makes using the object that much simplier and avoids you scattering null checks throughout your code.
In the case you give here I'd probably put the initialization in the getter so the child object is only instantiated when it's actually going to be used, ie: when the getter is called and then only if it's null.
In terms of loading from the database with one-to-one relationships I'd normally do the join and load the lot. The performance impact is typically minimal but you should be aware that there may be one.
When it comes to one-to-many relationships I normally go for lazy loading. Hibernate will take of this for you, but if you're rolling your own then you just need a custom implementation of List that calls the appropriate DAO when any of the methods relating to its contents are called.
The one exception to this behavior with one-to-many relationships is when you've got a list of parent objects that you intend to iterate over and for each parent you want to iterate over its children. Obviously the performance would suck because you'd be making a n + 1 calls to the DB when you could actually do it with 2 calls.

I guess you are talking about something like < form:input path="person.contactInfo.homeAddress.street"/> ?
Not clear for me but assuming i'm right :) :
1) Yes, When you write person.contactInfo.homeAddress.street , read person.getContactInfo().getHomeAddress().getStreet(). If ContactInfo or HomeAddress or Street objects are null, invocation of one of their method raises a NullPointException.
2)I usually initializes member objects at declaration, just like in code snippet. Don't see the benefit of factory class to do the job if initialization values are inconditionnal.
I don't clearly see the problem where you are forced to create a Person twice... but i may be tired ;)

I've gone with the Factory method approach (not a fan of using a seperate class for it, to me it makes more sense to have it in a static method so it's all in one place). I have something like -
public static Person getInstanceForContactInfoForm() {
ContactInfo contactInfo = ContactInfo.getInstanceForContactInfoForm();
Person person = new Person(contactInfo);
// set whatever other properties you need for Person
// just enough to 1-render the form and 2-avoid any exceptions
return person;
}
If I'm loading the Person from the database, I have a method in the Person class called something like "initalizeForContactInfoForm" or something. After loading the Person from the database, I'll call this method in the Service layer in the method that is called by the Spring MVC method which returns the Form Backing Object.
I don't think this is a really a convention, it's just an approach I cooked up on my own. I don't really see what any drawbacks are so if somebody disagrees please let me know...

Related

Using direct field access instead of getters in a copy constructor leads to null pointer exception

It must be Java 101 but I can't figure why I can't use direct field access and why I'm forced to use getters in a copy constructor.
I have a bunch of entities. They are organised like a tree. Linked entities are fetched eagerly.
I'm using Hibernate, Lombok and IntelliJ for the debugger.
When I pull one of the entity trees by the root I get a tree of objects. Let's call it "the original". For some reason related to business requirements I need to copy it (let's call this "the copy"). I do it using a copy constructor.
I first wrote a version of the copy constructor using direct field access.
this.someField= original.someField
It didn't work. When I checked the debugger I saw that original.someField (as well as the other fields) were always null.
Nevertheless, it works using the getters.
this.setSomeField(original.getSomeField())
In the debugger, I can see the fields are "set" in original.handler.target. (I've no idea what handler.target is).
Could someone explain to me why a direct field access doesn't work ?
(I'm asking about the technical reason not the philosophical one like "you should always use getters" etc).
I'd also be glad to know what is "handler.target".
Thanks in advance.
What you have encountered is not at all Java 101 problem. Hibernate has a feature called lazyloading, that allows the framework to defer the loading of an (potentially heavy) object to a later point in time, only when it is needed. This comes handy when you are for example loading an account object just to check an active flag, but absolutely do not need all the login history fetched with this account.
Now the "only when it is needed" part: getters.
Hibernate knows that you do need that lazily loadable object when you do call the getter on the parent object in the object graph. Until you do so, the lazily referred object remains null. Direct variable access bypasses the proxylogic that performs this "trick", and that is how you get to the unexpected null values. when the field is accessed via its getter, the proxied code kicks in, loading happens, and you get your object back.
The handler/target/etc are just the extra references you need to hvae due to the proxying. (your account will not have an direct accounthistory variable anymore, but instead an accounthistory_proxy, which in turn will have an accounthistory_real)
As per my understanding you are getting proxy object, once you are calling getter method you will get actual object.Please can you check once you are calling gettter method after that still the fields of object are null ? Try to use . operator after calling getter, I think values in fields should come.

Java Object Clone (additional class member) using Prototype, Builder Pattern

It is not easy to explain my issue.
JPA creates some complex objects for calculations, which are stored in a database.
We decided to set the results in a working copy of this objects.
This means for each object model we created a seperated working copy model file with the same fields but some other LocalDates values and new result fields.
When the calculation was starting the working copies are instantiated.
This approach is not the best i think.
I think of the prototype pattern to clone the object.
There i come to the problem how to add the new fields. How?
Instantion costs and ist creates lots of additionals model class files.
I only think of put the result field in the calculation data models as transient fields.
Maybe inner class or local class?
I also tried to use an interface as data bucket.
But thats not the realy purpose of interfaces and also it works only with many curious trick.
For Unit Tests and user input i think it is the best to use the builder pattern and then tell JPA to store the parent object, or not?
Sorry but my answer was to long for a comment :(
There is big complex object relationship with Lists and Sets One To Many etc. relationship. When i set the result i a new class i cant determine the right object e.g. in a list. So we bild the same structurefor these result and seperated these classes in a package. Maybe it is possible to dont build the structure a second time with also references to the "basic classes". It should be sufficient to reference to each basic class a result class. It would only a little bit more navigation to get values from deeper classes. For a similiar use case there must be a best practise, or? Interfaces or sth. I very dislike the many classes for the result. Is it not possible to clone and add classmember to it for the result or to logical group easier or something like this?
It could be a solution for somebody:
http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2FIWorkingCopy.html
Here you will work with the Eclipse API and create IWorkingCopies.
For the described task toooo much.

Should my objects hold objects or object IDs?

For example should I be doing this
class MyObject {
private Long subObjectId; //such as this
private List<Long> subObjectIds; //or this
//bunch of other fields omitted
}
or
class MyObject {
private SubObject mySubObject; //such as this
private List<SubObject> mySubObjectList; //or this
//bunch of other fields omitted
}
Which one is considered the typical / better approach? If I want to populate something like MyObject from a database, I don't know if my objects should be holding onto IDs or actually populate the objects themselves.
Is it considered bad practice to use the second method but keep the objects null until I need to populate them (a sort of lazy population approach).
The advantage of the first method is that it's quick and easy to populate, but then if I ever wanted to get access to the actual object the ID points to, then I have to query the database and populate some separate SubObject that is decoupled from MyObject.
I hope my question is clear enough. Thank you.
If you are using some ORM like hibernate, then references are the way to go.
If you are not using an ORM, then ids are the way to go. If you start using references without an ORM, you are going to start running into situations where you need a reference but all you are receiving from the database is an id, and the only way to overcome these situations is by writing your own ORM. Don't re-invent that wheel.

Object Relational mapping and performance

I am currently working on a product that works with Hibernate (HQL) and another one that works with JPQL. As much as I like the concept of the mapping from a relational structure (database) to an object (Java class), I am not convinced of the performance.
EXAMPLE:
Java:
public class Person{
private String name;
private int age;
private char sex;
private List<Person> children;
//...
}
I want to get attribute age of a certain Person. A person with 10 children (he has been very busy). With Hibernate or JPQL you would retrieve the person as an object.
HQL:
SELECT p
FROM my.package.Person as p
WHERE p.name = 'Hazaart'
Not only will I be retrieving the other attributes of the person that I don't need, it will also retrieve all the children of that person and their attributes. And they might have children as well and so on... This would mean more tables would be accessed on database level than needed.
Conclusion:
I understand the advantages of Object Relational Mapping. However it would seem that in a lot of cases you will not need every attribute of a certain object. Especially in a complex system. It would seem like the advantages do not nearly justify the performance loss. I've always learned performance should be the main concern.
Can anyone please share their opinion? Maybe I am looking at it the wrong way, maybe I am using it the wrong way...
I'm not familiar with JPQL, but if you set up Hiernate correctly, it will not automatically fetch the children. Instead it will return a proxy list, which will fetch the missing data transparently if it is accessed.
This will also work with simple references to other persistent objects. Hibernate will create a proxy object, containing only the ID, and load the actual data only if it is accessed. ("lazy loading")
This of couse has some limitations (like persistent class hierarchies), but overall works pretty good.
BTW, you should use List<Person> to reference the children. I'm not sure that Hibernate can use a proxy List if you specify a specific implementation.
Update:
In the example above, Hibernate will load the attributes name, age and sex, and will create a List<Person> proxy object that initially contains no data.
Once the application accesses calls any method of the List that requires knowledge of the data, like childen.size() or iterates over the list, the proxy will call Hibernate to read the children objects and populate the List. The cildren objects, being instances of Person, will also contain a proxy List<Person> of their children.
There are some optimizations hibernate might perform in the background, like loading the children for other Person objects at the same time that might be in this session, since it is querying the database anyways. But whether this is done, and to what extend, is configurable per attribute.
You can also tell hibernate to never use lazy-loading for certain references or classes, if you are sure you'll need them later, or if you continue to use the persistent oject once the session is closed.
Be aware that lazy loading will of course fail if the session is no longer active. If for example you load a Person oject, don't access the children List, and close the session, a call to children.size() for example will fail.
IIRC the hibernate session class has method to populate all not-yet-loaded references in a persistent oject, if needed.
Best read the hibernate documentation on how to configure all this.

Object Oriented CRUD program - What is the reason for the OO design?

First of all, I really don't want anyone to do my assignment. I just can't understand the point of the design that I've been asked to implement. One of the methods seems redundant to me and I wonder if someone could shed some light on it.
I have to make a Student class (and subclasses) that has 4 methods: add, delete, update and query. I have to be able to use those methods to update a database. For example the spec for the add() method says:
When this method is called, the database entry for the student is created.
I can understand that we need to have a class here because if the information entered into the GUI is incorrect, then I can have some setter methods in the Student class that will throw an exception that can be caught by the GUI and these can be displayed. So the class is useful to validate the information. Likewise for the update and delete methods.
The thing that is really annoying me is the query() method:
When this method is called, a query is made to the database to retrieve the information and is then printed to the screen.
The Student class is meant to have a query() method (and it has subclasses that inherit this as well). But in order to query the database, we already need to have the instance created, so we'll already have queried the database in order to get the info to create the class, so I could just as well call the toString() method that I've overridden to display the class's data.
I don't see the point of each Student instance having a query() method when it will be redundant for them to use it. Can anyone tell me why this might be useful?
Thanks
Update
Thanks to everyone who answered. I take on board the fact that there should normally be a separation of concerns between the object that holds data and an object that uses or acts upon that data.
My assignment states that the query method should query the database and then display that info to screen. I'm thinking now that if I made this a static method and gave it an argument of the student name or something, then it could actually query the database and then create a Student instance with that info and display it. At least that makes sense to me in that it's only called once, so there's no redundancy.
First off: I'd consider it a very bad design if the Student class is both the value holder and the class that handles loading/storing. It violates the single responsibility principle. I'll assume that this is homework and thus overlook this part for now. The same problem exists with the query() method: it seems to have two responsibilities for no apparent reason.
When writing an object-relational mapper (which you are kind-of doing here), it is often the case that you have "half-restored" objects: Objects which you know should exist in the database and you know their primary key (for example because you have a reference to that object in another object).
In that case it could easily be the case that a query() method that loads the actual data could be useful.
It is not useful and no one would (or should) do it like that. A Student is a persistable entity, but some other component will be responsible for creating, reading, updating or deleting those entities.
Often we see designs that consist of data transfer objects (a value holder, the *entity bean, your Student) and factories that do the CRUD business.
Ask yourself (or the teacher), what do you expect from a query method on Student? I'd expect some sort of query, where a student executes to get more informations for his/her studies.
The purpose for this is that the Student object should not be inextricably tied to a Student record. I should be able to create a new Student object that is empty, and does not have a unique ID yet.
Perhaps I want to create a new Student that doesn't exist yet in the system, I can provide the necessary data, call my add() or insert() method and then this will be persisted. Likewise if I create a Student object and call query() I imagine that the object values will all be replaced with the result of the fetched Student record.
As others here have noted, it is not considered a popular practice for the Value Holder, the entity itself to have the CRUD functionality built within. This doesn't necessarily mean that this is inherently wrong. In OOP, the object should have all functionality associated with itself and it would be more similar to an EJB EntityBean than your typical ORM/Persistence Framewok Bean that is more popular today.
The ORM/Persistence Framework that other answers have stated is known as an Anemic Data Model which certain OOP evangelists like Martin Fowler decry. http://martinfowler.com/bliki/AnemicDomainModel.html

Categories