I am going to execute a query and return result using com.sun.rowset.CachedRowSetImpl to the users (which are not in my control). I want to make sure that they will not perform any update operation on this object which can make changes in database.
One way could be:
Extend CachedRowSetImpl and override setReadOnly() method so that no user can set it to false.
Is this sufficient? Or there are any other ways using which users can still update database? Should I also override clone() method?
Thanks
I don't see a reason to override clone(), but the simplest way to make sure no updates can happen seems to be to use ResultSet.CONCUR_READ_ONLY.
As you see from the Javadoc, all the mutators throw an SQLException in that case.
So to create a read-only cached row set, the following should suffice:
CachedRowSet rowSetImpl = new CachedRowSetImpl();
rowSetImpl.setConcurrency(ResultSet.CONCUR_READ_ONLY);
rowSetImpl.setCommand("Select * from foo");
rowSetImpl.execute();
classes under com.sun are for internal use they provide reference implementation of APIs and you are not supposed to need access them directly.
It's better to avoid coupling your code to classes present in com.sun, and rather code against javax. or java packages
Moreover, classes in com.sunpackages can be changed or dropped in any version of Java.
Related
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.
I have a situation where i am changing few parameters values of an Object.
UserDetails has around 14 parameters.I am changing the values of few parameters and submitting them from a Form .These values should get updated on the database back-end.
Are there any inbuilt functions to check if any of the values got changed?
Are there any inbuilt functions to say which of the values got changed?
No.
Are there any inbuilt functions to check if any of the values got changed?
No.
However, you can implement your own methods to test these things. An equals method is easy to implement, and indeed many IDEs have "wizards" to generate them. A "what has changed" method is more complicated. The complexity comes in how the method tells the caller what fields have changed, and how the caller can make use of this information.
Alternatively, Apache Commons provides a class called EqualsBuilder that uses reflection, etcetera to compare objects based on their fields.
I also agree with JB Nizet. If you are doing this in an attempt to optimize database updates, you are probably wasting your time. You are probably better off just saving the all of the fields.
Consider this. Unless your front-end caches the old values of the fields read from the database while the user is updating the form (or not), your front end is going to have to re-query the database to find the old value. You would be better off just issuing the UPDATE to update all of the fields than doing a SELECT followed by a conditional UPDATE is something has changed.
Probably you can check this link.. I am not sure this can be done in java. But, you can try with javascript. Please check this link. You can do with EXT.js
handler: function(btn, evt) {
var f = btn.up('form').getForm();
f.submit({
url: '/some-path-on-my-server/save/,
getParams: function(useModelValues) {
var falseVal = false;
var fieldParams = this.form.getValues(falseVal, true, this.submitEmptyText !== falseVal, useModelValues, true);
return Ext.apply({}, fieldParams);
}
});
}
https://www.sencha.com/forum/showthread.php?173867-I-want-to-submit-only-dirty-field-values.
One of my goals is to create an engine that will set values in pojo object from JPA objects dynamically using reflection. One of the matching criteria is, that the field names should match.
I was successfully able to implement this for two pojo objects. But when I tried using JPA objects as one of the object parameter, it didn't work. Based on my research I found out that the method Class.getDeclaredFields() , does not give me the name of the field but the getter/setter method name of member variable for JPA objects.
Can anyone please give me a lead or direction as in where/what should I look to accomplish this task?
JPA providers will often use dynamic proxy classes of your concrete JPA classes, so you have no guarantee of the field names in the proxy. The only guarantee about a proxy is that the methods are the same. Use a debugger to inspect the runtime class of the JPA class instances that you're trying to use and you'll see the problem.
The best you'll be able to do is use reflection to call methods on JPA-returned objects.
All that aside, I don't really see why you'd need to POJO-ify an entity class anyway, since an entity is primarily an annotated... POJO.
One of the matching criteria is, that the field names should match.
I think that this is the root of your problem. There is simply no guarantee that a Java object's field names will match the names of getters and setters ... or anything else. If you make this assumption, you will run into cases where is doesn't work.
The best solution is to simply not use this approach. Make it a requirement that the Pojo classes conform to the JavaBeans spec and rely on the setters to set the properties. This is likely to work more often than making assumptions about (private) field names.
In fact, the state of a generic JPA object implemented using a dynamic proxies could well be held in a hash map. Those fields you can see could simply be constants used for something else.
I'm developing a Scala extension to an existing Java ORM (Ebean). The goal of this project is to add as much type safety as possible to the ORM.
Instead of
Ebean.find(Product.class).fetch("name", "unit").findList()
I would finally like to be able to write something like
(objects of entity[Product] with attributes name and unit) getIt
(note that this is just a very first DSL approach).
The ORM model is already defined as
#Entity
public class {
public String name;
public String unit;
}
In order to achieve type safety at compile time for the attributes in the query, I would need to access them on e.g. a dummy object like (new Product()).name.
I think this is the best way to ensure that only such model members are used that exists on that class, but, at runtime, I need a way to recognize that this variable was accessed. Otherwise I would just call that member name and wouldn't know about this in my query.
Does anybody know a way how to achieve this? Is there a possibility to trace when a variable is accessed and to give that information, at runtime, to any other object?
I already thought about hooking into getters and setters instead of using public members in the model classes, but this would either make the query or the model very ugly. Another problem is that any additional specific methods would have to be added manually for each model.
I would be happy if anyone could suggest possible solutions. Thanks!
If you are willing to define the fields of your model objects as something like the Record Fields, what Emil suggested could work, but if you're building your solution on top of a Java ORM using custom types might be an issue. If you need to track field access I think your best bet will be runtime bytecode instrumentation using a library like CGLib or Javassist. You can pass an instrumented "dummy" object into the body of your function, then track which field was accessed in a thread local. That's how it's done in Squeryl.
You could take a gander at how the Lift folks have implemented Mapper and Records. It allows for type safe queries using companion objects (as well as using raw sql). It does require inheriting traits into your model and the fields are specified as objects and not regular vals. Might be helpfull though. You can find the source for the persistance stuff here.
My Java (JDK6) project uses Spring and JDBCTemplate for all its database access. We recently upgraded from Spring 2.5 to Spring 3 (RC1). The project does not use an ORM like Hibernate nor EJB.
If I need to read a bunch of records, and do some internal processing with them, it seems like there are several (overloaded) methods: query, queryForList and queryForRowSet
What should be the criteria to use one instead of the other? Are there any performance differences? Best practices?
Can you recommend some external references for further research on this topic?
I find that the standard way to access as list is via the query() methods rather than any of the other approaches. The main difference between query and the other methods is that you'll have to implement one of the callback interfaces (either RowMapper, RowCallbackHandler, or ResultSetExtractor) to handle your result set.
A RowMapper is likely what you'll find yourself using most of the time. It's used when each row of the result set corresponds to one object in your list. You only have to implement a single method mapRow where you populate the type of object that goes in your row and return it. Spring also has a BeanPropertyRowMapper which can populate the objects in a list via matching the bean property names to the column names (NB this class is for convenience not performance).
A RowCallbackHandler is more useful when you need your results to be more than just a simple list. You'll have to manage the return object yourself you are using this approach. I usually find myself using this when I need a map structure as my return type (i.e. for grouped data for a tree table or if I'm creating a custom cache based of the primary key).
A ResultSetExtractor is used when you want to control the iteration of the results. You implment a single method extractData that will be the return value of the call to query. I only find myself using this if I have to build some custom data structure that is more complex to build using either of the other callback interfaces.
The queryForList() methods are valuable in that you don't have to implement these callback methods. There are two ways use queryForList. The first is if you're only querying a single column from the database (for example a list of strings) you can use the versions of the method that takes a Class as an argument to automatically give you a list of only objects of those classes.
When calling the other implementations of queryForList() you'll get a list back with each entry being a map of for each column. While this is nice in that you are saved the expense of writing the callback methods, dealing with this data structure is quite unwieldy. You'll find yourself doing a lot of casting since the map's values are of type Object.
I've actually never seen the queryForRowSet methods used in the wild. This will load the entire result of the query into a CachedRowSet object wapped by a Spring SqlRowSet. I see a big downside in using this object in that if you're passing the SqlRowSet around to the other layers of your application, you're coupling those layers to your data access implementation.
You shouldn't see any huge performance differences between any of these calls except as I mentioned with the BeanPropertyRowMapper. If you're working with some complex manipulation of a large result set, you might be able to get some performance gains from writing an optimized ResultSetExtractor for your specific case.
If you want to learn more I would consult the Spring JDBC documentation and the JavaDoc for the classes I've mentioned. You can also take a look at some of the books on the Spring Framework. Though it's a bit dated Java Development with the Spring Framework has a very good section on working with the JDBC framework. Most of all, I would say just try writing some code with each method and see what works best for you.
Since you are in the wonderful Generics land, what you may really want to do is to use SimpleJdbcTemplate and use its query() methods for Lists of objects and queryForObject() for individual objects. Reasoning for this simply is that they're even easier to use than the ones in JdbcTemplate.
One small addition to the excellent answers above: additional methods, like queryForInt, queryForLong, queryForMap, queryForObject, etc. might seem like good options at times if you're running a simple query and expect a single row.
However, if you could get 0 or 1 rows back, the queryForList method is generally easier, otherwise you'd have to catch IncorrectResultSizeDataAccessException. I learned that the hard way.