Java web app sql Result versus List of Objects - java

I seem to keep tripping over this problem. And I can't seem to get a straight answer on the way to approach it.
I have an MVC web app using Java, Tomcat, JSP, MySQL, etc. I'm not using a framework. I have Model Entities representing each table in the database. I'm using DAOs to access the database.
Say you have a Person, a Job, and an Application.
In the View, you need to relate those together to produce a row for a listing.
So far, I've been doing JOINs in the DAO and returning a long SQL Result from the ResultSet using ResultSupport. Then I loop through it in the JSP using a JSTL forEach tag.
I understand this is not the best way to do it.
But then, what is it I need to create in the DAO to pass back each row of data? Do I define a new object with all the field names I need in the view? Is this a DTO? Or do I stuff the original objects in a HashMap and pass back that?
When I ask the database, I assume that doing a join is going to be more efficient than doing a bunch of small queries to return the individual objects.
There must be an accepted pattern for doing this? I would prefer to just follow an accepted solution.
Can someone please point me in the right direction?
Thanks

If you only have one single view, then creating a plain old java object (POJO) works fine. I would create an POJO which contains all the fields you need for a view. Then create a collection (E.G. ArrayList). The collection of POJO's is your Data Transfer Object (DTO).
The database connections are costly. So you want to open the database, get the data and store it your POJO collection. You then either close database connection or return to a pool (if you are using database connection pool). The point is, don't try to create an html display while holding on to a live database connection. Get the data, close the database connection (or return to a pool), then perform your display logic (I.E. the View).
Yes, you want to select all the information at once (do a database join). Same idea, use the database connection and then close it as quickly as possible. You want to avoid multiple open/close, open/close, etc.
Hopefully that helps. You might want to narrow down your question to something more specific. It's really difficult for folks to answer broad architectural questions . Good Luck.

Related

Store session(data) into database

I am working with Java EE and I try to create a web application. I want to store the session data into the database.
The ways that I have considered are:
Create tables to be able to store the data (I did not like this approach, because for every different web app we need to create different tables on database, and I think if you have complex session data this will be painful, to have all the relations etc.).
Create Java class for holding the data, and store the JSON representation to the database. So when you retrieve the session data, you convert it back to Java object, with Jackson for instance.
Store the serialized Java class object, and after deserialize it and use it.
I think that approach 2 and 3 is somehow more generic and don't need too much effort.
Are these good approaches? Is there some other approaches better that that?
What do you suggest me?
You should use Hibernate framework. It will automatically reduce lot of your work.
Refer https://www.javatpoint.com/hibernate-tutorial.

data consistent in a desktop application

I am trying to create a desktop application using eclipse-rcp. In that application, I use a ORM framework to load objects from database and using JFace-databinding to bind these objects to user-interface, so the users can modify data that these objects contains.
since the objects loaded, other users or other client may also work with the same data. so when user want to save the objects back into database, the data these objects contains may differs from data in database, the difference may be caused by my application or caused by others.
should I check against real data in database when I need to save a object that may be not fresh any more?
maybe this is a common problem in ORM, but this is first time I need to deal with ORM.
yes - it's not a bad idea to check against "real" data before saving. you may have a special field - last update timestamp, or increment count.
such approach is called optimistic locking and, since it is very typical it may be supported by ORM's.

passing data from Oracle stored procedures to Java

We're going to write a new web interface for a big system based on Oracle database. All business rules are already coded in PL/SQL stored procedures and we'd like to reuse as much code as possible. We'll write some new stored procedures that will combine the existing business rules and return the final result dataset.
We want to do this on the database level to avoid java-db round trips. The interface layer will be written in Java (we'd like to use GWT), so we need a way of passing data from Oracle stored procedures to Java service side. The data can be e.g. a set of properties of a specific item or a list of items fulfilling certain criteria.
Would anyone recommend a preferable way of doing this?
We're considering one of the 2 following scenarios:
passing objects and lists of objects (DB object types defined on the
schema level)
passing a sys_refcursor
We verified that both approaches are "doable", the question is more about design decision, best practice, possible maintenance problems, flexibility, etc.
I'd appreciate any hints.
I would recommend sticking with a refcursor with well defined keys (agreed on both sides by java devs and pl/sql developers). This is much easier to extend in the future, you can easily convert the refcursor to hashmap and then a hashmap to a POJO using a apache bean utils if needed. I'm working on a big telecom project with many approaches to this issue and refcursor seems to be the best at the end of the day.
In the past I have achieved exactly the same with classic JDBC CallableStatement without any perfomance or maintenance issues. With ORM solutions like Hibernate making persistence much more flexible, you can wrap your solution around Hibernate as achieve in this post. Also see this example if you are not already familiar with the way store procedure and CallableStatement works.
It's been a while since I've done something like that, but the way I remember is that you need to define a view that calls your stored procedure, and you can then easily read the result sets from within java, with the OR-mapper of your choice.
So, this seems close to your scenario 1, which never caused any problems in my experience.
The one thing one needs to be careful is transaction handling: If your stored procedures write data, and you call several of them within a Java EE transaction, you might get into a situation of data inconsistency.

How to structure code when connecting to databases

I am developing a program in Java that I will use for registering data. I store the data in a MySQL database. We have not been making "big" programs in my class that uses databases for storage so what we have done is to make an adapter(We usually name it DBAdapter or something) that creates the connection and returns it. Then we have made a database handler class where all the statements are being executed. Then last the controller + view class have a reference to this handler and call whatever methods available.
However, my question is: When dealing with multiple tables and maybe different model data wouldn't it be good to separate the code in the handler into smaller chunks? Such as private classes or other public classes that a "main" handler could have references too? Example: If you make a system for a company that ship goods you probably would have a database that stores data about the goods. Then you would have a handler that has many select-statments for various stuff. You would also have many employees and then you probably want to separate the select-statements for the goods from the select-statements for the employees.
I also wonder if handler/adapter etc. is the correct terminology?
(This is not homework btw. I am making a program that will be a used for registering data for my iPhone app)
Thank you for your time.
You may want to look into Object-relational mapping libraries for Java, such as OpenJPA or Hibernate. If you'd rather stick to SQL - or like the fine-grained control - you may find Ibatis interesting.
In any case, I wouldn't manage the connections to the DB myself but rely on a connection pool, usually accessed through the DataSource interface.
While ORM may well be where you head, I'd start with
a connection pool
implementing a DAO pattern strategy. If you are using Spring, look at JDBCTemplate - it will be pretty easy to convert this to HibernateTemplate, etc.

How to implement database functionality effectively?

I am developing a Java Desktop Application which uses MySQL database. The DB has 6 tables. Every table, as usual, should allow CRUD (Create, Read, Update and Delete) operations.
I have designed 6*4 = 24 JPanels, 4 JPanels for each tables. Each JPanel have Components to take user input and perform the CRUD operation for which it is designed. For instance, a JPanel3 is designed for Create operation for Table1.
Now I want to know the following:
Q1. Would it be better to write 24 functions, each performing a specific function for a specific table?
Q2. This kind of situation is very normal as every application generally has many tables. So, Are all those applications use this approach of writing each function for each operation for each table?
Q3. As it is a Swing Application and every CRUD operation need the database connection, so Would it be better to make a connection to the database when the user starts the application?
or
Would it be better to make the database connection at the time when user clicks on the "save" or "edit" or "delete" or "create" button?
Q4. Would it be better to refer the connection from an instance variable which is shared by all the 24 functions? or Would it be better to have every function its own Connection?
Any other suggestions are also welcomed.
See this article about the DAO pattern, and then
see the Don't repeat the DAO! article so that you make a generic, reusable DAO.
In short - wrap your database access functionality in a single class and reuse that class from everywhere, thus effectively making your application not explicitly dependent on database operations - only on the DAO class (interface).
A1. No. The design should be guided by the requirements and the domain logic, not by technical considerations. Usually, it does not make sense to have all CRUD operations separately accessible to the user for each and every table. Write functions to perform those operations together that belong together.
A2. No. Nowadays, most applications use an Object/Relational mapper like Hibernate for this kind of thing. But still, there should be application logic on top that executes related operations together.
A3/4. Use a DB connection pool. O/R mappers generally do that automatically.
It would be great if you could join a project with experienced people. Your questions are understandable but... most project already have solutions for this.
I believe there are many more problems than the ones you describe, and you could work for months just to discover the questions ;-)
There are so many suggestions you might need that we can't even start.
Could you consider a framework such as Hibernate?
Although it would be complex for you to learn, in the process (and the recommandations) you would learn a lot about the database layer problems and solutions.
But to answer some of your questions :
Q1 : no, writing 24 functions would be a lot of duplication.
Q2 : certainly not.
Q3 : A database connection typically times out. I suggest to ask for one at appropriate times..., for example in the cases you describe.
Q4 : obtaining a connection should be shared code.
Q1: Could you have fewer JPanels and use a JComboBox to let the user pick wich table to operate on? That will probably save you some code.
Q2: In some way, yes. But see my answer for Q4.
Q3: Do the connection when the user clicks, and leave it open as short time as you need. Database connections takes resources.
Q4: It would be much better if you do all the Database-code and interacting in a single class, called Data Access Object, then is it much easier to change database from MySQL if you would like. See http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/
What does the application do?
I hope you're using more descriptive names for your objects than "JPanel3" and "Table1"?
It would be better if you write no code.
Yes! Just drag and drop.
Data validation, reports and graphs.
Create a complete database program without writing a single line of code.
Common things such as new/edit/delete/search/update.
Use JDeveloper.

Categories