Home » Java and J2EE

Category Archives: Java and J2EE

Advertisements

Spring Fundamental Tutorial

Spring First Tutorial

Since intention of this tutorial is to give a brief foundation of Spring framework so its start with covering the following basic modules first and later it would move to advance topics. Tutorial is based on spring 3.0 version.

§Introduction to Spring

§Features added in Spring 3.0+ version

§Spring Framework

§Spring Modules

§Spring IOC & Dependency Injection

§Application Context & Bean Factory

§Spring Bean Configuration

§Auto-wiring in Spring configuration

§@Annotations

§Working with Spring Name spaces

§Using Inner Beans 

—————————————————————————

§Introduction to Spring

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. Spring framework is a layered architecture consisting of seven well-defined modules. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in next Figure .

—————————————————————————

§Features added in Spring 3.0+ version

  • Spring 3.0 framework supports Java 5. It provides annotation based configuration support. Java 5 features such as generics, annotations, varargs etc can be used in Spring.
  • A new expression language Spring Expression Language SpEL is being introduced. The Spring Expression Language can be used while defining the XML and Annotation based bean definition.
  • Spring 3.0 framework supports REST web services.
  • Data formatting can never be so easy. Spring 3.0 supports annotation based formatting. We can now use the @DateFimeFormat(iso=ISO.DATE) and @NumberFormat(style=Style.CURRENCY) annotations to convert the date and currency formats.
  • Spring 3.0 has started support to JPA 2.0.
  • Apart from these main features there are lots of exiting improvements over the last revisions are also there.

—————————————————————————

§Spring Framework

§Spring Modules

The core container: The core container provides the essential functionality of the Spring framework. Primary component of the core container are BeanFactory and Application Context, Bean Factory an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code. Application Context is build on top of Bean factory and provides more functionalities, like integration with AOP/messaging resources/events etc.

Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. Spring provides option to specify configuration by XML or Java file based approach.

Spring AOP: AOP is very emerging feature now days which provides more modularity in programming by separating the cross cutting the concerns from main business logic.  The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. . Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

Spring ORM: Spring provides good abstraction layer to integrate with most of the popular ORM tools in market. The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.

Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.

Spring MVC framework: Spring provides a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and support most of the view technologies like JSP, Velocity, Tiles, iText, and POI.Spring framework functionality can be used in any J2EE server and most of it also is adaptable to non-managed environments. Concentrating more on allowing reusable business and data-access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (Web or EJB), standalone applications, test environments, and so on, without any hassle.

—————————————————————————

§Spring IOC & Dependency Injection

The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.In a typical IOC scenario, the container creates all the objects, wires them together by setting the necessary properties, and determines when methods will be invoked. The three implementation pattern types for IOC are listed below.

  1. Dependencies are assigned through JavaBeans properties (for example, setter methods).
  2. Dependencies are provided as constructor parameters and are not exposed as JavaBeans properties.

Lets see how Spring Uses the Power of simple bean

Most of the traditional frame works forces you to implement their life cycle methods

public class HelloWorldBean implements SessionBean {
    public void ejbActivate() {
    }
    public void ejbPassivate() {
    }

    public void ejbRemove() {
    }
    public void setSessionContext(SessionContext ctx) {
    }

    public String sayHello() {
    return "Hello World";}

    public void ejbCreate() {
    }
}

The SessionBean interface would let you hook into the EJB’s lifecycle by implementing several lifecycle callback methods, even if you didn’t need to. Spring avoids (as much as possible) littering your application code with its API. Spring almost never forces you to implement a Spring-specific interface or extend a Spring-specific class. Instead, the classes in a Spring-based application often have no indication that they’re being used by Spring. At worst, a class may be annotated with one of Spring’s annotations, but is otherwise a POJO.

  public class HelloWorldBean {
     public String sayHello() {
     }
  }

Isn’t that better? Gone are all of those noisy lifecycle methods. HelloWorldBean doesn’t implement, extend, or even import anything from the Spring API Dependency injection involves giving an object its dependencies as opposed to an object having to acquire those dependencies on its own.

Comparing with the traditional approach of programming vs the spring mechanism. With an interesting example taken from the Book : “Spring in Action 3.0”

Problem: RescueDamselQuest : Mission to rescue a pricess. If we analyse the class written bellow for a moment we can figure out several limitations as described further.

public class DamselRescuingKnight implements Knight {
   private RescueDamselQuest quest;
   public DamselRescuingKnight() {
   //Tightly coupled to RescueDamselQuest
     quest = new RescueDamselQuest();
   }

   public void embarkOnQuest() throws QuestException {
     quest.embark();
   }
}

Observed Drawbacks:

  • DamseRescueKnight is tightly coupled to RescueDamselQuest
  • Restricting the ability of Knights for embark on a Quest
  • Terrible writing for test case for DamseRescueKnight , you’d like to be able to assert that the quest’s embark() method is called when the knight’s embarkOnQuest() is called,but is difficult to write such test case.

Better approach to reduce the coupling between the DamselRescuingKnight and RescueDamselQuest, isn’t it.

public class BraveKnight implements Knight {
   private Quest quest;
   public BraveKnight(Quest quest) {
     this.quest = quest;
   }

   public void embarkOnQuest() throws QuestException {
     quest.embark();
   }
}

Observed advantages:

  • BraveKnight does not create own Quest
  • Rather he is given a quest at the construction time
  • What more he is give a typed Quest that can receive any kind of Quest, The point here is that BraveKnight isn’t coupled to any specific implementation of Quest

That’s the key benefit of DI—loose coupling. Writing the use case for the above problems also gets more meaning full approach.

@Test
   public void knightShouldEmbarkOnQuest() throws QuestException {
      Quest mockQuest = mock(Quest.class);
      BraveKnight knight = new BraveKnight(mockQuest);
      knight.embarkOnQuest();
      verify(mockQuest, times(1)).embark();
   }
  }

Here you’re using a mock object framework known as Mockito to create a mock implementation of the Quest interface. You really not need to wait to hit the real Quest while Unit test

—————————————————————————

§Application Context & Bean Factory

Two of the most fundamental and important packages in Spring are the org.springframework.beans and org.springframework.context packages. The BeanFactory provides an advanced configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage facility

The ApplicationContext builds on top of the BeanFactory (it’s a subclass) and adds other functionality such as easier integration with Springs AOP features, message resource handling , event handling, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext, among other enhancements. Best option is to use the ApplicationContext, since it offers all the features of the BeanFactory and adds on to it in terms of features

Code snippet of getting handler to ApplicationContext/BeanFactory. By providing the reference of the bean configuration file we can get hander of Bean Factory of Application context.

ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

Or

ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Users/manjul/../src/Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();

Or

ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Users/manjul/../src/Beans.xml");
BeanFactory factory = (BeanFactory) context
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");

I would suggest to use Application Context over the BeanFactory as it provides you all what BeanFactory does plus some other features. The most commonly used ApplicationContext implementations are:

  • FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.
  • ClassPathXmlApplicationContext This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
  • WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.

—————————————————————————

§Spring Bean Configuration

A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on.A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed.Spring Bean definition inheritance has nothing to do with Java class inheritance but inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit required configuration from the parent bean.When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.

The bean definition contains the information called configuration metadata which is needed for the container to know the followings:

  • How to create a bean
  • Bean’s lifecycle details
  • Bean’s dependencies

All the above configuration metadata translates into a set of the following properties that make up each bean definition. Following attributes used with bean tags and their usage is given in below table.

Configuring Spring. Spring provides several ways of defining the Bean configurations as listed below. But I preferably choose XML based configuration, as it provides centralized view of the artifacts to analyze the whole configuration very easily. But its totally up to you that which mechanism you like to implement in your application.

Spring Configuration MetaData

  1. XML based configuration file.
  2. Annotation-based configuration
  3. Java-based configuration

In a large project structure, the Spring’s bean configuration files are located at different folders for easy maintainability and modular. For example:

  1. Spring-Common.xml in common folder,
  2. Spring-Connection.xml in connection folder,
  3. Spring-ModuleA.xml in ModuleA folder…and etc.

Sample view of Bean configuration File

<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-3.0.xsd">
<!-- A simple bean definition -->
<bean id="..."singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with lazy init set on -->
<bean id="..." lazy-init="true">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with initialization method -->
<bean id="..." init-method="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with destruction method -->
<bean id="..." destroy-method="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>

 

Scopes of the Beans

—————————————————————————

§Auto-wiring in Spring configuration

You have seen how to declare beans using the <bean> element and inject <bean> with using <constructor-arg> and <property> elements in XML configuration file. The Spring container can autowire relationships

between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration you write for a big Spring based application. Using following ways/mode.

  • No
  • byName
  • byType
  • Constructor
  • Autodetect

Now we know how to set manual wiring !

<bean id=”customer”>
<property name=”person” ref=”person” />
</bean>

<bean id=”person” />

Autowiring by property name.

Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.

Spring will auto wired it via setter method – “setPerson(Person person)“.

<bean id=”customer” autowire=”byName” />
<bean id=”person” />

Autowiring by property datatype.

Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.

Spring will auto wired it via setter method – “setPerson(Person person)“.

<bean id=”customer” autowire=”byType” />
<bean id=”person” />

Auto-wire Constructore.

Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

Spring auto wired it via constructor method – “public Customer(Person person)“.

<bean id=”customer” autowire=”constructor” />
<bean id=”person”.manjul.spring.samples.Person” />

Auto-wire Autodetect

Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

<bean id=”customer” autowire=”autodetect” />
<bean id=”person” />

Limitations of Autowiring 

Limitations with autowiring:Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be confusing to developers to use it to wire

only one or two bean definitions. Though, autowiring can significantly reduce the need to specify properties or constructor arguments but you should consider the limitations and

disadvantages of autowiring before using them.Limitations Description

Overriding possibility, We can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.

Primitive data types,  We cannot autowire so-called simple properties such as primitives, Strings, and Classes.

Confusing nature Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring.

———-

§@Annotations

Using annotations for the defining Spring configuration file and beans configurations
@Configuration & @Bean Annotations

@Configuration
public class HelloWorldConfig {

@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}

This Is equivalent to
<beans>
<bean id=”helloWorld” />
</beans>

While retrieving the bean reference:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class); ctx.refresh();
MyService myService = ctx.getBean(MyService.class);

Autowired Annotation
We have seen how can we define autowiring in configuration file.

We can also specify auto wiring using @Autowired Annotation
Through setter method
@Autowired
public void setPerson(Person person) {
this.person = person;
}

Through construtor
@Autowired
public Customer(Person person) {
this.person = person;
}

Through field
@Autowired
private Person person;

By default, the @Autowired will perform the dependency checking to make sure the property has been wired
properly. When Spring can’t find a matching bean to wire, it will throw an exception. To fix it, you can disable
this checking feature by setting the “required” attribute of @Autowired to false. @Autowired(required=false)

@Qualifier
The @Qualifier annotation us used to control which bean should be autowire on a field. For example, bean configuration file with two similar person beans.

public class Customer
{
@Autowired
@Qualifier(“PersonBean1”)
private Person person;
private int type;
private String action;
//getter and setter methods
}

——–

§Spring NameSpaces

Namespace configuration has been available since version 2.0 of the Spring framework.

It allows you to supplement the traditional Spring beans application context syntax with elements from additional XML schema. You can find more information in the Spring Reference Documentation. A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user. A simple element may conceal the fact that multiple beans and processing steps are being added to the application context. For example, adding the following element from the security namespace to an application context will start up an embedded LDAP server for testing use within the application.

Name spaces are the preset of liberaries created for a significant purpose i.g. utilities, security, aop etc. Some of the popular libraries are listed below:

Spring core

aop – AopNamespaceHandler
c – SimpleConstructorNamespaceHandler
cache – CacheNamespaceHandler
context – ContextNamespaceHandler
jdbc – JdbcNamespaceHandler
jee – JeeNamespaceHandler
jms – JmsNamespaceHandler
lang – LangNamespaceHandler
mvc – MvcNamespaceHandler
oxm – OxmNamespaceHandler
p – SimplePropertyNamespaceHandler
task – TaskNamespaceHandler
tx – TxNamespaceHandler
util – UtilNamespaceHandler
Spring Security
security – SecurityNamespaceHandler
oauth – OAuthSecurityNamespaceHandler
P-Name space

The p-namespace enables you to use the bean element’s attributes, instead of nested <property/> elements, to describe your property values and/or collaborating beans.

Namespace specification need to be added in configuration file as shown below
xmlns:p=”http://www.springframework.org/schema/p&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&#8221;
Traditional way

<bean name=”john-classic”>
<property name=”name” value=”John Doe”/>
<property name=”spouse” ref=”jane”/>
</bean>

Using name spaces
<bean name=”john-modern”
p:name=”John Doe”
p:spouse-ref=”jane”/>
<bean name=”jane”>
<property name=”name” value=”Jane Doe”/>
</bean>

Util-Name space
<util:constant/>

Make sure that we need to have correct XSD loaded
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”

Ex1 : Generic way for configuring property is
<bean id=”…”>
<property name=”isolation”>
<bean id=”java.sql.Connection.TRANSACTION_SERIALIZABLE”
/>
</property>
</bean>

Using namespaces
<bean id=”…”>
<property name=”isolation”>
<util:constant static-field=”java.sql.Connection.TRANSACTION_SERIALIZABLE”/>
</property>
</bean>
<util:properties/>

Normal Spring FactoryBean implementation, the PropertiesFactoryBean, to instantiate a java.util.Propertie

Ex2 : Without using name spaces

<bean id=”jdbcConfiguration”>
<property name=”location” value=”classpath:com/foo/jdbc-production.properties”/>
</bean>

Using name spaces

<util:properties id=”jdbcConfiguration” location=”classpath:com/foo/jdbc-production.properties”/>
<util:list/>

One of the collection utility for populating values in list.
<bean id=”emails”>
<property name=”sourceList”>
<list>
<value>pechorin@hero.org</value>
<value>raskolnikov@slums.org</value>
<value>porfiry@gov.org</value>
</list>
</property>
</bean>

Ex3: Using Namespace:

<util:list id=”emails”>
<value>pechorin@hero.org</value>
<value>raskolnikov@slums.org</value>
<value>stavrogin@gov.org</value>
<value>porfiry@gov.org</value>
</util:list>

*Similarly utilities are also available to work with other collections like Map/Set/Properties

§Using Inner Beans

A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean.
An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean.

<bean id=”outer”>
<!– instead of using a reference to a target bean, simply define the target bean inline –>
<property name=”target”>
<bean> <!– this is the inner bean –>
<property name=”name” value=”Fiona Apple”/>
<property name=”age” value=”25″/>
</bean>
</property>
</bean>

Advertisements

Hibernate First Tutorial

Hibernate First Tutorial


1.Introduction

2.Hibernate Architecture

3.Main Components of Hibernate

4.Hibernate Configuration

5.Hibernate Mapping File

6.Mapping Association

7.Basic API’s

8.Hibernate Data source properties

9.Complete Example

1: Hibernate Introduction:

While today’s applications are designed using Object Oriented Approach. As the business data is stored in the databases and applications create/fetches/update and remove these data for the business purposes. . Since both data storage and data handling are wast domain, over the period of time they are many vendors have provided mechanism for data data storage like oracle, db2 etc.. and similarly many application development technologies have enhanced theirs capabilities like J2EE,.Net etc.

The basic concept in Object Oriented approach is we consider the solution by identifying different Objects involved in the applications. Where as in case of Data bases there have evolved concept of RDBMS where data is stored in the Relational databases in tables and records. And application developer has to play the role of bridging this gap of data stored in tables and creating objects to be used in the object oriented programming. Developers has to write this data plumbing code as well as data processing code.

Hibernate came up with the solution of bridging this gap and providing all the necessary arrangements through which developer can just configure the required database and tables and later Hibernate will take care of data management work and developer just need to concentrate on data processing i.e. their application programming. Hibernates main advantage is the mapping of Objects data model with the corresponding table, developer do not need to bother about transforming data bases data in to objects. Object creation updation and persistence work will be done by hibernate.

2: Hibernate Architecture

Hibernate architecture is explained in the given figure below. Hibernates persistence layer lies between the data base layer and the application layer.

Figure1:

Hibernate Architecture

Hibernate Architecture

Detailed Architecture

Second figure explains the details architecture with all the components. Session Factory is singleton object for every databases. For every connection there will be a session created by this session factory, which can internally create mutiple transaction bases on the requirement.

Figure 2:

Hibernate Detailed Architecture

Hibernate Detailed Architecture

 

 

 

3: Main Components of Hibernate

Basic building blocks of the hibernate application are listed below:

 

3.1 SessionFactory org.hibernate.SessionFactory

This is a thread safe singleton immutable object of the database mapping. There is only one connection factory for each database. Its a factory for the hibernate session and it also maintains the second level cache between the application and database at the process level.

Usage example:<to be added>

 

3.2 Session org.hibernate.Session

This is single threaded an short lived object represents the conversation between the application and the database or persistence store. This is the wrapper over sql connection and works as the factory for the org.hibernate.Transaction. It mentains the first level cache of the application’s persistent object and collections. This cache is used while looking for the object using object id or while navigating the object graph.

Usage example:<to be added>

 

 

3.3 ConnectionProvider org.hibernate.connection.ConnectionProvider

This is optional and not directly exposed to the application developer, it represents the pool of connections. If require developer can implement this.

 

3.4 TransactionFactory org.hibernate.TransactionFactory

This is connection factory for the org.hibernate.Transaction, this is also not exposed to the developer but if require developer can implement this.

 

 

3.5 Transaction org.hibernate.Transaction

This is a single threaded short lived object use by the application to specify the atomicity of the work. It abstract the application from underlying jdbc/JTA implementation. Hibernate Session can maintaine more than one transaction also at a time.

 

 

3.6 Persistent Object

These are short lived business object represent the persistence state. They are associated with exactly one hibernate session. Once the session is closed they are free to used by the any layer of the application.

 

 

3.7 Transient and Detached Object

These are those instance of the persistence java classes whose objects are not yet associated or loaded with the session. They may have been instantiated by the application but not yet been associated with the hibernate session.

 

 

4: Hibernate Configuration File

 

This is the file where we specify the database level configuration. This file is read while application loads and then hibernate creates the connection pool with the specified database as per the specification. It also consist of entire set of mapping of Java Objects and Database tables.

Org.hibernate.cfg.Configuration object represent the entire set of mapping.

Configuarion and Sessionfactory objects:

SessionFactory factory = new Configuration.configure().buildSessionFactory();

Hibernate allows one Session factory for every database. Though it allows multiple session factory for more than one databases.

 

This is a simple example of the hibernate configuration file.

 

<?xml version=’1.0′ encoding=’utf-8′?>

<!DOCTYPE hibernate-configuration PUBLIC”-//Hibernate/Hibernate Configuration DTD//EN”

http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;

<hibernate-configuration>

<session-factory>

<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver

</property>

<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/mysql

</property>

<property name=”hibernate.connection.username”>root</property>

<property name=”hibernate.connection.password”>root</property>

<property name=”hibernate.connection.pool_size”>10</property>

<property name=”show_sql”>true</property>

<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

<property name=”hibernate.hbm2ddl.auto”>update</property>

<!– Mapping files –>

<mapping resource=”contact.hbm.xml”/>

</session-factory>

</hibernate-configuration>

 

5: Hibernate Mapping File

 

We specify individual mapping for each database table. Mapping is declared between class with a table and respective column with the attributes of the class.

 

Mapping can be defined in following ways:

-Using Java 5 Annotations

-Using Hibernate legacy XML file.

 

5.1 Mapping using Java Annotation

Simple example of hibernate configuration using Annotation, here we can see we are explicitly specifying the mapping in the bean file itself using java 5 annotation.

 

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;


@Entity

@Table(name = “contact”)

public class Contact implements Serializable {

public Contact() {

}


@Id

@Column(name = “id”)

Integer id;


@Column(name = “firstName”)

String firstName;


public Integer getId() {

return id;

}


public void setId(Integer id) {

this.id = id;

}


public String getName() {

return firstName;

}


public void setName(String name) {

this.firstName = name;

}


}

 


5.2 Using Hibernate legacy XML file.

 

The traditional way of declaring the mapping is the hibernate configuration file and we can see in this example how we declare the same mapping by XML file.

This is the most simple and popular way of declaring the mapping, we can also specify the mapping between come other class and table in the same file or we can maintain separate mapping file for each table.

 

 

<?xml version=”1.0″?>

<!DOCTYPE hibernate-mapping PUBLIC

“-//Hibernate/Hibernate Mapping DTD 3.0//EN”

http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;

<hibernate-mapping>

<class name=”roseindia.tutorial.hibernate.Contact” table=”CONTACT”>

<id name=”id” type=”long” column=”ID” >

<generator class=”assigned”/>

</id>

<property name=”firstName”>

<column name=”FIRSTNAME” />

</property>

<property name=”lastName”>

<column name=”LASTNAME”/>

</property>

<property name=”email”>

<column name=”EMAIL”/>

</property>

</class>

</hibernate-mapping>

 

…………………………….article to be completed soon !

 

Multithreading in Java

Multithreading

Usually a program has logic to execute and some objects or data to modify. In a single threaded system program executes in a sequence line by line. Multithreaded system can allow multiple threads to execute a program parallel in multiple instances. If there is any part of code dealing with the object data modification, there is no guarantee that it will not be attempted any more than one thread at a time.

Now there a need to make sure that such kind of code should be executed exclusively. To achieve this in Java we a concept of LOCK. Using Lock mechanism thread holds complete hold on an object and object is also can not be access any other thread except the thread holding that lock. Lock is an object level control and one thread only can hold it at a time.

Synchronized: We have to specify about the piece of code in a program which should be run exclusively. It could be a code segment or a complete function. Synchronised can be used in following ways:

Function level synchronise will fetch a lock on the object, this function is defined in.

1)  synchronised function updateTotal(){
       // some code
    }

2)  a block of code can also be defined as synchronised with an specified object, to capture a lock control on.

function updateTotal(){
     // some code 
     Synchronised(this){
     //some code
     }
}

Thread Sates or Life cycle. Thread follwos a life cycle, which starts from the threation till it is destroyed.

multith

  •  A thread can be in one of the following states:

    • NEW
      A thread that has not yet started is in this state.  This is the first state when thread object is created. Thread will be in this state until the run method is not called of.
    • RUNNABLE
      A thread executing in the Java virtual machine is in this state. Once the run method is called, thread goes in the runnble state.  While it is in a runnable state it is eligible to get process time to execute its part. Process though will keep distributing the time among all the active threads. Thread can also move to waiting state due to two reasons. 1 Timed waiting 2: Object waiting. Threads not in runnable states do not get process time.
    • BLOCKED
      A thread that is blocked waiting for a monitor lock is in this state.
    • WAITING
      A thread that is waiting indefinitely for another thread to perform a particular action is in this state.Some time a thread need a lock on a object and that object is being used bus another prohram or thread, in this case thread will wait for this object untill the object is not free. Some time this can cause a deadlock schenario if there is a possiblility that threads are using same objects in multiple situations and if the program is not designed properly.
    • TIMED_WAITING
      A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. Tread is forced to wait for some period of time may be by using Thread.sleep method. It will automatically come back to runnable state once specifiled time is over.
    • TERMINATED
      A thread that has exited is in this state.

    A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states. Ref :  http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html

 

Inter Thread Communication: When threads are trying to access a common object and that is bieng used by another thread. Theres has to be some way to notify the waiting threads once that object becomes free. This is achieved by wait,notify, notifyAll machanism. Wait and Notify is a machanism by which we can send signals between the thread when some specific condition is met.

Lets understand by the example of >> Producer and Consumer Problem in Java
======================================

import java.util.ArrayList;
import java.util.Random;
//Shared resource
class Pool{
   ArrayList pool = new ArrayList();
   int maxSize=10;
   public synchronized String popItem(){
   if(this.pool.size() = maxSize){
     System.out.println("List Full !" + this.pool.size());
     try {
      wait();
     } catch (InterruptedException e) {
      LOG.error("Interrup has occured");
      e.printStackTrace();
     }
   }
   notify();
   pool.add(item);
 }
}

//Supplier Thread
class Supplier extends Thread{
  Pool poolSet;
  public Supplier(Pool poolSet) {
     this.poolSet = poolSet;
     this.setName("Supplier");
  }

 public void run() {
   while(true){
   String rand = new Random().toString();
   System.out.println(this.getName()+" Adding " + rand);
   poolSet.pushItem(rand);
   try {
     Thread.sleep(1000);
   } catch (InterruptedException e) {
      LOG.error("Interrupt has occurred");
      e.printStackTrace();
   }
 }
}
}

//Consumer Thread
class Consumer extends Thread{
  Pool poolSet;
  public Consumer(Pool poolSet) {
   this.poolSet = poolSet;
   this.setName("Consumer");
  }
 public void run() {
 while(true){
    System.out.println(this.getName()+" Read: " + poolSet.popItem());
    try {
       Thread.sleep(10000);
    } catch (InterruptedException e) {
       e.printStackTrace();
    }
    }
  }
}

//Test case
public class TestThread {
   public static void main(String[] args){
   Pool mypool = new Pool();
   Supplier sup = new Supplier(mypool);
   Consumer con = new Consumer(mypool);
   con.start();
   sup.start();
 }
}

======================================

Above Example demonstrate three classes Pool , Consumer and Supplier as all are part defined under the main program so that class Consumer and Supplier have direct access to the object of Class Pool.

Otherwise if they are we can also pass PoolC class object to Consumer and Supplies class constructor if they are not under a same class.

Notify() and NotifyAll(): It’s a good question to ask that what’s difference between notify() and notifyAll() methos. Notify() method will send a signal to one of the thread waiting for the same object (this may depend on any criteria like thread priprity or it can also be random). Whereas notifyAll() will send signal to all the threads who are waiting for that object and then it is upto the processor which therads it allows to execute.

Sleep() method: Sleep method is a static method and called from the Thread class directly. Thread.sleep(100) and it throws intereuptException, so you have to catch it also.

wait() method: Wait is the method of Object class and should always be called from the synchronised block of code. Advised to use wait(long timeOut)

Thread Interruption: Each thread has a boolean property associated with it which represents its interrupt status. When a thread is interrupted by some other thread by calling its Thread.interrupt() method then one of the two things happen

a) If a thread is executing low level incorruptible method like sleep() wait() pr join() then it unblocks them and throws InterruptedException.

b) Otherwise interrupt() just sets the internal flag value of the interrupted thread to true, that why is is recommended to check its status by calling isInterrupted() in threads normal business. When isInterrupted() returns true that means it is signal to stop the thread execution.