Unidirectional – bidirectional relationship provides navigational access in one direction

  Parent -----> Child

i.e you can go from parent to child, but you cannot go back from children to parent.

However, if there were no pointer to Parent in Child:

class Child { }

Bidirectional – bidirectional relationship provides navigational access in both directions

  Parent <-----> Child

i.e you can go from a Parent to its child, and vice-versa: the parent knows about its child, the child knows about its parent

class Parent {
  Child* children;
}

class Child {
  Parent* parent;
}

Idle Scenarios
One to One unidirectional Mapping
employee knows the employer

One to One Bidirectional Mapping
employer knows the employee and employee knows the employer

One to Many unidirectional Mapping
employee has a skill in his skill set which is not used by other employees

One to Many bidirectional Mapping
employee has a skill in his skill set which is not used by other employees and
employer knows that employee has this skill in skill set

Many to One unidirectional Mapping
employees knows which employer he is going to work but employer has no idea about employee

employees will have employerId in their entity class but employer has no details of employee

Many to One bidirectional Mapping
Many employees work for one Employer. The employer knows about employee and employee knows about employer

employees will have employerId in their entity class but employer will have empid of employee

Many to Many unidirectional Mapping
Employee knows the employers he has worked for but employers does not know details of employee who worked for them

Many to Many bidirectional Mapping
Employee knows about the employers he has worked for and employers knows about employee who has worked for them.

JPA COUNT returns a Long
When extracting the count from the table JPA returns long based on the type of query used.

JPQL

Query query = em.createQuery("SELECT COUNT(p) FROM PersonEntity p " );
query.getSingleResult().getClass().getCanonicalName() --> java.lang.Long

Native Query

Query query = em.createNativeQuery("SELECT COUNT(*) FROM PERSON");
query.getSingleResult().getClass().getCanonicalName() --> java.math.BigInteger

If it is Native Query big Integer is returned or if it is JPQL then Long is returned.

So before assigning to Integer the value should be typecasted.

 int count = ((Number)arrCount.get[0]).intValue();
 System.out.println(count);

Needs to be Removed

<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"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

	<context:annotation-config />
	<context:component-scan base-package="" />
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
	
	
	<!-- Configure the entity manager factory bean -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
		<!-- Set JPA properties -->
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10g</prop>
			</props>
		</property>
		<!-- Set base package of your entities -->
		<property name="packagesToScan" value="com.mugil.org.model" />
	</bean>
	
	
	<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton" lazy-init="true">
    	<beans:property name="jndiName" value="java:jboss/datasources/TurboDS"/>
	</beans:bean>	
</beans>

SpringMVC

Posted in JPA.

What is PersistenceContext
A persistence context handles a set of entities which hold data to be persisted in some persistence store (e.g. a database).Entities are managed by javax.persistence.EntityManager instance using persistence context.Each EntityManager instance is associated with a persistence context. Within the persistence context, the entity instances and their lifecycle are managed.Persistence context defines a scope under which particular entity instances are created, persisted, and removed.
A persistence context is like a cache which contains a set of persistent entities , So once the transaction is finished, all persistent objects are detached from the EntityManager’s persistence context and are no longer managed

A Cache is a copy of data, copy meaning pulled from but living outside the database.Flushing a Cache is the act of putting modified data back into the database.
A PersistenceContext is essentially a Cache(copy of data from database outside database). It also tends to have it’s own non-shared database connection.An EntityManager represents a PersistenceContext (and therefore a Cache).An EntityManagerFactory creates an EntityManager(and therefore a PersistenceContext/Cache)

What is the difference between LocalContainerEntityManagerFactoryBean and LocalEntityManagerFactoryBean?

JPA specification defines two types of entity managers.

LocalEntityManagerFactoryBean LocalContainerEntityManagerFactoryBean
Entity Managers are created and managed by merely the application(“opening , closing and involving entity manager in transactions”) Entity Managers are created and managed by merely the J2EE container
creates a JPA EntityManagerFactory according to JPA’s standard standalone bootstrap contract creates a JPA EntityManagerFactory according to JPA’s standard container bootstrap contract.
Application-managed EntityManagers are created by an EntityManagerFactory obtained by calling the createEntityManagerFactory() container-managed EntityManagerFactorys are obtained through PersistenceProvider’s createContainerEntityManagerfactory()
LocalEntityManagerFactoryBean produces an application-managed Entity- ManagerFactory. LocalContainerEntityManagerFactoryBean produces a container-managed EntityManagerFactory

The only real difference between application-managed and container-managed entity manager factories, as far as Spring is concerned, is how each is configured in the Spring application context.

When to use JPA getSingleResult()
getSingleResult() is used in situations like: “I am totally sure that this record exists. I don’t want to test for null every time I use this method because I am sure that it will not return it. Otherwise it causes alot of boilerplate and defensive programming. And if the record really does not exist (as opposite to what we’ve assumed), it is much better to have NoResultException compared to NullPointerException. If the record is not found it throws NoResultException

When the JPA Entities will become detached

  1. When the transaction (in transaction-scoped persistence context) commits, entities managed by the persistence context become detached.
  2. If an application-managed persistence context is closed, all managed entities become detached.
  3. Using clear method
  4. using detach method
  5. rollback
  6. In extended persistence context when a stateful bean is removed, all managed entities become detached.

What is JPADialect
Dialect is “the variant of a language”.Speaking about Hibernate in context hibernate works with different databases.hibernate has to use database specific SQL. Hibernate uses “dialect” configuration to know which database you are using so that it can switch to the database specific SQL generator code wherever/whenever necessary

<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.jpaDialect"/>

Now in the above statement I have specified that the jpaDialect I am going to use is of Hibernate Variant of implementation for JPA and Spring needs to take this into consideration
while creating entityManagerFactory.

The way it is referred is as follows

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
    <property name="jpaDialect"  ref="jpaDialect"/>
</bean>

Why we need JPAVendorAdapter
EntityManagerFactory manages the lifecycle of the entities.Persistence Provider is the one which specifies the details about the database and connection details of the underlying database either by persistence-context.xml or by injecting instances of EntityManager using @PersistenceContext annotation. JPAVendorAdapter helps to define the persistence context which is likely to be used.

Persistence-context.xml

  <persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <non-jta-data-source>java:comp/env/jdbc/ooes_master</non-jta-data-source>
        <properties>
        	<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
        	<property name="hibernate.show_sql" value="true"/>
        	<property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory"/>
            <property name="hibernate.cache.use_second_level_cache" value="true"/>
            <property name="hibernate.cache.use_query_cache" value="true"/>
        </properties>
 </persistence-unit>

If we want to inject instances of EntityManager using @PersistenceContext annotation, we have to enable annotation bean processor in Spring configuration

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

Usually this line is optional because a default PersistenceAnnotationBeanPostProcessor will be registered by the and XML tags.

getSingleResult() return detached or Managed Object
objects returned from .getResultList() are managed.When you made changes on the managed objects, you do not worry about merging as those changes will be picked up by the EntityManager automatically.The managed objects will become detached when the EntityManager that is used to load that object is close(), clear() or detach(). Detached objects are not manged anymore and you should do merging to let the EntityManager pick up the changes.

org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class
Sol

  1. @Entity Should be added in the Model class
  2. If you have missed to add the Model class in the xml file
  3. Make sure the annotation is javax.persistence.Entity, and not org.hibernate.annotations.Entity. The former makes the entity detectable.

————————————————————————————————————————————————————-
javax.naming.NoInitialContextException: Need to specify class name in environment or system property
Sol
“I want to find the telephone number for John Smith, but I have no phonebook to look in”.This exception is thrown when no initial context implementation can be created.JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext).

————————————————————————————————————————————————————-
hibernate exception: org.hibernate.AnnotationException: No identifier specified for entity
Sol

  1. You are missing a field annotated with @Id. Each @Entity needs an @Id – this is the primary key in the database.
  2. If you don’t want your entity to be persisted in a separate table, but rather be a part of other entities, you can use @Embeddable instead of @Entity.
  3. If you want simply a data transfer object to hold some data from the hibernate entity, use no annotations on it whatsoever – leave it a simple pojo.

————————————————————————————————————————————————————-
org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped
Sol
In the HQL , you should use the java class name and property name of the mapped @Entity instead of the actual table name and column name

For example if your bean class name is UserDetails then the Hibernate code should be as below.Not Tbl_UserDetails instead of UserDetails

 Query query = entityManager. createQuery("Select UserName from UserDetails"); 

The problem can also be because of wrong import

import javax.persistence.Entity;

instead of

import org.hibernate.annotations.Entity;

————————————————————————————————————————————————————-

  1. AnnotationSessionFactoryBean is used to create session factory if hibernate pojo are annotated
  2. AnnotationSessionFactoryBean is a factory that produces SessionFactory automatically.This is used when you create a sessionFactory object of Hibernate from Spring
     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.
    annotation.AnnotationSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="annotatedClasses">
         <list>
           <value>test.package.Foo</value>
           <value>test.package.Bar</value>
         </list>
       </property>
     </bean>
    
  3. This session factory is assigned to all dao beans and hibernate template to do database transaction.
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.
    HibernateTemplate">
    	<property name="sessionFactory">
    	  <ref bean="sessionFactory" />
    	</property>
    </bean>
    <bean id="pageDao" class="com.concretepage.dao.PageDaoImpl">
        <property name="hibernateTemplate">
    	  <ref bean="hibernateTemplate" />
    	</property>
    </bean>
    

Spring vs EJB

App servers written to support the EJB standard can, in theory, be ported from one compliant Java EE app server to another. But that means staying away from any and all vendor-specific extensions that lock you in to one vendor.

Spring ports easily between app servers (e.g., WebLogic, Tomcat, JBOSS, etc.) because it doesn’t depend on them

Spring Boot offers an even better way to write applications without Java EE app servers. You can create an executable JAR and run it on a JVM.

The Spring framework sits on top of the application servers and service libraries. Service integration code (e.g. data access templates) resides in the framework and is exposed to the application developers. In contrast, the EJB 3 framework is integrated into the application server and the service integration code is encapsulated behind an interface. EJB 3 vendors can thus optimize the performance and developer experience by working at the application server level. For example, they can tie the JPA engine closely to JTA transaction management. Another example is clustering support which is transparent to EJB 3 developers

Spring vs J2EE

Strictly speaking, Spring is a framework while Java EE is a specification which is implemented by various softwares such as JBoss and Glassfish.
The greatest difference is that Spring is an actual library while JavaEE is an API that has to be implemented. Depending on the JAVA EE container you could find a full implementation (e.g. Glassfish), a partial implementation (e.g. Tomcat) a full implementation with extra sugar (e.g. JBoss and others).

Spring MVC uses 2 design Patterns Internally

  1. Front Controller
  2. MVC

How Spring MVC Handles Request

  1. Receive the request from client
  2. Consult Handle Mapper to decide which controller processes the request
  3. Dispatch the request to the controller
  4. Controller processes the request and returns the logical view name and model back to DispatcherServlet
  5. Consult View Resolver for appropriate View for the logical view name from Controller
  6. Pass the model to View implementation for rendering
  7. View renders the model and returns the result to DispatcherServlet
  8. Return the rendered result from view to the client

MappingHandler
DispatcherServlet uses MappingHandler to find out which controller is right one for this request.There are many MappingHandler implementations which uses different strategies to map the request to Controller. By default DispatcherServlet will use BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping.

public interface HandlerMapping 
{
      HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}

ViewResolver
With the help of ViewResolver strategy object DispatcherServlet can find out physical view from the logical view name. Similar to MappingHandler there are also many different strategies for resolving the view based on the different view technologies. Most commonly used implementation of ViewResolver is InternalResourceViewResolver.

public interface ViewResolver 
{
      View resolveViewName(String viewName, Locale locale) throws Exception;
}

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.Inversion of Control (IoC) means any sort of programming style where an overall framework or run-time controlled the program flow.

Dependency Injection is a Type of IoC

IoC means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside service (for example, xml file or single app service).

DI means the IoC principle of getting dependent object is done without using concrete objects but abstractions (interfaces). This makes all components chain testable, cause higher level component doesn’t depend on lower level component, only from interface.

Techniques to implement inversion of control

  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection of any given below type:
    1. a constructor injection
    2. a setter injection
    3. an interface injection

DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.

IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.

DI Frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in implementations.

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.

Say the Excel Jar files with utility methods used the application uses the methods in the Utility Class and the flow is controlled by the way the method gets called in order the get the things done.

whereas

In framework like spring the implementation is defined in XML files and by using annotation and the framework calls the methods as per defined in xml.

Without Ioc

  Application -> Methods -> Framework      

With Ioc

  Framework -> XML File ->  Method Call (or) Implementation      

Inversion of Control(IoC) Container:
Common characteristic of frameworks IOC manages java objects

  1. From instantiation to destruction through its BeanFactory.
  2. Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean’s scope, lifecycle events, and any AOP features for which it has been configured and coded.

Flow of control is “inverted” by dependency injection because you have effectively delegated dependencies to some external system

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.

For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:

public class TextEditor
{
    private SpellChecker checker;
    public TextEditor()
    {
        this.checker = new SpellChecker();
    }
}

What we’ve done here is create a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:

public class TextEditor
{
    private ISpellChecker checker;
    public TextEditor(ISpellChecker checker)
    {
        this.checker = checker;
    }
}

Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We’re injecting the TextEditor with the dependency.

Without IoC: you ask for “apple”, and you are always served apple when you ask more.

With IoC:
You can ask for “fruit”. You can get different fruits each time you get served. for example, apple, orange, or water melon.

Inversion of Control, (or IoC), is about getting
freedom (You get married, you lost freedom and you are being controlled. You divorced, you have just implemented Inversion of Control. That’s what we called, “decoupled”. Good computer system discourages some very close relationship.)

flexibility (The kitchen in your office only serves clean tap water, that is your only choice when you want to drink. Your boss implemented Inversion of Control by setting up a new coffee machine. Now you get the flexibility of choosing either tap water or coffee.)

less dependency (Your partner has a job, you don’t have a job, you financially depend on your partner, so you are controlled. You find a job, you have implemented Inversion of Control. Good computer system encourages in-dependency.)

Dependency Injection

What is Dependency

Quick Example:EMPLOYEE OBJECT WHEN CREATED,
              IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT
   (if address is defines as dependency by Employee object)

Now in the above EMPLOYEE Class is dependent on ADDRESS Class.

You can not create the Address Object unless you create Employee Object

EMPLOYEE Class is dependent and ADDRESS Class is dependency

What is the purpose of DI?
With dependency injection, objects don’t define their dependencies themselves, the dependencies are injected to them as needed.The purpose of Dependency Injection is to reduce coupling in your application to make it more flexible and easier to test.

How does it benefit ? The objects don’t need to know where and how to get their dependencies, which results in loose coupling between objects, which makes them a lot easier to test.

When to use Dependency Injection
One of the most compelling reasons for DI is to allow easier unit testing without having to hit a database and worry about setting up ‘test’ data.Dependency Injection gives you the ability to test specific units of code in isolation.

Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It’s a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.

Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g Spring) to do that, but they certainly aren’t required.

Example
A Car depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car object

Without Dependency Injection (DI):

class Car
{
  private Wheel wh   = new ApolloWheel();
  private Battery bt = new ExideBattery();

  //The rest
}

Here, the Car object is responsible for creating the dependent objects.

What if we want to change the type of its dependent object – say Wheel – after the initial ApolloWheel() punctures? We need to recreate the Car object with its new dependency say SpareWheel(), but only the Car manufacturer can do that.

Then what does the Dependency Injection do us for…?

When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time). So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.

After using dependency injection:

class Car
{
  private Wheel wh   = [Inject an Instance of Wheel at runtime];
  private Battery bt = [Inject an Instance of Battery at runtime];

  Car(Wheel wh,Battery bt) 
  {
      this.wh = wh;
      this.bt = bt;
  }

  //Or we can have setters
  void setWheel(Wheel wh) 
  {
      this.wh = wh;
  }
}

Lets take the below example

public class Foo
{
    private Bar _bar;

    public Foo(Bar bar)
    {
        _bar = bar;
    }

    public bool IsPropertyOfBarValid()
    {
        return _bar.SomeProperty == PropertyEnum.ValidProperty;
    }
}

without dependency injection the Bar object is dependent and tightly coupled with Foo class like below

public class Foo
{
    private Bar _bar = new Bar();
    .
    . 
}

But by using dependency injection like before code you can mock the Bar Object at runtime and call the IsPropertyOfBarValid() method over it.