Tuesday, 31 May 2011

AOP example in spring

http://veerasundar.com/blog/2009/04/aspect-oriented-programming-using-spring-aop-an-introduction/
http://veerasundar.com/blog/2009/04/aspect-oriented-programming-using-spring-aop-an-introduction-part-2/

http://sivalabs.blogspot.com/2011/01/aspect-oriented-programming-using.html

Spring AOP Example: Profiling method execution time tutorial

http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/

Use cases of Aspect Oriented Programming

http://veerasundar.com/blog/2010/01/use-cases-of-aspect-oriented-programming/

Monday, 30 May 2011

Annotation driven caching with Ehcache and Spring

http://onjavahell.blogspot.com/2009/09/annotation-driven-caching-with-ehcache.html

Monitoring ehcahe with JMX and Spring

http://onjavahell.blogspot.com/2009/09/monitoring-ehcache-with-jmx-and-spring.html

Saturday, 28 May 2011

Java Bean Properties

In the following sections you will learn how to implement Bean properties: Bean appearance and behavior characteristics customizable at design time in builder tools.

Agile Development

http://www.codeinstructions.com/search/label/Agile

Thursday, 26 May 2011

Integrating spring with struts

http://snehaprashant.blogspot.com/2009/05/integrating-spring-with-struts.html

Tuesday, 24 May 2011

init-method and destroy-method attribute in Spring

Sometimes it required to call a (non-static) method in the bean only-once at the ApplicationContext load up, just to initialize the bean components. So you may inject some parameters by setters or constructors, but than you may have some other fields, which have to instantiated from those fields or separately like from some local file.

So for this various approaches are available. See here for these approaches.

Consider the Student service example we saw here. Also note the approach of doing the same thing by using @PostConstruct and @PreDestroy annotations.

Service Bean:

public class StudentService {

String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}


public void initIt() throws Exception {
System.out.println("After properties has been set : " + message);
//do some initialization
}


public void cleanUp() throws Exception {
System.out.println("Cleaned Everyting");
}

}


Bean config file (initMethod.xml):

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>
<!-- our bean here -->
<bean id="studentService" class="com.xxxx.StudentService"
init-method="initIt" destroy-method="cleanUp">
<property name="message" value="property message" />
</bean>

<beans>


Running the program:


public class Runner 
{
public static void main( String[] args )
{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"initMethod.xml"});

StudentService stud =
(StudentService)context.getBean("studentService");

System.out.println(stud );

context.close();
}
}

Initializing the bean by some init method using Spring

Sometimes it required to call a (non-static) method in the bean only-once at the ApplicationContext load up, just to initialize the bean components. So you may inject some parameters by setters or constructors, but than you may have some other fields, which have to instantiated from those fields or separately like from some local file.

So for this various approaches are available. See here for these approaches.

  1. Using init-method attribute. This method is discussed here.
    Pros – doesn't require bean to implement an interface
  2. Implement InitializingBean
    Cons – more invasive than init-method approach
  3. Use JSR-250 @PostConstruct lifecycle annotation. This method is discussed here.
    Pros :

    Useful when using component scanning to autodetect beans.

    Makes it clear that a specific method is to be used for initialisation

    Cons:

    Initialisation no longer centrally specified in configuration. Now scattered throughout code.

Spring – SimpleJdbcTemplate batchUpdate() example

In some cases, you may required to insert a batch of records into the database. If you call a single insert method for every record, the SQL create statement will be compiled repeatedly and causing your system very slow.
In Spring JDBC framework, you can use JdbcTemplate class batchUpdate() template to perform the batch insert operations. With this method, the statement is compiled only once and executed multiple times.
Now consider the function insertBatch() present in your dao, called FlightDao, which takes list of flights as parameter and batch inserts them in database.
Click here to know about this flight database and its corresponding pojo Flight class.
This DAO has simpleJdbcTemplate as its field, on which batchUpdate() function is called. See here for such DAO creation in database. This link will tell you how to use SimpleJdbcTemplate to create dao and use it for insert, update or retrieve operations.
In the dao, initialize the field SimpleJdbcTemplate :
SimpleJdbcTemplate simpleJdbcTemplate = new 
SimpleJdbcTemplate(dataSource);

Now use this field in this function:
 

public void insertBatch(final List<Flight> flightList){
String sql = "INSERT INTO flights_test " +
"(flight_no, carrier, kahase,kahatak) VALUES (?, ?, ?,?)";

List<Object[]> paramList = new ArrayList<Object[]>();

for (Flight flight : flightList) {
paramList.add(new Object[] {flight.getFlightNo(),
flight.getCarrier(), flight .getFrom(), flight.getTo()}
);
}
simpleJdbcTemplate.batchUpdate(sql, parameters);
}


Calling the above function:


Flight flight1 = new Flight("JL-220", "Jet 
Airways"
,"Mumbai","Jaipur");
Flight flight2= new Flight("KL-
202", "Kingfisher","Jaipur","Agra");
Flight flight3= new Flight("AI-220", "Air
India"
,"Agra","Delhi");

List<Flight> flights = new ArrayList<Flight>();
flights.add(flight1);
flights.add(flight2);
flights.add(flight3);

flightDao.insertBatch(flights);

Sunday, 15 May 2011

Application server

An Application Server is any server that supplies additional functionality related to enterprise computing -- for instance, load balancing, database access classes, transaction processing, messaging, and so on.

As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object (or a function in the procedural world).

Such application server clients can include GUIs (graphical user interface) running on a PC, a Web server, or even other application servers. The information traveling back and forth between an application server and its client is not restricted to simple display markup. Instead, the information is program logic. Since the logic takes the form of data and method calls and not static HTML, the client can employ the exposed business logic however it wants.

In most cases, the server exposes this business logic through a component API, such as the EJB (Enterprise JavaBeans) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Moreover, the application server manages its own resources. Such gate-keeping duties include security, transaction processing, and resource pooling, and messaging. Like a Web server, an application server may also employ various scalability and fault-tolerance techniques.

The web server may need to execute an application in response to the user’s request. It may be generating a list of news items, or handling a form submission to a guest book. If the server application is written as a Java Servlet, it will need a place to execute, and this place is typically called a Servlet Engine

EJB Application Servers provide an EJB container, which is the environment that beans will execute in, and this container will manage transactions, thread pools, and other issues as necessary. These application servers are usually stand-alone products, and developers would tie their servlets/JSP pages to the EJB components via remote object access APIs. Depending on the application server, programmers may use CORBA or RMI to talk to their beans, but the baseline standard is to use JNDI to locate and create EJB references as necessary.

WebLogic contains a web server, servlet engine, JSP processor, JMS facility, as well as an EJB container.

An Application Server = Web Server + EJB Container + middle ware services(resources Such gate-keeping duties include security, transaction processing, and resource pooling, and messaging)

Some examples of application server

The Java Enterprise Edition Application servers are:

BEA WebLogic server,Red Hat JBoss, IBM WebSphere Application server, Glassfish Application server.

Difference between a web server and an application server

A Web server serves pages for viewing in web browser, application server provides exposes business logic for client applications through various protocols .Web server exclusively handles http requests.
- A Web Server (otherwise known as an HTTP Server)

An Application Server is any server that supplies additional functionality related to enterprise computing -- for instance, load balancing, database access classes, transaction processing, messaging, and so on.

A Web Server understands and supports only HTTP protocol whereas an Application Server supports HTTP, TCP/IP and many more protocols. Also many more features such as Caches, Clusters, and Load Balancing are there in Application Servers which are not available in Web Servers. We can also Configure Application Servers to work as Web Server.


In short, Application Server is a super set of which Web Server is a sub set.

Lazy loading vs pre-loading beans in spring framework

Spring framework can instantiate and load related Java objects (called beans) according to a given configuration. An XML file can easily be used to define these bindings. Spring framework supports two different types of loading methods; lazy loading and pre-loading respectively managed by BeanFactory and ApplicationContext containers.

Lazy Loading

A bean is loaded only when an instance of that Java class is requested by any other method or a class. org.springframework.beans.factory.BeanFactory (and subclasses) container loads beans lazily. Following code snippet demonstrate lazy loading, concentrate on how "beans.xml" spring configuration file is loaded by BeanFactory container class.
BeanFactory factory = new XmlBeanFactory(
new InputStreamResource(
new FileInputStream("beans.xml"))); // 1
Employee emp = (Employee) factory.getBean("employeeBean"); // 2


Even though "beans.xml" configuration file is loaded with BeanFactory container in line number 1, none of the beans will be instantiated. Instantiation takes place only at line number 2, where bean called "employeeBean" is requested from container. Since the class is instantiated at getBean() method call, time spend to return this method will vary depending on the instantiated object.




Pre-loading


All beans are instantiated as soon as the spring configuration is loaded by a container. org.springframework.context.ApplicationContext container follows pre-loading methodology.

ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml"); // 1
Employee emp = (Employee) context.getBean("employeeBean"); // 2


As all singleton beans are instantiated by container at line number 1, this line will take some considerable time to complete. However line number 2 will return the bean instance immediately since instances are already available inside the container.

Point to note

Decision to choose one from these two methods would depend solely on application specific requirements. Some applications need to load as soon as possible while many others would probably willing to spend more time at startup but serve client requests faster. However some of the beans defined in a configuration may only be used rarely, so instantiating such classes at start up would not be a wise decision. Similarly, some Java instances would be highly resource consuming; leading not to instantiate at start up.

Sunday, 8 May 2011

Eclipse productivity shortcuts

Ctrl + Space : Autocomplete the word to some command or variable in eclipse. See here for more.
Ctrl + 1 : If there is just one more shortcut you remember from this post, let it be this one. The other super awesome, context sensitive shortcut in Eclipse, which is basically Quick Fix. See here for more.
Ctrl + F11 : Reruns the last run configuration that was executed. If you do TDD, then Alt + Shift + X, T followed by Ctrl + F11 is the most standard approach.
Ctrl + Shift + R : Shows the Open Resource dialog. Type to filter, and jump directly between classes. I love this shortcut, and use and abuse it!
Ctrl + Shift + O : Organizes Imports, and gets rid of unused imports.
Ctrl + O : Shows the methods and properties of a class. You can start typing to filter and hit enter to jump to a particular signature / type. Hitting Ctrl + O again toggles showing inherited members. Very useful for jumping between sections in a class, or finding that one method you want to get to.
Ctrl + T : Opens the Type Heirarchy. Shows all super classes as well as sub classes / implementing types in your class path. Very useful for jumping to an implementation class. Can be called from the class type, or even a method signature. Can toggle between Supertype and Subtype heirarchy if you hit Ctrl + T again. Again, you can type and filter once you are in this menu.
Ctrl + / : Comment / Uncomment code. Single or multiple lines, depending on what you have selected. Enuff said.
Alt + Shift + R : One of my most used shortcuts, Rename. It renames anything from variables to methods to even classes, renaming the class files if necessary. Also fixes all references to refer to it by the new name. Can sometimes break if there are compile errors, so watch out when you use it. You can also ask it to fix all textual references as well.
Alt + Shift + M : Extract Method. Super useful method to break up a larger method into smaller chunks. If the code block you have selected does not need to return too many types, and looks reasonable as a separate method, then pulls up  a prompt where you can basically edit the method signature, including return type, method name and order and type of parameters. Very useful
Alt + Shift + C : Only useful when the cursor is on a method signature, but this one allows you to refactor and change the method signature. This includes changing the return type, method name, and the parameters to the method, including order, and default values if you are introducing a new one. Automagically fixes all references to said method.
Alt + Shift + L : Once you have a expression selected (a method call, or whatever), then Alt + Shift + L extracts that to a local variable. It prompts you for the name of the variable, and automatically infers the type as best as it can. Extremely useful shortcut!
Alt + Shift + Up / Down : This one is a useful one. If you hit up, it selects the next biggest code block, down selects the next smallest. Useful in conjunction with refactoring shortcuts like extract local variable, extract method, etc. Useful to know.
Alt + Shift + T : Brings up the Refactor menu. Depending on the context, this will show options like Rename, Move, Extract Interfaces and classes, Change Method Signature, etc. Nice to know, but not one I use very often. The ones I do use have already been listed above.
Alt + Shift + S : Shows the Source menu. This includes menu options like Comment related, and the ever useful Override / Implement Methods, Generate Getters and Setters, and much more. Some of the menu options have direct shortcuts, but a lot of the generate commands don’t, so useful to know.
Alt + Shift + X : Pulls up the Run menu, and shows what key you have to press to run a particular type. Now I generally use this as Alt + Shift + X, followed by T, which basically executes a JUnit Test. Fastest way to run unit tests without leaving the comfort of your keyboard.
Alt + Up / Down : Moves a block of lines up or down. Rather than say, selecting, hitting Ctrl + X and then going to the place and pasting, why not just select all the lines, and use Alt + Up or Down to move them. Automatically handles indentation depending on the block. Very convenient
Ctrl + D :  Nice and Simple, deletes the current line the cursor is on. If you have selected multiple lines, then they are all blown away. Much faster than selecting a line and hitting delete.
UPDATE: Adding in some of the shortcuts that I forgot or were mentioned in the comments for easy finding
Ctrl + L : Jump to a Line number
Ctrl + Shift + T : Display available types. A better version of Ctrl + Shift + R if you are only looking for Java classes
Alt + Shift + Up / Down : Duplicate selected lines above or below. Easier than hitting Ctrl + C followed by Ctrl + V
Ctrl + Alt + H : This one, I didn’t know about. but pulls up the Call heirarchy, showing you all callers and users of the method under the cursor. Super useful, especially if you are refactoring.
Ctrl + Shift + L : Show the list of shortcuts. You can hit it again to go in and edit your shortcuts.

Spring can inject Servlets too!

In this article, I will show you that Spring dependency injection mechanism is not restricted solely to Spring-managed beans, that is Spring can inject its beans in objects created by the new keywords, servlets instantiated in the servlet container, and pretty anything you like. Spring classical mode is to be an object factory. That is, Spring creates anything in your application, using the provided constructor. Yet, some of the objects you use are outer Spring’s perimeter. Two simple examples:

  • servlets are instantiated by the servlet container. As such, they cannot be injected out-of-the-box
  • some business objects are not parameterized in Spring but rather created by your own code with the new keyword

Both these examples show you can’t delegate to Spring every object instantiation.

There was a time when I foolishly thought Spring was a closed container. Either your beans were managed by Spring, or they didn’t: if they were, you could inject them with other Spring-managed beans. If they weren’t, tough luck! Well, this is dead wrong. Spring can inject its beans into pretty much anything provided you’re okay to use AOP.

In order to do this, there are only 2 steps to take:

  • Use AOP
  • Configure object creation interception

Use AOP

It is done in your Spring configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>

<This does the magic />
<context:spring-configured />

<-- These are for classical annotation configuration -->
<context:annotation-config />
<context:component-scan base-package="com.vaani.spring.outcontainer" />

</beans>


You need also configure which aspect engine to use to weave the compiled bytecode. In this case, it is AspectJ, which is the AOP component used by Spring. Since i’m using Maven as my build tool of choice, this is easily done in my POM. Ant users will have to do it in their build.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd"
>
...
<properties>
<spring-version>2.5.6.SEC01</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<configuration>
<complianceLevel>1.5</complianceLevel>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

 


Configure which object creation to intercept


This is done with the @org.springframework.beans.factory.annotation.Configurable annotation on your injectable object.



@Configurable
public class DomainObject {

/** The object to be injected by Spring. */
private Injectable injectable;

public Injectable getInjectable() {

return injectable;
}

@Autowired
public void setInjectable(Injectable injectable) {

this.injectable = injectable;
}
}

Now with only these few lines of configuration (no code!), I’m able to inject Spring-managed beans into my domain object. I leave to you to implement the same with regular servlets (which are much harder to display as unit test).

You can find the Maven project used for this article here. The unit test packaged shows the process described above.

To go further:



Autocomplete text to some function or variable.

Ctrl+Space is one of the two most important keyboard shortcuts that eclipse offers. This one is probably commonly known for autocomplete in eclipse, but not many people know that it is also context sensitive. For example, hitting Ctrl + Space when you are in the middle of typing will show you all members and methods that begin with your text. But hitting Ctrl + Space when you have nothing typed shows you all members and properties available. But the real eclipse masters know that, hitting Ctrl + Space when you type in for or foreach will show you autocomplete options for generating a for loop or for each loop. And if you do it right after you assign something to a collection or a list, it will fill in the loop variables for the for each loop. Autocomplete after typing in test, will allow you to generate the skeleton of a JUnit test case method. Autocomplete after typing in new, generates you a skeleton for a new call, which you can tab through and fill in. So many more uses and use cases for Ctrl + Space that can be found. You can generate / override method signatures in child classes. Just use and abuse it, and you will learn so much.

Eg.
Write sysou and hit Ctrl+Space, following will be generated:
System.out.println();
Similarily various macros are converted to respective words, eg. syserr, ifelse, etc.

JPA support in Application Servers

Since JPA is part of the JEE 5 specification, all application servers need to support JPA. Spring and EJB3 provides full support for JPA, which means one can use DI (Dependency injection )  to direct access JPA EntityManagerFactory and EntityManager instances.

Integrating Spring and Hibernate

The Spring framework provides extensive support for data access through the use of support classes (JdbcDaoSupport, JdbcTemplate etc.), and extensive exception hierarchy to wrap any platform specific SQLException into an exception in the spring exception hierarchy. Additionally Spring framework also provides good support for integrating with ORM technologies like Hibernate and iBatis etc.

 

Prerequisite jars for this example

  • commons-logging-1.1.1.jar
  • hibernate3.jar
  • dom4j-1.6.1.jar
  • ojdbc14.jar
  • commons-collections-3.2.jar
  • log4j-1.2.15.jar
  • commons-dbcp.jar
  • commons-pool.jar
  • spring.jar
  • cglib-nodep-2.1_3.jar
  • antlr-2.7.6.jar
  • jta.jar

Example Code

1. Create the entity bean: The bean here represents a simple stock quote

package com.vaani.entity;

public class StockQuoteBean {
private String quoteId;

private String stockSymbol;

private String name;

public String getQuoteId() {
return quoteId;
}

public void setQuoteId(String quoteId) {
this.quoteId = quoteId;
}

public String getStockSymbol() {
return stockSymbol;
}

public void setStockSymbol(String stockSymbol) {
this.stockSymbol = stockSymbol;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


2. Create a Hibernate Mapping file (hbm) for the entity:


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaani.entity.StockQuoteBean" table="STOCK_QUOTES" lazy="false">
<id name="quoteId" column="quote_id">
<generator class="assigned" />
</id>

<property name="stockSymbol">
<column name="stock_symbol" />
</property>
<property name="name">
<column name="name" />
</property>
</class>
</hibernate-mapping>


The one important thing to note here is that in the declaration, a [lazy="false"] has been added to the mapping for the stockquote bean. The reason for this is that in hibernate 3, lazy initialization is turned on by default. This raises a problem when used with spring's HibernateCallback. The spring HibernateTemplate.execute() by default closes any open sessions upon completion. When used with lazy initialization you may get a LazyInitializationException like the following


org.hibernate.LazyInitializationException: could not initialize proxy - no Session


If you want to use lazy initialization with HibernateCallback, you will have to use this within a transaction context. The javadoc for HibernateTemplate specifies this explicitly.


Note that operations that return an Iterator (i.e. iterate) are supposed
to be used within Spring-driven or JTA-driven transactions (with
HibernateTransactionManager, JtaTransactionManager, or EJB CMT). Else, the
Iterator won't be able to read results from its ResultSet anymore, as the
underlying Hibernate Session will already have been closed.

Lazy loading will also just work with an open Hibernate Session, either within a
transaction or within OpenSessionInViewFilter/Interceptor. Furthermore, some
operations just make sense within transactions, for example: contains, evict,
lock, flush, clear.


3. Create the service class: The service class simply acts as an intermediary between the client and the DAO classes.


package com.vaani.springhibernate;

import com.vaani.entity.StockQuoteBean;
import com.vaani.hibernate.dao.PortfolioDAO;

public class PortfolioService {
private PortfolioDAO portfolioDAO;

public StockQuoteBean getStockQuote(String id) {
StockQuoteBean result = portfolioDAO.getStockQuote(id);
return result;
}

public void updateStockQuote(StockQuoteBean stockQuoteBean) {
portfolioDAO.updateStockQuote(stockQuoteBean);
}

public PortfolioDAO getPortfolioDAO() {
return portfolioDAO;
}

public void setPortfolioDAO(PortfolioDAO portfolioDAO) {
this.portfolioDAO = portfolioDAO;
System.out.println("Setting portfolio DAO to : " + portfolioDAO.getClass());
}

}


4. The DAO interface:


package com.vaani.hibernate.dao;

import com.vaani.entity.StockQuoteBean;

public interface PortfolioDAO {
public StockQuoteBean getStockQuote(String id);
public void updateStockQuote(StockQuoteBean bean);
public StockQuoteBean getStockQuote_hibernateTemplate(String id);
public void updateStockQuote_hibernateTemplate(StockQuoteBean bean);
}


5. The DAO Classes: The DAO classes shows the different ways in which the Hibernate calls can be made using the Spring support classes. There are three primary ways in which these calls can be made


  1. Using the HibernateCallback
  2. Using the HibernateTemplate directly
  3. Using the hibernate native calls using Session
Spring also provides two different ways to create the Data access objects that interact with Hibernate.

  1. Using Composition, with HibernateTemplate
  2. Using Inheritance by extending HibernateDaoSupport

All these methods will be explained when used in the following sections.


Using HibernateTemplate


package com.vaani.hibernate.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import beans.StockQuoteBean;

public class PortfolioDAOTemplate implements PortfolioDAO{
private HibernateTemplate hibernateTemplate;

public PortfolioDAOTemplate() {
System.out.println("Init transaction dao");
}


public StockQuoteBean getStockQuote(final String id) {

HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
return session.load(StockQuoteBean.class, id);
}
};
return (StockQuoteBean) hibernateTemplate.execute(callback);
}

public void updateStockQuote(final StockQuoteBean StockQuoteBean) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
session.saveOrUpdate(StockQuoteBean);
return null;
}
};
hibernateTemplate.execute(callback);

}

public void updateStockQuote_hibernateTemplate(StockQuoteBean StockQuoteBean) {
hibernateTemplate.update(StockQuoteBean);

}
public StockQuoteBean getStockQuote_hibernateTemplate(String id) {
List<StockQuoteBean> transactions = hibernateTemplate.find("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?", id);
return transactions.get(0);
}


public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}


public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}



}

This class shows how to use the HibernateTemplate to make calls to Hibernate. The getStockQuote() and updateStockQuote() methods use HibernateCallback class, note that when using HibernateCallback, it is necessary to either do it in a transactional context or turn off lazy initialization. While the getStockQuote_hibernateTemplate() and updateStockQuote_hibernateTemplate() make calls using hibernateTemplate directly. Also note that the parameters to the getStockQuote(), and updateStockQuote() methods are marked final.

 

Using HibernateDaoSupport

package com.vaani.hibernate.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import beans.StockQuoteBean;

public class PortfolioDAOSupport extends HibernateDaoSupport implements PortfolioDAO {

public void updateStockQuote(StockQuoteBean stockQuoteBean) {
Query query = getSession().createQuery("update beans.StockQuoteBean set stockSymbol=? where quoteId=?");
query.setString(0, stockQuoteBean.getStockSymbol());
query.setString(1, stockQuoteBean.getQuoteId());
query.executeUpdate();
}
public StockQuoteBean getStockQuote(String id) {
Query query = getSession().createQuery("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?");
query.setString(0, id);
List results = query.list();
if(results == null || results.size() == 0) {
throw new RuntimeException("No result");
}
return (StockQuoteBean)results.get(0);
}

public void updateStockQuote_hibernateTemplate(StockQuoteBean StockQuoteBean) {
getHibernateTemplate().update(StockQuoteBean);

}
public StockQuoteBean getStockQuote_hibernateTemplate(String id) {
List<StockQuoteBean> transactions = getHibernateTemplate().find("from beans.StockQuoteBean stockQuoteBean where stockQuoteBean.quoteId=?", id);
return transactions.get(0);
}

}

This class uses HibernateDaoSupport to get instances of HibernateTemplate, and the Hibernate Session. The getStockQuote() and updateStockQuote() in this class make calls to hibernate session directly.

 

6. The application context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
>

<bean id="portfolioDAOTemplate" class="com.vaani.hibernate.dao.PortfolioDAOTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="portfolioDAOSupport" class="com.vaani.hibernate.dao.PortfolioDAOSupport">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>

<bean id="portfolioService" class="com.vaani.springhibernate.PortfolioService">
<property name="portfolioDAO" ref="portfolioDAOSupport"></property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/xe" />
<property name="username" value="appUser" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>stockquote.hbm.xml</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>



  • The SessionFactory is defined with the datasource and mapping-resources. The hibernate specific properties are defined under the hibernateProperties property.
  • The HibernateTemplate uses are reference to the SessionFactory.
  • The HibernateTemplate is used as a reference to the DAO classes.
  • The porfolioService bean in uses a reference to the PortfolioDAO, which can be switched between the dao.PortfolioDAOSupport and dao.PortfolioDAOTemplate beans

7 . The main class

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import com.vaani.entity.StockQuoteBean;


public class SpringHibernateTest {


public static void main(String[] args) {
Resource resource = new FileSystemResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);

PortfolioService portfolioService = (PortfolioService) factory.getBean("portfolioService");

StockQuoteBean result = portfolioService.getStockQuote("123");
System.out.println(result.getStockSymbol());

empResult.setStockSymbol("GOOG");
portfolioService.updateStockQuote(result);
}


}



 

JPA Tutorial Index


But there are various JPA compliant existing like EclipseLink, hibernate, TOPLink.
Seeing the examples:
JPA 2.0 with EclipseLink

Wednesday, 4 May 2011

Quick fix shortcut in eclipse

Ctrl + 1 : If there is just one more shortcut you remember from this post, let it be this one. The other super awesome, context sensitive shortcut in Eclipse, which is basically Quick Fix. If you have an error in a line, Ctrl + 1 will show you potential options to fix it, like importing a class, or adding an argument to a method or fixing the method signature. If you just do a method call which returns something, then you can hit Ctrl + 1 and ask it to assign it to a new local or field variable. You can hit Ctrl + 1 on a parameter to a method and assign it to a field. Ctrl + 1 on a variable can allow you to inline it, and on an assignment, can allow you to split up the declaration and assignment, or convert it to a field, parameter, etc.

Autocomplete shortcut in eclipse

Ctrl + Space : One of the two most important keyboard shortcuts that eclipse offers. This one is probably commonly known for autocomplete in eclipse, but not many people know that it is also context sensitive. For example, hitting Ctrl + Space when you are in the middle of typing will show you all members and methods that begin with your text. But hitting Ctrl + Space when you have nothing typed shows you all members and properties available. But the real eclipse masters know that, hitting Ctrl + Space when you type in for or foreach will show you autocomplete options for generating a for loop or for each loop. And if you do it right after you assign something to a collection or a list, it will fill in the loop variables for the for each loop. Autocomplete after typing in test, will allow you to generate the skeleton of a JUnit test case method. Autocomplete after typing in new, generates you a skeleton for a new call, which you can tab through and fill in. So many more uses and use cases for Ctrl + Space that can be found. You can generate / override method signatures in child classes. Just use and abuse it, and you will learn so much.

Tuesday, 3 May 2011

Redirecting eclipse console output to log file

There is a way to redirect the console text into a log/text file under eclipse. If you are running a web-based application, possibility is that you already have a .log file configured some where. You can simply open this log file and look for messages.

In case of pure java application however, most of the output is showin in the eclipse console unless you configure a redirect.

Pull up the "Debug" or "Run" dialogs where you configured your main class. Select the java application you want to run. If you dont have an entry under "java applications", you might have to create one. On the right hand side of the screen, select the "Common" tab. Check the "File" checkbox and mention a physical path+filename in the input textbox. You are all set! Open the specified file in your fav text editor.

Rowmapper


Eclipse Shortcut : Open a type like class or Interface

Open a type (e.g.: a class, an interface) without clicking through interminable list of packages: Ctrl + Shift + T. If what you want is a Java type, this shortcut will do the trick. Unlike the previous shortcut, this even works when you don’t have the Java source file in your workspace (e.g.: when you’re opening a type from the JDK).

Thank you

Eclipse : commonly used shortcuts


  1) Ctrl + T for finding class even from jar
  2) Ctrl + R for finding any resource (file) including config xml files
  3) Ctrl + 1 for quick fix
  4) Ctrl + Shift + o for organize imports
  5) Ctrl + /  for commenting , uncommenting lines and blocks
  6) Ctrl + Shift + / for commenting ,uncommenting lines with block comment
  7) Ctrl + o for quick outline going quickly to method
  8) Selecting class and pressing F4 to see its Type hierarchy
  9) Alt + right and Alt + left  for going back and forth while editing.
  10) Ctrl + F4 or Ctrl + w  for closing current file
  11) Ctrl+Shirt+W  for closing all files.
  12) Alt + Shift + W for show in package explorer
  13) Ctrl + Shift + Up and down for navigating from member to member (variables and methods)
  14) Ctrl + l go to line
  15) Ctrl + k and Ctrl + Shift +K for find next/previous
  16) select text and press Ctrl + Shift + F for formatting.
  17) Ctrl + F for find , find/replace
  18) Ctrl + D to delete a line
  19) Ctrl + Q for going to last edited place
  20) Ctrl + T for toggling between super type and subtype
  21) Go to other open editors: Ctrl + E.
  22) Move to one problem (i.e.: error, warning) to the next (or previous) in a file: Ctrl + . for next, and Ctrl + , for previous problem
  23) Hop back and forth through the files you have visited: Alt + ← and Alt + →, respectively.
  24) Go to a type declaration: F3
  25) CTRL+Shift+G, which searches the workspace for references to the selected method or variable
  26) Ctrl+Shift+L to view listing
  27) Alt + Shift + j  to add javadoc at any place in java source file.
  28) CTRL+SHIFT+P to find closing brace. place the cursor at opening brace and use this.
  29) Alt+Shift+X, Q  to run Ant build file using keyboard shortcuts.
  30) Ctrl + Shift +F  for Autoformating.

Shortcuts related to source code insertion Eclipse:

Sunday, 1 May 2011

About joinpoint object


Rules for java beans

1) There should be one no argument constructor
2) The class should implement the java.io.Serializable interface
3) There should be getter and setter methods for properties which are declared as private.