Popularity of RowCallbackHandler with JdbcTemplate - java

There are often times when I have need for a RowCallbackHandler, because in processing the result set I don't map each row to a single type, nor each result set to a single data structure. Instead, I may map the majority rows to a specific Java bean, and add the remainder to a list for post-processing.
In these cases, I need a callback with return type void, and the only callback which satisfies this is RowCallbackHandler.
But I don't come across many examples of this, and I have to admit, it's aesthetically nicer to use JDBC and loop through a ResultSet, than to use the clunky Spring callbacks. Is RowCallbackHandler more common than I think? I'm curious what people have to say...
Edit: Some people have asked for my data model. Okay, there's a nodes table and an edges table. If there's an edge between nodes A and B, that edge can signify two things:
A and B are disjoint nodes that interact
A is a member of B, or vice versa
In the second case, I need to add these group nodes to a list. They can't be mapped to a Java bean yet, because they don't signify interactions between disjoint nodes.
Perhaps what I should be doing, instead, is to have 2 queries, one that retrieves case (1), another that retrieves case (2). Case (1) could be mapped to a Java bean, case (2) to a List.
If this is indeed better, then maybe RowCallbackHandler is a bad code smell?

If what you want is to process the whole result set, without returning anything, simply use a ResultSetExtractor<Void> (and one of the JdbcTemplate methods taking it as argument).

You can create a new class that's composed of your bean objects(s), plus the list. Then fill it in a ResultSetExtractor or RowCallbackHandler. Then your return type can change from void to the new class' type.

Related

Can not understand the sequence of method and constructor

According to sequence diagram I should create firstly method "regisreItem(Item item)" with argument "item" as an object. I see my problem that the constructor for "items" is called after the method "regisreItem(Item item)" so that I have nothing to insert into "regisreItem(Item item)" method according sequence diagramm. Or not ?
Sequence diagram
Class diagram
Here is a part of sequence diagram i am interested in
https://drive.google.com/open?id=1eJolWNoN32IubP3iaaXPc_cLM5Es08hK
Here is all my sort of code.
Please provide me some sort of code ho is it possible to implement.
And clarify the beginning of sequence diagram.
Since the operation registerItem expects an item as parameter, the Auctioneer object needs to create it, before calling the operation. That means the Auctioneer has to send a create message, not the Auction (using new Item() as a parameter is not possible in a sequence diagram - and it doesn’t change the creator anyway). i1 and i2 are attributes of the interaction. They can be used as parameters of registerItem.
addBid also expects a bidder. Again the attributes Max and Moritzof the interaction should be used here.
In a real program these interaction attributes would be temporary variables of the Auction::addBid operation or of the Auctioneer. The Auctioneer is probably not supposed to have variables, therefore the registerItem Operation should probably only have generic data types such as stringas parameters.
The Auction is supposed to send messages to i1 and i2, however, since these are attributes of the interaction, the Auction object does not know them. It’s Ok to omit this detail, but it would be better to show how the Auction finds the relevant Item, for example with a findItemByName Operation called on itself.
A better alternative is, to let the Auction send the messages to its own attribute allItems. Then two lifelines would represent the same attribute, but with different objects. A selector could be used to distinguish between the two objects in the slot defined by this attribute (allItems[0], allItems[1], this is optional). The same is applicable to allBids instead of b300EUR and the like.
You can get around the issue of the Item constructor being called after registerItem by using:
registerItem(new Item(...));
and passing in the attributes of Item i1 and i2. That will create the new Item and then it can be added to the auction Item list.
I'm assuming the start of the sequence diagram is the auctioneer creating or opening an already created auction and then adding a list of items that will be used in the auction by repeatedly calling registerItem(new Item(...)); which can then have bids added to them by Max and Moritz via the Auction object

4 Key Value HashMap? Array? Best Approach?

I've got loads of the following to implement.
validateParameter(field_name, field_type, field_validationMessage, visibleBoolean);
Instead of having 50-60 of these in a row, is there some form of nested hashmap/4d array I can use to build it up and loop through them?
Whats the best approach for doing something like that?
Thanks!
EDIT: Was 4 items.
What you could do is create a new Class that holds three values. (The type, the boolean, and name, or the fourth value (you didn't list it)). Then, when creating the HashMap, all you have to do is call the method to get your three values. It may seem like more work, but all you would have to do is create a simple loop to go through all of the values you need. Since I don't know exactly what it is that you're trying to do, all I can do is provide an example of what I'm trying to do. Hope it applies to your problem.
Anyways, creating the Class to hold the three(or four) values you need.
For example,
Class Fields{
String field_name;
Integer field_type;
Boolean validationMessageVisible;
Fields(String name, Integer type, Boolean mv) {
// this.field_name = name;
this.field_type = type;
this.validationMessageVisible = mv;
}
Then put them in a HashMap somewhat like this:
HashMap map = new HashMap<String, Triple>();
map.put(LOCAL STRING FOR NAME OF FIELD, new Field(new Integer(YOUR INTEGER),new Boolean(YOUR BOOLEAN)));
NOTE: This is only going to work as long as these three or four values can all be stored together. For example if you need all of the values to be stored separately for whatever reason it may be, then this won't work. Only if they can be grouped together without it affecting the function of the program, that this will work.
This was a quick brainstorm. Not sure if it will work, but think along these lines and I believe it should work out for you.
You may have to make a few edits, but this should get you in the right direction
P.S. Sorry for it being so wordy, just tried to get as many details out as possible.
The other answer is close but you don't need a key in this case.
Just define a class to contain your three fields. Create a List or array of that class. Loop over the list or array calling the method for each combination.
The approach I'd use is to create a POJO (or some POJOs) to store the values as attributes and validate attribute by attribute.
Since many times you're going to have the same validation per attribute type (e.g. dates and numbers can be validated by range, strings can be validated to ensure they´re not null or empty, etc), you could just iterate on these attributes using reflection (or even better, using annotations).
If you need to validate on the POJO level, you can still reuse these attribute-level validators via composition, while you add more specific validations are you´re going up in the abstraction level (going up means basic attributes -> pojos -> pojos that contain other pojos -> etc).
Passing several basic types as parameters of the same method is not good because the parameters themselves don't tell much and you can easily exchange two parameters of the same type by accident in the method call.

Execute Batch with only one query?

My General Question is: Is it inefficient/bad practice to call preparedStatement.executeBatch() if there's only one query in the batch?
I'm writing a generic method for the Java Helper Library to execute a query. There's a javabean called HelperQuery which holds a list of arrays another javabean called QueryParameter which holds a type (like STRING, BLOB, INT, etc.) and a value. The QueryParameter is used to fill the HelperQuery's PreparedStatement. In many cases, there will be only one array of QueryParameters.
My Specific Question is: Should I handle things differently if there's only one array of QueryParameters or would it be ok to handle things exactly the same regardless of how many QueryParameters there are?
executeBatch is a "super" method from the PreparedStatement's parent Statement which returns an int[] which indicates the success/failure of the executed queries and executeQuery returns a ResultSet. Therefore, it would be a good idea to have the two be totally different method calls so the developer can handle them differently. I would recommend:
An executeQuery(HelperQuery helperQuery) method which will return the associated ResultSet and will only get the first QueryParameters from the HelperQuery (for convenience) and another method which the developer can specify which QueryParameter set to use (either have them specify a number of the QueryParameter list or just pass in the QueryParameters explicitly (I recommend the second of the two)).
An executeBatch(HelperQuery helperQuery method which will return the int[] and the developer can handle that as they wish.
It's always good to give the user (developer in this case) power to do what they want (but also provide for a simple solution for them to perform common tasks).

What's the best pattern to handle a table row datastructure?

The Facts
I have the following datastructure consisting of a table and a list of attributes (simplified):
class Table {
List<Attribute> m_attributes;
}
abstract class Attribute {}
class LongAttribute extends Attribute {}
class StringAttribute extends Attribute {}
class DateAttribute extends Attribute {}
...
Now I want to do different actions with this datastructure:
print it in XML notation
print it in textual form
create an SQL insert statement
create an SQL update statement
initialize it from a SQL result set
First Try
My first attempt was to put all these functionality inside the Attribute, but then the Attribute was overloaded with very different responsibilities.
Alternative
It feels like a visitor pattern could do the job very well instead, but on the other side it looks like overkill for this simple structure.
Question
What's the most elegant way to solve this?
I would look at using a combination of JAXB and Hibernate.
JAXB will let you marshall and unmarshall from XML. By default, properties are converted to elements with the same name as the property, but that can be controlled via #XmlElement and #XmlAttribute annotations.
Hibernate (or JPA) are the standard ways of moving data objects to and from a database.
The Command pattern comes to mind, or a small variation of it.
You have a bunch of classes, each of which is specialized to do a certain thing with your data class. You can keep these classes in a hashmap or some other structure where an external choice can pick one for execution. To do your thing, you call the selected Command's execute() method with your data as an argument.
Edit: Elaboration.
At the bottom level, you need to do something with each attribute of a data row.
This indeed sounds like a case for the Visitor pattern: Visitor simulates a double
dispatch operation, insofar as you are able to combine a variable "victim" object
with a variable "operation" encapsulated in a method.
Your attributes all want to be xml-ed, text-ed, insert-ed updat-ed and initializ-ed.
So you end up with a matrix of 5 x 3 classes to do each of these 5 operations
to each of 3 attribute types. The rest of the machinery of the visitor pattern
will traverse your list of attributes for you and apply the correct visitor for
the operation you chose in the right way for each attribute.
Writing 15 classes plus interface(s) does sound a little heavy. You can do this
and have a very general and flexible solution. On the other hand, in the time
you've spent thinking about a solution, you could have hacked together the code
to it for the currently known structure and crossed your fingers that the shape
of your classes won't change too much too often.
Where I thought of the command pattern was for choosing among a variety of similar
operations. If the operation to be performed came in as a String, perhaps in a
script or configuration file or such, you could then have a mapping from
"xml" -> XmlifierCommand
"text" -> TextPrinterCommand
"serial" -> SerializerCommand
...where each of those Commands would then fire up the appropriate Visitor to do
the job. But as the operation is more likely to be determined in code, you probably
don't need this.
I dunno why you'd store stuff in a database yourself these days instead of just using hibernate, but here's my call:
LongAttribute, DateAttribute, StringAttribute,… all have different internals (i.e. fields specific to them not present in Attribute class), so you cannot create one generic method to serialize them all. Now XML, SQL and plain text all have different properties when serializing to them. There's really no way you can avoid writing O(#subclasses of Attribute #output formats)* different methods of serializing.
Visitor is not a bad pattern for serializing. True, it's a bit overkill if used on non-recursive structures, but a random programmer reading your code will immediately grasp what it is doing.
Now for deserialization (from XML to object, from SQL to object) you need a Factory.
One more hint, for SQL update you probably want to have something that takes old version of the object, new version of the object and creates update query only on the difference between them.
In the end, I used the visitor pattern. Now looking back, it was a good choice.

How do you query object collections in Java (Criteria/SQL-like)?

Suppose you have a collection of a few hundred in-memory objects and you need to query this List to return objects matching some SQL or Criteria like query. For example, you might have a List of Car objects and you want to return all cars made during the 1960s, with a license plate that starts with AZ, ordered by the name of the car model.
I know about JoSQL, has anyone used this, or have any experience with other/homegrown solutions?
Filtering is one way to do this, as discussed in other answers.
Filtering is not scalable though. On the surface time complexity would appear to be O(n) (i.e. already not scalable if the number of objects in the collection will grow), but actually because one or more tests need to be applied to each object depending on the query, time complexity more accurately is O(n t) where t is the number of tests to apply to each object.
So performance will degrade as additional objects are added to the collection, and/or as the number of tests in the query increases.
There is another way to do this, using indexing and set theory.
One approach is to build indexes on the fields within the objects stored in your collection and which you will subsequently test in your query.
Say you have a collection of Car objects and every Car object has a field color. Say your query is the equivalent of "SELECT * FROM cars WHERE Car.color = 'blue'". You could build an index on Car.color, which would basically look like this:
'blue' -> {Car{name=blue_car_1, color='blue'}, Car{name=blue_car_2, color='blue'}}
'red' -> {Car{name=red_car_1, color='red'}, Car{name=red_car_2, color='red'}}
Then given a query WHERE Car.color = 'blue', the set of blue cars could be retrieved in O(1) time complexity. If there were additional tests in your query, you could then test each car in that candidate set to check if it matched the remaining tests in your query. Since the candidate set is likely to be significantly smaller than the entire collection, time complexity is less than O(n) (in the engineering sense, see comments below). Performance does not degrade as much, when additional objects are added to the collection. But this is still not perfect, read on.
Another approach, is what I would refer to as a standing query index. To explain: with conventional iteration and filtering, the collection is iterated and every object is tested to see if it matches the query. So filtering is like running a query over a collection. A standing query index would be the other way around, where the collection is instead run over the query, but only once for each object in the collection, even though the collection could be queried any number of times.
A standing query index would be like registering a query with some sort of intelligent collection, such that as objects are added to and removed from the collection, the collection would automatically test each object against all of the standing queries which have been registered with it. If an object matches a standing query then the collection could add/remove it to/from a set dedicated to storing objects matching that query. Subsequently, objects matching any of the registered queries could be retrieved in O(1) time complexity.
The information above is taken from CQEngine (Collection Query Engine). This basically is a NoSQL query engine for retrieving objects from Java collections using SQL-like queries, without the overhead of iterating through the collection. It is built around the ideas above, plus some more. Disclaimer: I am the author. It's open source and in maven central. If you find it helpful please upvote this answer!
I have used Apache Commons JXPath in a production application. It allows you to apply XPath expressions to graphs of objects in Java.
yes, I know it's an old post, but technologies appear everyday and the answer will change in the time.
I think this is a good problem to solve it with LambdaJ. You can find it here:
http://code.google.com/p/lambdaj/
Here you have an example:
LOOK FOR ACTIVE CUSTOMERS // (Iterable version)
List<Customer> activeCustomers = new ArrayList<Customer>();
for (Customer customer : customers) {
if (customer.isActive()) {
activeCusomers.add(customer);
}
}
LambdaJ version
List<Customer> activeCustomers = select(customers,
having(on(Customer.class).isActive()));
Of course, having this kind of beauty impacts in the performance (a little... an average of 2 times), but can you find a more readable code?
It has many many features, another example could be sorting:
Sort Iterative
List<Person> sortedByAgePersons = new ArrayList<Person>(persons);
Collections.sort(sortedByAgePersons, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
}
});
Sort with lambda
List<Person> sortedByAgePersons = sort(persons, on(Person.class).getAge());
Update: after java 8 you can use out of the box lambda expressions, like:
List<Customer> activeCustomers = customers.stream()
.filter(Customer::isActive)
.collect(Collectors.toList());
Continuing the Comparator theme, you may also want to take a look at the Google Collections API. In particular, they have an interface called Predicate, which serves a similar role to Comparator, in that it is a simple interface that can be used by a filtering method, like Sets.filter. They include a whole bunch of composite predicate implementations, to do ANDs, ORs, etc.
Depending on the size of your data set, it may make more sense to use this approach than a SQL or external relational database approach.
If you need a single concrete match, you can have the class implement Comparator, then create a standalone object with all the hashed fields included and use it to return the index of the match. When you want to find more than one (potentially) object in the collection, you'll have to turn to a library like JoSQL (which has worked well in the trivial cases I've used it for).
In general, I tend to embed Derby into even my small applications, use Hibernate annotations to define my model classes and let Hibernate deal with caching schemes to keep everything fast.
I would use a Comparator that takes a range of years and license plate pattern as input parameters. Then just iterate through your collection and copy the objects that match. You'd likely end up making a whole package of custom Comparators with this approach.
The Comparator option is not bad, especially if you use anonymous classes (so as not to create redundant classes in the project), but eventually when you look at the flow of comparisons, it's pretty much just like looping over the entire collection yourself, specifying exactly the conditions for matching items:
if (Car car : cars) {
if (1959 < car.getYear() && 1970 > car.getYear() &&
car.getLicense().startsWith("AZ")) {
result.add(car);
}
}
Then there's the sorting... that might be a pain in the backside, but luckily there's class Collections and its sort methods, one of which receives a Comparator...

Categories

Resources