I have a model instance already, it's a basic POJO, how can I populate it (by issuing a SELECT) with the values using dbutils by calling the setters which are named to match the table column names?
So BasicRowProcessor should match, I just don't find the appropiate class/method to call with the object as parameter.
There is only one instance I want to set, not an array.
I'm not sure I understand your question. Some source code would help.
There are lots of libraries that perform ORM. See source forge for some ORM projects. One of them is sormula which I created. For the simplest use of it, see POJO zero-config example.
All you can do is
YourObject result = new BasicRowProcessor().toBean(yourResultSet,YourObject.class);
It will create the instance though. This API is not designed to allow you to modify an already existing object.
If you really need to update the existing object you might implement a YourObject.copy(YourObject obj) method and call it with the result from BasicRowProcessor.toBean but it looks quite ugly.
An other (also ugly) solution would be to implement the BeanProcessor class, implement the BeanProcessor.newInstance(Class) method to return your object, then pass your implementation instance to the BasicRowProcessor instance.
Related
I have seen in many Rest Assured frameworks that we create POJO classes for Serialization & deserialization but let's say we have to automate more than 50-70 APIs thus, creating POJO classes for all seems tedious work so can we deal with JSON objects and data directly? We can get rid of getters and setters by using Lombok annotations but still, we will have to set variables. just curious about what should be the best practice we can follow?
Not sure if I understood correctly. So maybe this answer goes in the totally wrong direction.
If you have lots of Classes and member variables, to streamline handling, you could introduce a level of abstraction.
As an example:
instead of a class and its member variables, you could have a HashMap that stores [variable name] as key, and [variable value] as value.
for multiple object of the same class, instantiate multiple HashMaps
maybe hold all those produced HashMaps in a Collection like a List
maybe even have an 'outer' HashMap, that maps [class name] to [collection]
in the end it might look like this: HashMap[class name -> Collection], Collection contains multiple 'object' HashMaps. Object HashMaps map their [member variable name] to the [meber variable value]
Now, to the JSON part: Google's GSON already has classes in place that do exactly that (object abstraction), so you now have an easy bridge between JSON and Java.
And then you bring it all together and only write ONE serializer and ONE deserializer for ALL classes you wanna handle.
In the end, you still have to put value to POJO or any kinds of object (Map, List, JSON objects...) to create a json payload. I don't like the idea manipulating data directly, it's so rigid.
To make your work less tedious, some techniques can be applied:
Create inner classes if you don't want to create too many POJO classes separatly.
Use Builder pattern (Intellij suggestion or #Builder annotation in lombok) to create POJO instance more straightforward (comparing to basic Setter).
Create POJO instance with default value for each property, then only the property that matters.
Separate the creation of POJO object in other packages, like PersonFactory to build Person instance. It will help make test cleaner.
I'm working on a Maven Plugin and I need to modify one class of an external jar (used during maven execution), to add:
a new field on this class
a getter for the field
some behavior to an existing setter to populate the field
The library code should use my 'new' class, and I want to be able to use the getter to retrieve some additional information.
Instances of this class are created within the library code (I'm not creating them in my code, I just need to access them).
Class is a non-final public class.
Do you know if this feasible and which is the best way to do it? Is it possible to do it with ByteBuddy?
EDIT: I cannot wrap the class, because it's not instantiated in my own code, let me elaborate a bit.
There's a library class named "Parser" that instantiate and populate some "Element" instances. My code looks like:
List<library.Element> elements = new library.Parser(file).parse();
the Parser.parse() method calls "Element.setProperties(List properties)" on each element.
I want to be able to enrich the setProperties method to store the original list of properties (that are lost otherwise)
Thanks
Giulio
At the end I managed to obtain the wanted result with byte-buddy (I don't know if it's the best solution but it works):
instrument library class (library.Element) using 'rebase' strategy to delegate the method 'setProperties' call to an interceptor.
Note: this must be done as the first instruction of the maven plugin execution when library.Element.class is not yet loaded (I didn't want to use a JVM agent)
define the above interceptor as a class that stores the original 'properties' value in a global map (key = identity hash code of the object, value = properties) and then call the original 'setProperties' method of library.Element
change my code to get properties from the map, instead of library.Element getter (I had already a wrapper of this class).
If someone is interested, I can show some code.
Your suggestion sounds a bit hackish, and in general what you want to do would not even be possible without generating sources from the JAR, modifying them, and then repackaging. If I faced this problem, I would consider using a decorator pattern instead. You can create a wrapper which exposes all the methods of your JAR, except it would add one extra field along with a getter and setter.
import com.giulio.old.jar.everything.*;
public class WrapperOfJar {
private String newField;
public String getNewField() { // ... }
public void setNewField() { // ... }
// all getters and setters from current JAR
}
Now your users will see the same interface, plus one new method for your field. This answer assumes that the class in question is not final.
I have defined a data object that maps to the fields stored in DynamoDB table. Whenever I do a load by specifying the class name such as dynamodbmapper.load(Item.class, hashkey). Should I be making the Item class fields final? Conceptually should this object be immutable? I don't want any service code to modify this object.
Yes, if you don't want any service code to modify this object then this seems like a good idea in general. Only viable for you if DynamoDB Java library supports creating instances via costructor args only, no direct field access or setters - it may not (I dunno).
I recently debated with a collegue about how to compare 2 instances of the same java class.
You have an two instances of a complicated object and want to know which attributes differ between those two.
Here is a use case :
You have a user profile with lot of fields and the user submits a new profile, you want to know which fields have changed to be able to display something like "successfully changed your birthday, name, street name ..."
So at the moment, the best solution I have is to write a compare method in the class that takes another object and compare every field one by one, then return the list of fields that are differents.
I was wondering if there was any automatic method (from a external library for example) to do that without having to manually specify each attribute.
Btw, if hibernate has a method which could do this to compare local and database object it could do the trick.
Use reflection, as noted by Guillaume Polet. I'd also put an annotation on the fields that need to be exposed like this. If you don't like the idea of public fields, use getX() methods with annotations. I don't know of any library code to do the comparison; but it wouldn't take long to write.
If you have a method where the input parameter might be the output.
Let's say that we have a save method that generates an autogenerated id that the client might be interested to use after the call to save().
Person
id (autogenerated)
name
... (other fields)
Should you design the method signature like this:
1.
public void save(Person person);
The client call:
personService.save(person);
System.out.println(person.getId());
2.
public Person save(Person person);
The client call:
person = personService.save(person);
System.out.println(person.getId());
We know that in a method call that receives an object the reference to that object is passed so any changes made to the object will be perceived by others as long as they have the same reference. But in the case of remote calls serialization/deserialization occurs so my object reference is a different reference from the remote service object. So even though changes are made there the client won't notice the difference.
At this time I know that the method is not going to be a remote call so I could design it using the first signature. But what if in the future this changes and needs to be called as a remote call.
So my question is:
Should I design my API thinking that the API might be called in the future as a remote call and don't use the object parameter as a way to return a value to the client (2) or should I design my API according to my actual situation which the sevice is not remote (1)?
Thank you
It's OK to do both; have save() return the new ID and have a getId() method. Returning a value from a "setter" (a method that changes state) has lots of precedents - the java Collections API does it all the time, eg Map.remove(Object) returns a boolean.
Fluent Interface
There's another pattern you might want to consider, the Fluent Interface pattern. With a fluent API, you return the object (ie this) from every method you would otherwise return void. This lets the caller "chain up" method calls. With a fluent interface, your code would look like this:
public Person save() {
// do your save stuff
return this;
}
If you want the ID after a save, you'd code this:
save().getId();
Simple! This pattern has been used in lots of existing java code too, notably hibernate as in this java fluent code example
I would recommend using fluent, if nothing else to get the practice using it
Why not do both? Use the second signature, modify person locally, and for the time being, just return a reference to that same person. This way, changing it in the future for whatever needs arise won't change the API, and current users can still use your first approach.
That being said, in general, I am uncomfortable with methods that change their parameters unless that is their sole purpose and they are named and documented to indicate this. From the standpoint of "what is the method doing, and what new information do I get from it," I would probably opt for a signature like:
public ID save(Person);
I would recommend using the first approach since objects are seldom used in isolation. The Person object is usually referenced by other entities such as Employee. If you create a new instance, you're invalidating the whole object graph and believe me, you don't want to mess around with deep copying.
As for the possibility of future RPC's, whatever you'll be using to accomplish this, it will most likely be able to update the ID field after the operation commits.
#CPerkins - Objects are passed by "reference value" to be absolutely correct ;)