Autowiring vs new Object Keyword

Autowiring new Object()
decouples object creation and life-cycle from object binding and usage Using new Keyword creates new Object everytime.The object graph grows over a period of time.Consider UserDaoImpl perhaps needs a Hibernate session, which needs a DataSource, which needs a JDBC connection – it quickly becomes a lot of objects that has to be created and initialized over and over again. When you rely on new in your code
Autowiring offers object at different scopes – Singleton, request and prototype All objects are JVM Scope

How Autowiring works
The autowiring happens when the application starts up, during the time of deployment.When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically.

Lets see a example where the dependencies are resolved by XML and annotation
ApplicationContext.xml

<beans ...>
    <bean id="userService" class="com.foo.UserServiceImpl"/>
    <bean id="fooController" class="com.foo.FooController"/>
</beans>

When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than 1 UserService bean, then you’ll have to qualify which one it should use.

FooController.java

public class FooController 
{
    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;

    // rest of class goes here
}

Things to Note while Autowiring

  1. Marks a constructor, field, setter method or config method as to be autowired by Spring’s dependency injection facilities.
  2. Only one constructor (at max) of any given bean class may carry this annotation, indicating the constructor to autowire when used as a Spring bean. Such a constructor does not have to be public.
  3. Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.
  4. •In the case of multiple argument methods, the ‘required’ parameter is applicable for all arguments.

Annotation or XML
For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code’s dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration.

However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.

I haven’t used JPA annotations, so I don’t know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn’t care where its information came from.If an annotation provides functionality and acts as a comment in and of itself, and doesn’t tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won’t change the main functionality of the code, and hence doesn’t belong in the source files.

How auto wiring works in Spring

  1. All Spring beans are managed – they “live” inside a container, called “application context”.the application context is bootstrapped and all beans – autowired. In web applications this can be a startup listener.
  2. All application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver
  3. the context instantiates the objects, not you. I.e. – you never make new UserServiceImpl() – the container finds each injection point and sets an instance there.
  4. applicationContext.xml you should enable the so that classes are scanned for the @Controller, @Service, etc. annotations.
  5. Apart from the @Autowired annotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring – to have fields injected with dependencies without any configuration. Other annotations like @Inject, @Resource can also be used

Problem
When using getResultList() to retrieve the Rows of the DB table there may be times where you would end up getting the same rows multiple times.

Why this Happens
Let’s have a table tblGroup the one below

ParentGrp GrpName
Finance Accounts
Finance Sales
  1. You have 2 records in database.Both the records has Finance as value in parentGrp column
  2. Now when you run a select query to select parentGrp = ‘Finance’ you will get 2 records
  3. Lets query them WHERE parentGrp = ‘Finance’
  4. SQL Query returns 2 rows
  5. Hibernate loads first one, and puts into session, with parentGrp as a key.Now this will happen if you have specified it as @ID in entity class or you havent specified it while joining two tables in entity class.The object is placed into the result list.
  6. Hibernate loads second one, notices that an object with the same @Id is already in the session, and just places the reference into the result List. Row data are ignored.
  7. Now we have two copies of the same record

Solution:
We can solve this by introducing a primary key column something like tblGroup_pk_id.Now this helps to uniquely identify the records in the table so it won’t get overridden when the next rows retrieved.

Now the GrpId should be entitled with @ID annotation in the entity class.

GrpId ParentGrp GrpName
101 Finance Accounts
102 Finance Sales
createQuery() createSQLQuery() createCriteria()
Creates Query Object Creates Query Object Creates Criteria Object
Uses HQL Syntax Uses DB Specific Syntax Uses Entity Class
The Columns of the rows retrieved would be name of the POJO Model Class The Columns of the rows retrieved would be name of Native DB fields Create sql query using Criteria object for setting the query parameters
CRUD operation could be done CRUD operation could be done Only Read Operation is allowed
Supports Interoperability between different DB’s Does not support Interoperability since the query format should be changed when the DB is changed Supports Interoperability between different DB’s
Does not work without Model Class Bean with columns of Table alone is Enough.No need for Entity class generation Does not work without Model Class
No need for mapping between Entity class object and Table Columns The Bean Objects should be mapped with table Columns No need for mapping

createQuery – session.createQuery()

------------------------------------------------------
**DB_TBL_Col(tblEmployee)**| **POJO(Employee)**
EMP_ID                     | employeeID
------------------------------------------------------
Query query = session.createQuery("from Employee E where E.employeeID = 'A%'");
List<Person> persons = query.list();

The below batch script helps to read the selected trailing lines from Log File

@echo off
cls
setlocal EnableDelayedExpansion
set "cmd=findstr /R /N "^^" C:\Users\Mugil\Desktop\test.txt | find /C ":""

for /f %%a in ('!cmd!') do set totalLines=%%a
rem echo "totalLines-"%totalLines%


@set linesToConsider=4
set /a lineToStart="%totalLines%-%linesToConsider%" 

rem echo "lineToStart-"%lineToStart%

set content=
for /f "skip=%lineToStart% delims=" %%i in ('type C:\Users\Mugil\Desktop\test.txt') do set content=!content! %%i


@echo "content - "%content%


If NOT "%content%"=="%content:SUCCESS=%" (
    echo Build Successful
) else (
    echo Build Failed
)

pause

Working with EntityManagerFactory – Best Practices

  1. EntityManagerFactory instances are heavyweight objects. Each factory might maintain a metadata cache, object state cache, EntityManager pool, connection pool, and more. If your application no longer needs an EntityManagerFactory, you should close it to free these resources.
  2. When an EntityManagerFactory closes, all EntityManagers from that factory, and by extension all entities managed by those EntityManagers, become invalid.
  3. It is much better to keep a factory open for a long period of time than to repeatedly create and close new factories. Thus, most applications will never close the factory, or only close it when the application is exiting.
  4. Only applications that require multiple factories with different configurations have an obvious reason to create and close multiple EntityManagerFactory instances.
  5. Only one EntityManagerFactory is permitted to be created for each deployed persistence unit configuration. Any number of EntityManager instances may be created from a given factory.
  6. More than one entity manager factory instance may be available simultaneously in the JVM. Methods of the EntityManagerFactory interface are threadsafe.
Posted in JPA.

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;

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