best practice for wicket and db access - java

So I'm writing a simple application and rather then fumble my way through it I wanted to see if someone can give advice on how to set this up.
I have a wicket app, that I'm basically going to do something like a forum app (I've been looking at the wicket guestbook example) however I want to persist these messages to a database. I would like to use a listview (or maybe a repeater) to display the messages. I have created the db (mysql) and tables, and created entity objects for them.
What is a best practice for interfacing wicket with the db. I think I need a loadabledetachablemodel but I'm open to suggestions.
Should I create a class that implements the loadabledetachable interface and do my transactions to the database in that class? Should I do a DAO? and load in the data in the model by calling methods in the DAO? I've been looking at examples and I'm confused on how to do this. I am already learning wicket and the whole JPA stuff so I really don't want to throw something like Spring on this. I need to be able to add/update/delete and I'm just trying to figure out where is the best place to do this.
Any help or guidance is appreciated.

I would suggest you use simplest model like Model or PropertyModel. When rendering the page, load data from database into your model and display the data. When user press update button, read new value from model and then update to the database.
You don't need any LoadableDetachableModel right now since you're still learning the basic part of the wicket framework.
About DAO part, if you just want to focus on learning wicket, create a simple CRUD application without DAO class is okay. You can always refactor those code into DAO classes later anyway. But if you're trying to learn developing a web application, then you should create a DAO class and learn about the concept of Multiple Tier Architecture.

There is a pretty good explanation in German - but the code is in English:
The solution extends the LoadableDetachableModel to hold an EntityFacade by storing the classname and performing the lookup on load().
I think the example from here:
http://hotchpotch-blog.de/2012/10/09/wrapping-eines-ejb-in-ein-loadabledetachablemodel/
can be extended to something like this (not production ready):
public class EjbModel extends LoadableDetachableModel {
/**
* Get the name of the EJBInterface type suitable for lookup.
*
*/
protected String ejbName;
public EjbModel(EJBInterface bean){
//store the bean so it will get detached
super(bean)
ejbName = bean.getSimpleName() + "Facade"; //not sure if + "Facade" is needed
}
#Override
protected EJBInterface load() {
EJBInterface result = null;
try {
InitialContext ctx = new InitialContext();
result = (EJBInterface ) ctx.lookup("java:module/" + ejbName);
} catch (NamingException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Error at JNDI lookup for " + getEjbName(), ex);
}
return result;
}
}

Related

How to select JDBC / JPA implementations at run time?

I'm writing an application meant to manage a database using both JDBC and JPA for an exam. I would like the user to select once at the beginning the API to use so that all the application will use the selected API (whether it be JPA or JDBC).
For the moment I decided to use this approach:
I created an interface for each DAO class (e.g. interface UserDAO) with all needed method declarations.
I created two classes for each DAO distinguished by the API used (e.g UserDAOImplJDBC and UserDAOImplJPA). Both of them implement the interface (in our case, UserDAO).
I created a third class (e.g. UserDAOImpl) that extends the JDBC implementation class. In all my code I've been always using this class. When I wanted to switch to the JPA I just had to change in all DAO classes the extends ***ImplDAOJDBC to extends ***ImplDAOJPA.
Now, as I'm starting having many DAO classes it's starting being complicate to modify the code each time.
Is there a way to change all extends faster?
I was considering adding an option in the first screen (for example a radioGroup) to select JDBC or JPA. But yet I have no idea how to make it work without having to restructure all code. Any idea?
Use a factory to get the appropriate DAO, every time you need one:
public class UserDaoFactory {
public UserDao create() {
if (SomeSharedSingleton.getInstance().getPersistenceOption() == JDBC) {
return new UserDAOImplJDBC();
}
else {
return new UserDAOImplJPA();
}
}
}
That's a classic OO pattern.
That said, I hope you realize that what you're doing there should really never be done in a real application:
there's no reason to do the exact same thing in two different ways
the persistence model of JPA and JDBC is extremely different: JPA entities are managed by the JPA engine, so every change to JPA entities is transparently made persistent. That's not the case with JDBC, where the data you get from the database is detached. So the way to implement business logic is very different between JPA and JDBC: you typically never need to save any change when using JPA.
You got 1 and 2 right, but 3 completely wrong.
Instead of having Impl extending one of the other implementations, choose which implementation to initialize using a utility method, for example. That's assuming you don't use Dependency Injection framework such as Spring.
UserDAO dao = DBUtils.getUserDAO();
public class DBUtils {
public static boolean shouldUseJdbc() {
// Decide on some configuration what should you use
}
public static UserDAO getUserDAO() {
if (shouldUseJdbc()) {
return new UserDAOImplJDBC();
}
else {
return new UserDAOImplJPA();
}
}
}
This is still jus an examle, as your DAOs don't need to be instantiated each time, but actually should be singletons.

Java OOP in MVC Legacy

My question, overall, is in regards to best practices and efficiency. Today, my teacher and I had a discussion about OOP in MVC Legacy. We were going through a previous project of mine and the question is "What's the point?"
The way my project (and all my projects) are structured, it doesn't make sense to me. Here is an example followed by my code.
Controller- Gets the String values from the form/View and passes them to the Service class. Single Responsibility would state that this is all it is responsible for, not creating an object to pass, but creating a < Map < String,Object >> would be totally fine from my understanding.
Service Class- Following best practices/single responsibility these methods are not supposed to do anything other than call the requested method/pass values.
DAO- The DAO is supposed to be responsible for transferring all data/objects into usable form for the D.B accessor and to return them as such.
But why build an object just to tear it down? Especially when you could just pass a list of values down as a Map< String,Object > so all the values and columns match up?
The following are code snippets to help illustrate my question:
Service Class:
public class ClientService {
private Client_SQL_DAO_Strategy dao;
public ClientService(Client_SQL_DAO_Strategy dao){
setDaoStrategy(dao);
}
public void sendClientToStorage(Client client) throws SQLException, ClassNotFoundException{
dao.sendClientToDatabase(client);
}
public void updateClient(List values) throws SQLException, ClassNotFoundException {
dao.updateClient(values);
}
}
DAO
public void saveClient(Client client) throws ClassNotFoundException, SQLException {
List columns = new ArrayList<>();
columns.add("Last_Name");
columns.add("First_Name");
columns.add("Business_Name");
columns.add("Phone");
List<Object> values = new ArrayList<>();
values.add(client.getClientLastName());
values.add(client.getClientFirstName());
values.add(client.getClientBusiness());
values.add(client.getClientPhone());
accessor.createRecord(TABLE_NAME, columns, values);
}
public void updateClient(List listOfValues) throws ClassNotFoundException, SQLException{
List<Object> columns = new ArrayList<>();
columns.add("Last_Name");
columns.add("First_Name");
columns.add("Business_Name");
columns.add("Phone");
int primaryKey = Integer.valueOf(listOfValues.get(0).toString());
accessor.updateRecord(TABLE_NAME, columns, listOfValues, PK_COLUMN, primaryKey);
}
Comparing the two methods provided in the DAO which approach makes more sense? Creating the Client to tear it down or passing associated values and columns to the accessor? This Map< String,Object > seems ideal for both methods.
And yes, I'm aware of the newer techniques as well, but at the current time in the semester Legacy is the lesson of the week.
Spring MVC implements the Model-View-Controller design pattern.
The responsibility of the Controller is to obtain/create/populate the Model and prepare the environment for the View.
The View is responsible for displaying Model data, in Spring MVC usually through JSP, but you can also specify View classes which do things like render Excel or PDF, for example.
The Model implements the domain logic. Depending on your implementation, this could be a "view model" containing only logic for the front end, or it can contain the real business rules. It should be a real class. Do not EVER use Map<String, Object>. Such usage of maps sacrifices type safety and is not OOP.
The Service class is like a controller class for external service coordination, like persistence, email, payment, etc.
The DAO class is a service provider just for persistence. It translates the object representation to database operations. This layer can be replaced by an ORM. Do not pass around Map<String, Object>!
If the only external service used by your app is persistence, you can avoid separate Service and DAO classes, and defer separation until you require more services.
For more information about this type of object modeling, check out Domain Driven Design.

Fetching selected Data

I am new to spring I want to get all the data whose id=given by me. Can any one tell me how can I do That
#Override
public Collection<Device> listDevice() {
Collection<Device> deviceCollection=new ArrayList<>();
Iterable<Device> deviceIterable=deviceRepository.findAll();
for(Device d:deviceIterable){
deviceCollection.add(d);
}
return deviceCollection;
}
This is giving me all the data But I want data having id
long id=device.getManufacturer_id();
please tell how to do that
Instead of Repository#findAll, use Repository#findById(ID primaryKey).
Check this documentation:
http://docs.spring.io/spring-data/jpa/docs/1.0.0.M1/reference/html/
Instead try SpringDao library for JDBC related operations in Spring framework. It gives lots of pre built classes for requirements like your like NamedParameterJdbcDaoSupport, JdbcDaoSupport etc.
Will find host of examples of that on the net. just google it.

Best practice of managing database connections in a web app

I am developing a MongoDB app with Java but I think this question related to datastore connections for web apps in general.
I like to structure all web apps with four top-level packages which are called (which I think will be self explanatory):
Controller
Model
Dao
Util
Ideally I would like to have a class in the Dao package that handles all the connections details.
So far I have created a class that looks like this:
public class Dao {
public static Mongo mongo;
public static DB database;
public static DB getDB() throws UnknownHostException, MongoException{
mongo = new Mongo("localhost");
database = mongo.getDB("mydb");
return database;
}
public static void closeMongo(){
mongo.close();
}
}
I use it in my code with something like this
public static void someMethod(String someData){
try {
DB db = Dao.getDB();
DBCollection rColl = db.getCollection("mycollection");
// perform some database operations
Dao.closeMongo();
} catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace();
}
}
This seems to work fine, but I'd be curious to know what people think is the "best" way to handle this issue, if there is such a thing.
The rule of thumb when connecting to relational database server is to have a pool. For example if you connect to an oracle database using a pool gives you some performance benefits both in terms of connection setup time and sql parsing time (if you are using bind variables). Other relational database may vary but my opinion is that a pool is a good pattern even for some other reason (eg. you may want to limit the maximum number of connections with your db user). You are using MongoDB so the first thing to check is how MongoDB handles connections, how expnsive is creating a connection,etc. I suggest to use/build a class that can implements a pool logic because it gives you the flexibility you may need in the future. Looking at your code it seems that you api
DB db=Dao.getDB();
should be paired with:
Dao.closeDB(DB db);
So you have a chance to really close the connection or to reuse it without affecting the Dao code. with these two methods can switch the way you manage connections without recoding the Dao objects
I would suggest you can write a java class to establish the connection with the database.
The arguments to the method should be the database name, password, host port and other necessary credentials.
You can always call the parametrized constructor everywhere where there is a need to establish database connectivity. This can be a model.
I got a 'nice' solution from this article. http://www.lennartkoopmann.net/post/722935345
Edit Since that link is dead, here's one from waybackmachine.org
http://web.archive.org/web/20120810083748/http://www.lennartkoopmann.net/post/722935345
Main Idea
What I found interesting was the use of a static synchronised method that returns an instance of the static class and its variables. Most professional devs probably find this obvious. I found this to be a useful pattern for managing the db connections.
Pooling
Mongo does automatic connection pooling so the key is to use just one connection to the datastore and let it handle its own pooling.
I think it is better if you call a method inside DAO to get data from database as well. If you do it in this way, say your database got changed. Then you have to edit many classes if you get data directly calling db queries. So if you separate db calling methods inside the DAO class itself and call that method to get data it is better.

JSP MVC Model 2 Architecture Question

I want to develop a web application and I have access this API. In the API there are methods that allow you to get the userId of the current user via context objects. Maybe I'm overthinking this, but I'm very confused as to where to put my CurrentUserId() method. Does that method go in the controller or the model? I was thinking it goes in the model, but it seems redundant to write a property called "getUserId" to return a string called getUserId().toString(). Is this normal and I'm overthinking or am I correct? My co-worker told me to put the logic in the view, but from everything I've read you never put java code or scriplets in the view. I hope this makes sense.
Also here's a method I wrote to return the userId as a string
protected String CurrentUserId(HttpServletRequest request)
{
ContextManager ctxMgr = ContextManagerFactory.getInstance();
Context ctx = ctxMgr.setContext(HttpServletRequest request);
Id userID = ctx.getUserId();
return userID.toString();
}
It should go to Controller.
Create a utility class having this method as static
Because here HttpServletRequest is this model specific(jsp,servlet) , suppose tomorrow if you want to apply the same model to your desktop application then it would fail so better place is controller.

Categories