Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Top 10 Spring Interview Questions Answers J2EE



What is IOC or inversion of control?
Inversion of control means now we have inverted the control of creating the object from our own using new operator to container or framework. Now it’s the responsibility of container to create object as required.
We maintain one xml file where we configure our components, services, all the classes and their property. We just need to mention which service is needed by which component and container will create the object for us. This concept is known as dependency injection because all object dependency (resources) is injected into it by framework.

Explain Bean-LifeCycle.
Spring beans reside inside the IOC container. Spring beans are nothing but Plain old java object (POJO).
Following steps explain their life cycle inside container.
1. Container will look the bean definition inside configuration file (e.g. bean.xml).
2 using reflection container will create the object and if any property is defined inside the bean definition then it will also be set.
3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called before the properties for the Bean are set.
6. If an init() method is specified for the bean, it will be called.
7. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.
8. If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.

Read full article from Top 10 Spring Interview Questions Answers J2EE

Dealing with org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate Java



"lazy initialization" allows framework to lazily initialize dependencies, relationship or association lazily from database on need basis.

For example, if you are dealing with User object, which has relationship with Permission object like one user can have multiple permissions, then Hibernate may choose not to initialize the collection which holds all permissions at the time it initialized User object and instead returns a proxy object. At this point, if you close your session and letter tries to access an attribute from Permission object, you will get "org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate".

hibernate needs to go database to initialize the proxy object, but connection is already closed.

org.hibernate.LazyInitializationException: could not initialize proxy - no Session. this error mainly comes when you have closed the connection and trying to access the proxy object which is no fully initialized.

1) Code tries to access a lazy initialized property or collection and session is not available.
Easy Solution
Use lazy=false in hibernate mapping file.
main disadvantage of this approach can be slow performance. Since dependent objects are loaded at the time of persistent object loading, it will increase loading time. Also since now object is fully initialized, there memory consumption would be very high. This can become more severe if your Collection classes are big list of other objects, which are not always accessed.


Better Solution :
The real problem is that you are trying to access a collection in an object that is detached or associated session is closed. You need to re-attach the object before accessing the collection to the current session. You can either reattach the object by calling session.update(object); Or you can move the code which access proxy object to the line before you close the session.

Hibernate with JPA Annotation
If you are using hibernate with JPA annotations and manually managing your transactions: In your service class there should be a setter for entity manager with @PersistenceContext. change this to @PersistenceContext(type = PersistenceContextType.EXTENDED). Then you can access lazy property in any where. By the way, its worth remember that, Spring EXTENDED persistence context type is for long conversation pattern, not the session-per-request pattern.

4) Application wide Solution
When we want an easy solution and doesn't care anything about performance e.g. for testing or prototyping purpose. In that case you can make following configuration change into your application to avoid this error, but remember the impact eager initialization can cause if this code makes its way to production.

if you are using XML configuration: add default-lazy="false" to your element
if you are using annotation configuration: add @Proxy(lazy=false) to all your entity classes.

Read full article from Dealing with org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate Java

10 Hibernate Interview Questions and Answers for Java J2EE Programmers



What is SessionFactory in Hibernate? is SessionFactory thread-safe?
SessionFactory is a factory to create hibernate Session objects. SessionFactory is often built during start-up and used by application code to get session object. It acts as single data store and its also thread-safe so that multiple thread can use same SessionFactory. Usually a Java JEE application has just one SessionFactory, and individual threads, which are servicing client’s request obtain hibernate Session instances from this factory, that’s why any implementation of SessionFactory interface must be thread-safe. 
Also internal state of SessionFactory, which contains all meta data about Object/Relational mapping is Immutable and can not be changed once created.

What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate?
Session represent a small unit of work in Hibernate, they maintain connection with database and they are not thread-safe, it means you can not share Hibernate Session between multiple threads. Though Session obtains database connection lazily it's good to close session as soon as you are done with it.

What is difference between sorted and ordered collection in hibernate?
A sorted collection is sorted in memory by using Java Comparator, while a ordered collection uses database's order by clause for ordering. For large data set it's better to use ordered collection to avoid any OutOfMemoryError in Java, by trying to sort them in memory.

What is difference between transient, persistent and detached object in Hibernate?
In Hibernate, Object can remain in three state transient, persistent or detached.  An object which is associated with Hibernate session is called persistent object. Any change in this object will reflect in database based upon your flush strategy i.e. automatic flush whenever any property of object change or explicit flushing by calling Session.flush() method. 

If an object which is earlier associated with Session, but currently not associated with it are called detached object. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session. 

Transient objects are newly created instance of persistence class, which is never associated with any Hibernate Session. Similarly you can call persist() or save() methods to make transient object persistent.

Difference between get and load method
http://javarevisited.blogspot.com/2012/07/hibernate-get-and-load-difference-interview-question.html
1. Behavior when Object is not found in Session Cache
get method of Hibernate Session class returns null if object is not found in cache as well as on database while load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null.
Database hit
Get method always hit database while load() method may not always hit the database, depending upon which method is called.
Proxy
Get method never returns a proxy, it either returns null or fully initialized Object, while load() method may return proxy, which is the object with ID but without initializing other properties, which is lazily initialized. If you are just using returned object for creating relationship and only need Id then load() is the way to go.

Performance
get method will return a completely initialized object if  Object is not on the cache but exists on Database, which may involve multiple round-trips to database based upon object relational mappings 

while load() method of Hibernate can return a proxy which can be initialized on demand (lazy initialization) when a non identifier method is accessed. Due to above reason use of load method will result in slightly better performance, but there is a caveat that proxy object will throw ObjectNotFoundException later if corresponding row doesn’t exists in database, instead of failing immediately so not a fail fast behavior.

5. load method exists prior to get method which is added on user request.

When to use Session get() and load() in Hibernate
1. Use get method to determine if an instance exists or not because it can return null if instance doesn’t exists in cache and database and use load method to retrieve instance only if you think that instance should exists and non availability is an error condition.

2. consider using load method  if  your code doesn't access any method other than identifier or you are OK with lazy initialization of object, if persistent object is not in Session Cache because load() can return proxy.

Difference between save and saveOrUpdate in Hibernate
Difference between save vs persist and saveOrUpdate in Hibernate
save() generates a new identifier and INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence of record.
Clearly saveOrUpdate is more flexible in terms of use but it involves an extra processing to find out whether record already exists in table or not.

In summary  save() method saves records into database by INSERT SQL query, Generates a new identifier and return the Serializable identifier back. On the other hand  saveOrUpdate() method either INSERT or UPDATE based upon existence of object in database. If persistence object already exists in database then UPDATE SQL will execute and if there is no corresponding object in database than INSERT will run.

Difference between save and persist method in Hibernate
1. The return type: Similar to save method persist also INSERT records into database but return type of persist is void while return type of save is Serializable object.

2. both methods make a transient instance persistent. However, persist() method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.

3. persist() method guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. save() method does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator), this INSERT happens immediately, no matter if you are inside or outside of a transaction.

4. Because of its above behavior of persist method outside transaction boundary, its useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.

What is named SQL query in Hibernate?
Named queries are SQL queries which are defined in mapping document using <sql-query> tag and called using Session.getNamedQuery() method. Named query allows you to refer a particular query by the name you provided, by the way you can define named query in hibernate either by using annotations or xml mapping file, as I said above. @NameQuery is used to define single named query and @NameQueries is used to define multiple named query in hibernate.

What does Session lock() method do in Hibernate?
Session's lock() method reattach object without synchronizing or updating with database. So you need to be very careful while using lock() method. By the way you can always use Session's update() method to sync with database during reattachment.

What is Second level Cache in Hibernate?
Second level Cache is maintained at SessionFactory level and can improve performance by saving few database round trip. Another worth noting point is that second level cache is available to whole application rather than any particular session.

What is query cache in Hibernate ?
QueryCache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. Hibernate support various open source caching solution to implement Query cache e.g. EhCache.

Can we make an Hibernate Entity Class final?
Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn't allow extension of final class, thus limiting your performance improvement options. Though, you can avoid this penalty, if your persistent class is an implementation of interface, which declares all public methods defined in Entity class.

Read full article from 10 Hibernate Interview Questions and Answers for Java J2EE Programmers

Difference between get and load in Hibernate



Difference between get and load method
1. Behavior when Object is not found in Session Cache
get method of Hibernate Session class returns null if object is not found in cache as well as on database while load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null.
Database hit
Get method always hit database while load() method may not always hit the database, depending upon which method is called.
Proxy
Get method never returns a proxy, it either returns null or fully initialized Object, while load() method may return proxy, which is the object with ID but without initializing other properties, which is lazily initialized. If you are just using returned object for creating relationship and only need Id then load() is the way to go.

Performance
get method will return a completely initialized object if  Object is not on the cache but exists on Database, which may involve multiple round-trips to database based upon object relational mappings 

while load() method of Hibernate can return a proxy which can be initialized on demand (lazy initialization) when a non identifier method is accessed. Due to above reason use of load method will result in slightly better performance, but there is a caveat that proxy object will throw ObjectNotFoundException later if corresponding row doesn’t exists in database, instead of failing immediately so not a fail fast behavior.

5. load method exists prior to get method which is added on user request.

When to use Session get() and load() in Hibernate
1. Use get method to determine if an instance exists or not because it can return null if instance doesn’t exists in cache and database and use load method to retrieve instance only if you think that instance should exists and non availability is an error condition.

2. consider using load method  if  your code doesn't access any method other than identifier or you are OK with lazy initialization of object, if persistent object is not in Session Cache because load() can return proxy.
Read full article from Difference between get and load in Hibernate

Difference between save vs persist and saveOrUpdate in Hibernate



Difference between save and saveOrUpdate in Hibernate
save() generates a new identifier and INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence of record.
Clearly saveOrUpdate is more flexible in terms of use but it involves an extra processing to find out whether record already exists in table or not.

In summary  save() method saves records into database by INSERT SQL query, Generates a new identifier and return the Serializable identifier back. On the other hand  saveOrUpdate() method either INSERT or UPDATE based upon existence of object in database. If persistence object already exists in database then UPDATE SQL will execute and if there is no corresponding object in database than INSERT will run.

Difference between save and persist method in Hibernate
1. The return type: Similar to save method persist also INSERT records into database but return type of persist is void while return type of save is Serializable object.

2. both methods make a transient instance persistent. However, persist() method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.

3. persist() method guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. save() method does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator), this INSERT happens immediately, no matter if you are inside or outside of a transaction.

4. Because of its above behavior of persist method outside transaction boundary, its useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.

Read full article from Difference between save vs persist and saveOrUpdate in Hibernate

Top 10 Servlet Interview Question Answers - J2EE



Question 1: In web.xml file   <load-on-startup>1</load-on-startup> is defined between <servlet></servlet> tag what does it means.
Ans: whenever we request for any servlet the servlet container will initialize the servlet and load it which is defined in our config file called web.xml by default it will not initialize when our context is loaded .defining like this <load-on-startup>1</load-on-startup> is also known as pre initialization of servlet means now the servlet for which we have define this tag has been initialized in starting when context is loaded before getting any request

Why super.init (config) wiil be the first statement inside init(config) method.
Ans: This will be the first statement if we are overriding the init(config ) method by this way we will store the config object for future reference and we can use by getServletConfig ()  to get information about config object if will not do this config object will be lost and we have only one way to get config object because servlet pass config object only in init method . Without doing this if we call the servletConfig method will get NullPointerException.
javax.servlet.GenericServlet.init(ServletConfig)
  public void init(ServletConfig config)
    throws ServletException
  {
    this.config = config;
    init();
  }

Can we call destroy() method inside the init() method is yes what will happen?
Ans:Yes we can call like this but  if we have not override this method container will call the default method and nothing will happen.after calling this if any we have override the method then the code written inside is executed.

How can we refresh servlet on client and server side automatically?
Ans: On client side we can use Meta http refresh and server side we can use server push.

How can you get the information about one servlet context in another servlet?
Ans: In context object we can set the attribute which we want on another servlet and we can get that attribute using their name on another servlet.
Context.setAttribute (“name”,” value”)
Context.getAttribute (“name”)

what is servlet collaboration?
Ans communication between two servlet is called servlet collaboration which is achieved by 3 ways.
1. RequestDispatchers include () and forward() method .
2. Using sendRedirect()method of Response object.
3. Using servlet Context methods

What is the difference between ServletConfig and ServletContext?
Ans: ServletConfig as the name implies provide the information about configuration of a servlet which is defined inside the web.xml file or we can say deployment descriptor.its a specific object for each servlet.

ServletContext is application specific object which is shared by all the servlet belongs to one application in one JVM .this is single object which represent our application and all the servlet access application specific data using this object.servlet also use their method to communicate with container.

Read full article from Top 10 Servlet Interview Question Answers - J2EE

Labels

Algorithm (219) Lucene (130) LeetCode (97) Database (36) Data Structure (33) text mining (28) Solr (27) java (27) Mathematical Algorithm (26) Difficult Algorithm (25) Logic Thinking (23) Puzzles (23) Bit Algorithms (22) Math (21) List (20) Dynamic Programming (19) Linux (19) Tree (18) Machine Learning (15) EPI (11) Queue (11) Smart Algorithm (11) Operating System (9) Java Basic (8) Recursive Algorithm (8) Stack (8) Eclipse (7) Scala (7) Tika (7) J2EE (6) Monitoring (6) Trie (6) Concurrency (5) Geometry Algorithm (5) Greedy Algorithm (5) Mahout (5) MySQL (5) xpost (5) C (4) Interview (4) Vi (4) regular expression (4) to-do (4) C++ (3) Chrome (3) Divide and Conquer (3) Graph Algorithm (3) Permutation (3) Powershell (3) Random (3) Segment Tree (3) UIMA (3) Union-Find (3) Video (3) Virtualization (3) Windows (3) XML (3) Advanced Data Structure (2) Android (2) Bash (2) Classic Algorithm (2) Debugging (2) Design Pattern (2) Google (2) Hadoop (2) Java Collections (2) Markov Chains (2) Probabilities (2) Shell (2) Site (2) Web Development (2) Workplace (2) angularjs (2) .Net (1) Amazon Interview (1) Android Studio (1) Array (1) Boilerpipe (1) Book Notes (1) ChromeOS (1) Chromebook (1) Codility (1) Desgin (1) Design (1) Divide and Conqure (1) GAE (1) Google Interview (1) Great Stuff (1) Hash (1) High Tech Companies (1) Improving (1) LifeTips (1) Maven (1) Network (1) Performance (1) Programming (1) Resources (1) Sampling (1) Sed (1) Smart Thinking (1) Sort (1) Spark (1) Stanford NLP (1) System Design (1) Trove (1) VIP (1) tools (1)

Popular Posts