Thursday, September 20, 2012
JAXBcontext inside servlet context
Tuesday, July 10, 2012
Jersey ApacheHttpClient with connection pooling
When using the jersey client. Make use you use ApacheHttpClient instead of jersey client.
http://jersey.java.net/nonav/apidocs/1.2/contribs/jersey-apache-client/com/sun/jersey/client/apache/ApacheHttpClient.html
This is the standard way you get the client
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setConnectionTimeout(connectTimeout);
connectionManager.getParams().setSoTimeout(readTimeout);
connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionsPerHost);
HttpClient httpClient = new HttpClient(connectionManager);
ApacheHttpClientHandler httpClientHandler = new ApacheHttpClientHandler(httpClient);
contentServerClient = new ApacheHttpClient(httpClientHandler);
contentServerClient.setConnectTimeout(connectTimeout);
contentServerClient.setReadTimeout(readTimeout);
once you get the client get the web resource from the uri
WebResource resource = getContentServerClient().resource(contentServerUrl).path("streets").path("6708NE");
try {
Street street = resource.get(Street.class);
} catch (UniformInterfaceException e) {
throw new NoContentFoundException("Can't locate street for Id " + kaniId);
}
Wednesday, August 3, 2011
SOAP web service with custom headers - SOAP Action
String operation = "HelloThere"; // "FetchMerchants"; // could
// also be
String destination = "http://localhost/interfaces/reseller/BusinessLayer/ResellerWS.asmx";
// First create the connection
SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory
.newInstance();
SOAPConnection connection = soapConnFactory.createConnection();
// Next, create the actual message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("xsd",
"http://www.w3.org/2001/XMLSchema");
envelope.addNamespaceDeclaration("xsi",
"http://www.w3.org/2001/XMLSchema-instance");
// This method demonstrates how to set HTTP and SOAP headers.
// setOptionalHeaders(message, envelope);
envelope.removeNamespaceDeclaration("soapenc");
// Create and populate the body
SOAPBody body = envelope.getBody();
// Create the main element and namespace
SOAPElement bodyElement = body.addChildElement(envelope.createName(
operation, "", "http://tempuri.org/"));
// Add parameters
bodyElement.addChildElement("mid").addTextNode("3");// 41221");
// envelope.getHeader().detachNode();
SOAPHeader header = envelope.getHeader(); // xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
// QName hName = envelope.createQName("Header", "");
// header.setElementQName(hName);
// Hearder - Authentication info
Name headerElementName = envelope.createName("AuthHeader", "",
"http://tempuri.org/");
SOAPHeaderElement headerElement = header
.addHeaderElement(headerElementName);
// headerElement.setMustUnderstand(false);
// headerElement.addNamespaceDeclaration("soap",
// "http://schemas.xmlsoap.org/soap/envelope/");
SOAPElement sessionId = headerElement.addChildElement("UID");
sessionId.addTextNode("380");
// Username Password
SOAPElement auth = headerElement.addChildElement("Authorization");
auth.addTextNode("Basic " + "UserIndustries:Authnet101");
// remove SOAPAction from HTTP Header
MimeHeaders mimeHeaders = message.getMimeHeaders();
mimeHeaders.addHeader("SOAPAction", "http://tempuri.org/"
+ operation);
// Save the message
message.saveChanges();
// Send the message and get the reply
SOAPMessage reply = connection.call(message, destination);
// remove soapAction from the header
// Retrieve the result - no error checking is done: BAD!
soapPart = reply.getSOAPPart();
envelope = soapPart.getEnvelope();
body = envelope.getBody();
Iterator iter = body.getChildElements();
Node resultOuter = ((Node) iter.next()).getFirstChild();
Node result = resultOuter.getFirstChild();
System.out.println("result : " + result.toString());
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SOAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Wednesday, December 15, 2010
Profiling with YourKit
tar xjvf yjp-9.0.7-linux.tar.bz2
If you want to profile a web application running on say Tomcat,
1. You should upload the yourkit to one of the accessible folders on the server.
2. your catalina.sh or setenv.sh should have:
# enable YourKit java profiling.
CATALINA_OPTS_YJP="-agentpath:/home/tom8080/yjp-9.0.9/bin/linux-x86-64/libyjpagent.so"
When you start the application, in the logs yjp will log a line saying on which port it is listening. Use that port when connecting from the local box UI.
Start the application
Connect and then start profiling. End and save to get the snapshot.
Friday, December 10, 2010
Cisco anyconnect vpn client on ubuntu 10
cd /usr/local
sudo mkdir firefox
cd firefox
sudo ln -s /usr/lib32/libnss3.so
sudo ln -s /usr/lib32/libplc4.so
sudo ln -s /usr/lib32/libnspr4.so
sudo ln -s /usr/lib32/libsmime3.so
sudo ln -s /usr/lib32/nss/libsoftokn3.so
sudo ldconfig
sudo sh ./vpn_install.sh
Wednesday, December 8, 2010
Adding new monitor resolution to Ubuntu
Go to /etc/X11/
vi the file xorg.conf
my ubuntu did had the resolution - 1920x1080 so I had to add this file:
# xorg.conf (X.Org X Window System server configuration file)
#
# This file was generated by dexconf, the Debian X Configuration tool, using
# values from the debconf database.
#
# Edit this file with caution, and see the xorg.conf manual page.
# (Type "man xorg.conf" at the shell prompt.)
#
# This file is automatically updated on xserver-xorg package upgrades *only*
# if it has not been modified since the last upgrade of the xserver-xorg
# package.
#
# Note that some configuration settings that could be done previously
# in this file, now are automatically configured by the server and settings
# here are ignored.
#
# If you have edited this file but would like it to be automatically updated
# again, run the following command:
# sudo dpkg-reconfigure -phigh xserver-xorg
Section "Monitor"
Identifier "Configured Monitor"
EndSection
Section "Screen"
Identifier "Default Screen"
Monitor "Configured Monitor"
Device "Configured Video Device"
SubSection "Display"
Depth 24
Modes "1920x1080"
EndSubSection
EndSection
Section "Device"
Identifier "Configured Video Device"
EndSection
-- Installing Intel HD graphics card --
You need to install drivers for the graphics card. Here are the steps for Intel HD graphics card:
sudo add-apt-repository ppa:glasen/intel-driver
sudo apt-get update && sudo apt-get upgrade
-- Change grub ----
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash i915.modeset=1"
in /etc/default/grub
run update-grub after making these changes & reboot.
-- run --
Run the below command:
cvt 1920 1080 60
This should output correct line to be used in xorg.conf
Here is the out put:
# 1920x1080 59.96 Hz (CVT 2.07M9) hsync: 67.16 kHz; pclk: 173.00 MHz
Modeline "1920x1080_60.00" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync
$ xrandr --newmode "1920x1080_60.00" 173.00 1920 2048 2248 2576 1080 1083 1088 1120 -hsync +vsync
$ xrandr --addmode VGA1 1920x1080_60.00
Wednesday, October 20, 2010
Thrift Installation
Thrift
Thrift is a framework for cross-language services development. It has less documentation and the documentation you will find is for implementing the services. Data is transferred over http in binary form. We can use the serialization it does for caching. So instead of passing it over the wire we will put the serialized data in our cachepage.
How Thrift works is :
Create thrift definition files.
Compile the files to get client and server codes.
Compiled code will have methods to get or set the serialized object.
Languages Supported
* C++
* C#
* Cocoa
* Erlang
* Haskell
* Java
* OCaml
* Perl
* PHP
* Python
* Ruby
* Smalltalk
Compare this with ProtocolBuffers, which supports : C++, Java, Python
You will find interesting comparison with protoBufs at this page : http://stuartsierra.com/2008/07/10/thrift-vs-protocol-buffers
Serialization
Can serialize from and to binary or JSON . http://wiki.apache.org/thrift/ThriftUsageJava
Binary
TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
byte[] bytes = serializer.serialize(work);
TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
Work moreWork = new Work();
deserializer.deserialize(moreWork, bytes);
JSON
TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = serializer.toString(work);
Thrift Definition File
Objects are defined as Structures.
Structure can contain other structures. - same as in Protocol Buffers
Can contain methods that act on the members
* Can import files.
* supports inheritance
For the above to work, compile using special option.
Here it the [http://wiki.apache.org/thrift/Tutorial tutorial]
You can find more examples in the test folder of downloaded tar.
Services
Thrift definition files can have services. The compiler generates client and server code that provides RPC.
This is how Thrift can be used with [http://cassandra.apache.org/ cassandra] and [http://www.lexemetech.com/2008/07/rpc-and-serialization-with-hadoop.html Haddop]
Development Support
* IDE :
Eclipse and IntelliJ plugins have been out. But not sure if they work. Here is the link for [http://sourceforge.net/projects/thrift4eclipse/ Eclipse] and [http://incubator.apache.org/thrift/version_control.html IntelliJ]
* Maven :
out of the box Thrift is supported by ant.
But [http://github.com/dtrott/maven-thrift-plugin maven] plugin is availabile
References
* [http://incubator.apache.org/thrift/ Main Page]
* [http://incubator.apache.org/thrift/static/thrift-20070401.pdf WhitePage]
Installation
Ubuntu
sudo apt-get install libboost-dev automake libtool flex bison pkg-config g++
1. Download Thrift tar ball
http://incubator.apache.org/thrift/download/
2. unzip to /url/local/thrift
unzip /home/asulgaonkar/download/thrift-0.5.0.tar.gz
3. go to the root and read README
follow the instructions and do :
./configure
4. go to lib/java
ant
This will create thrift jar.
5. create thrift compiler
cd compile/cpp
make
How to run the thrift compiler ?
6. Make sure thrift is compiled, both the compiler and the Java library. You should
be able to verify the following:
thrift/tutorial/java$ file ../../lib/java/libthrift.jar
../../lib/java/libthrift.jar: Zip archive data, at least v1.0 to extract
if not do step 4.
thrift/tutorial/java$ file ../../compiler/cpp/thrift
../../compiler/cpp/thrift: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, not stripped
if not do step 5.
thrift/tutorial/java$ ls ../../lib/java/build/ivy/lib/
commons-lang-2.5.jar junit-4.4.jar servlet-api-2.5.jar slf4j-api-1.5.8.jar slf4j-simple-1.5.8.jar
7. Generate code for java:
thrift/tutorial/java$ cd ..
thrift/tutorial$ thrift -r -gen java tutorial.thrift
>> This will create gen-java
and folders inside it - shared and tutorial
8. Compile example
thrift/tutorial/java$ ant
This will compile the files that were generated
9. Run example:
thrift/tutorial/java$ ./JavaServer &
thrift/tutorial/java$ ./JavaClient
To prove that the serialization and de-serialization works
I modified client code to include following lines :
TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
byte[] bytes = serializer.serialize(work);
System.out.println("bytes : " + String.valueOf(bytes));
System.out.println("Serialization Works!!");
TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
deserializer.deserialize(moreWork, bytes);
System.out.println("De - Serialization Works!!" + moreWork.op + " on " + moreWork.num1 + " and " + moreWork.num2);
TSerializer jsonSerializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = jsonSerializer.toString(moreWork);
System.out.println("JSON " + json);
Friday, May 8, 2009
Anosh Sulgaonkar
| Java / J2EE : | Servlets, EJB, JMS, JCA, socket programming, swing |
| MVC | Spring MVC, Spring Webflow, JSP, Struts, Synapse (like Velocity) |
| IOC / ORM | Spring, Hibernate (with and without annotations) |
| Build and CI Tools | Ant, Ivy, Maven, Cruise control, Hudson. |
| Testing | JUnit, JMeter, Selenium RC, STIQ (Story test IQ) |
| UI & Frameworks | HTML, CSS, SWING, ColdFusion, Flex, Silverlight, JQuery |
| Servers | Weblogic, JBoss, Tomcat |
| OS | Unix (Solaris), Linux, Windows. |
| Working Knowledge | Ruby on Rails, Groovy and Grails, C#, Objective C. |
Masters Degree in Electronics Engineering. (Walchand College of Engg., Sangli. India)
Bachelors Degree in Electrical Engineering. (Walchand College of Engg., Sangli. India)
Scrum Master Certification.
Ruby on Rails course at University of Washington
Experience:
SolutionsIQ : April 2006 to Present.
SolutionsIQ is a leading IT service provider company that promotes agile methodology.
I got to work on various projects in roles such as Team lead and SDE.
Zones Inc.
Team Lead. MIS, WebDev Group.
Duration: May 2000 to April 2006.
Zones Inc is a retailer of IT products.
EAI implementation:
Duration: 2003 September to April 2006.
Role : Lead.
This initiative was to build web based system that was connected to ERP, CRM and content system and present to the user a unified view.
Technology Used : JBoss, EJB 2, JCA, JMS, Sockets, FLEX.
B2B Web site:
Duration : 2000 May to 2003 December
Role : Sr Java Developer.
Technology Used: Java, Synapse(proprietary MVC like Velocity)
Product Maintenance tool:
Duration: May 2002 to August 2002.
Technology Used: Java, Swing
Customer Management Reports:
Duration : 2006 January to 2006 February
Technology Used: Java, iText, JFreeReport.
Independant Software Developer.
Duration : 1995 to 2000
Developed payrole system for textile mills.
Technology Used: FoxPro, VB 5
Assitant Professor in Electronics Engg. at Walchand Institute of Technology, India.
Duration : 1990 January to 1999 February
Lecturer on subjects like : programming languages, Computer Graphics, Electronic System Design, ElectroMagnetic Engg., Analog Devices etc. Did research on Computer aided Textile designing.
Technology Used: C, ASM86
Immigration Status: Permanent Resident (Green Card Holder).
Referrals:
Please refer to LinkedIn page:
http://www.linkedin.com/in/anoshsulgaonkar
Wednesday, April 8, 2009
Attaching detached objects
For example I get list of Memberships. Each Membership has a user. Each User has an Address.
If I get list of Memberships in one session. Then try to access address from the user in another session we will get the famous 'no session exception'
We need to attach the user created in the first session to the second one.
session2.update(user);
system.out.printf("user City :"+ user.address().getCity);
so session1 creates memberships.
user.address is invoked by session2.
before we invoke the command, we need to attach user to the session2.
session2.update(user) will do the trick.
Friday, April 3, 2009
Hibernate Transactions with Annotations
Here are the steps for setting the Transactions
Pass the sessionFactory to the transactionManager.
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Add the tx namespace to context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
.
.
.
<tx:annotation-driven />
Place the annotations above the methods you are going to use the sessionFactory.
@Transactional
public Product getProductById(final long id) {
final Session session = sessionFactory.getCurrentSession();
final Product product = (Product) session.get(Product.class, id);
return product;
}
Here are some points to remember:
1. If you want a method to be transactional.
2. The classes that use transactional annotation should use not use constructor autowire. - It will give bean creation exceptions. I have used setter injection autowire byType.
3. If a class is calling a method that needs transaction, The public method needs to be transactional. So you cannot call from outside, a non-transactional public method and then delegate to a transactional method.
4. How do you check if the hibernate transactions are working?
Insert in the method : sessionFactory.getCurrentSession()
If the transactions are not set correctly, you will get errors.
5. If the transaction is going to run a batch job, flush and clear the session at batches of 20 - 30.
final Session session = sessionFactory.getCurrentSession();
int count = 0;
for (final EipCharge charge : eipCharges) {
// Do the stuff .....
.....
if (count % 20 == 0) {
session.flush();
session.clear();
}
count++;
}
Monday, March 9, 2009
Quartz Implementation
This should override the method executeInternal. This should contain the stuff you need to cron.
2. Define the bean : org.springframework.scheduling.quartz.JobDetailBean
set the property ''jobClass' which it your implementation of cron that you want to run
3. Point the above bean to org.springframework.scheduling.quartz.CronTriggerBean
as the property jobDetail.
Another parameter it takes is the cron string. This is similar to unix cron
4.Place the above bean in the org.springframework.scheduling.quartz.SchedulerFactoryBean.
as content of the property 'trigger'
<bean name="helloWorld" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.test.eip.viva.batch.HelloWorld" />
</bean>
<bean id="helloWorldBatchTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="helloWorld" />
<property name="cronExpression" value="0 * * * * ?" />
</bean>
<bean id="eipSchedulerFactoryBean"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="helloWorldBatchTrigger" />
</list>
</property>
</bean>
If your cron bean requires additional beans. This is the way to inject the bean. Provide the beans required by the jobClass in a jobDataAsMap property
<bean name="helloWorld" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.test.eip.viva.batch.HelloWorld" />
<property name="jobDataAsMap">
<map>
<entry key="message">
<ref bean="messageProvider" />
</entry>
</map>
</property>
</bean>
Tuesday, March 3, 2009
Contextual sessions with Hibernate3 and Spring2.5
The blog describes how to effectively use hibernate 3 with spring2.5 without using hibernateTemplate or HibernateDaoSupport.
Blog will walk you through setting up spring and hibernate. Using SessionFactory and session to access tables. Then it will show you how to use contextual sessions.
You need to start with a spring project. Create a Spring context.xml
Below is the header:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
Create session factory
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/hibernate.cfg.xml" />
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_configuration">classpath:/ehcache.cfg.xml</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
</props>
</property>
</bean>
Create DataSource:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
<property name="url">
<value>${db-url}</value>
</property>
<property name="username"><value>${db-username}</value></property>
<property name="password"><value>${db-password}</value></property>
</bean>
Using Properties File
The properties db-url, db-username, db-password are in the app.properties file. Spring will be able to read them using PropertyPlaceholderConfigurer which takes the location propety. Below is the bean definition in spring context:
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:/app.properties</value>
</property>
</bean>
Using JNDI
You can use Jndi instead of maintaining the connection properties. Define dataSource as a JndiObjectFactoryBean instead of DriverManagerDataSource.
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="${datasource.jndi.name}" />
<property name="jndiEnvironment">
<props>
<prop key="java.naming.provider.url">${provider.url}</prop>
</props>
</property>
</bean>
Why JNDI?
1. Database url, username is not hard coaded inside in the war, so easy for deployment. Set up jndi on realted environment.
2. Connection pool size is managed by the jndi provider. If we are using DriverManager, it will allow you to create as many connections limited at the database. With Jndi provider, it is easy to figure out sessions left open.
Hibernate Configuration and Bean Annotations
Create hibernate configuration file under 'war/WEB-INF/classes/'. This file points to the beans that will be mapped to the tables.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="com.test.eip.domain.ExampleBean1" />
<mapping class="com.test.eip.domain.ExampleBean2" />
</session-factory>
</hibernate-configuration>
The beans will be mapped to the tables using annotations from package 'javax.persistence.'
The annotations at the begining of the class : @Entity @Table(name='MyEntity' schema='')
Fields are mapped by the @Column(name='') annotations at the getters or at the field declarations.
@Entity
@Table(name = “ExampleBean1″, schema = “”)
public class Equipment implements java.io.Serializable {
private static final long serialVersionUID = 2959455667770311499L;
private long id;
@Id
@Column(name = “ID”, unique = true, nullable = false, precision = 38, scale = 0)
public long getId() {
return id;
}
With above 3 things, you should be able to get the entity from Database using command like session.get(MyEntity.class, id)
Using the SessionFactory
Below is the sample to get the Objects.
final Session session = sessionFactory.openSession();
try{
Equipment equipment = (Equipment) session.get(Equipment.class, id);
.
.
}finally{
session.close();
}
Below is the sample to execute the raw SQL
final Session currentSession = sessionFactory.openSession();
final Query query = currentSession.createSQLQuery("select ID_SEQ.nextval from dual");
try{
final String id = query.uniqueResult()).toPlainString();
}finally{
currentSession.close();
}
Contextual Sessions
You can use contextual sessions with sessionFactory.getCurrentSession(). For this you will have to define transactionManger.
Pass the sessionFactory to the transactionManager.
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Add the tx namespace to context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
.
.
.
<tx:annotation-driven />
Place the annotations above the methods you are going to use the sessionFactory.
@Transactional
public Equipment getEquipmentById(final long id) {
final Session session = sessionFactory.getCurrentSession();
final Equipment equipment = (Equipment) session.get(Equipment.class, id);
return equipment;
}
You no longer need to close the session or open the session with SessionFactory. getCurrentSession will check if there is an active session and return it. If there is no active session it will create new.
If the method in transaction calls other methods that use sessionFactory, all will use the same transaction provided you have '@Transaction' annotation over all the methods called. Same hibernate session will be kept alive for you by the SessionFactory.