- Java Collection hierarchy ?
-
What is the difference between ArrayList and LinkedList ?
Array List Linked List ArrayList uses a dynamic array. LinkedList uses doubly linked list. ArrayList is not efficient for manipulation because a lot of shifting is required. LinkedList is efficient for manipulation. ArrayList is better to store and fetch data. LinkedList is better to manipulate data. - What is the difference between List and Set? List can contain duplicate elements whereas Set contains only unique elements.
-
What is the difference between ArrayList and Vector ?
Array List Vector ArrayList is not synchronized. Vector is synchronized. ArrayList is not a legacy class. Vector is a legacy class. ArrayList increases its size by 50% of the array size. Vector increases its size by doubling the array size. -
What is the difference between Iterator and ListIterator ?
Iterator ListIterator Iterator traverses the elements in forward direction only. ListIterator traverses the elements in backward and forward directions both. Iterator can be used in List, Set and Queue. LinkedList is efficient for manipulation. ArrayList is better to store and fetch data. ListIterator can be used in List only. - What is the difference between HashSet and TreeSet? HashSet maintains no order whereas TreeSet maintains ascending order.
-
What is the difference between Iterator and Enumeration ?
Iterator Enumeration Iterator can traverse legacy and non-legacy elements. Enumeration can traverse only legacy elements. Iterator is fail-fast. Enumeration is not fail-fast. Iterator is slower than Enumeration. Enumeration is faster than Iterator. - What is the difference between Set and Map ? Set contains values only whereas Map contains key and values both.
-
What is the difference between HashMap and Hashtable ?
HashMap Hashtable HashMap is not synchronized. Hashtable is synchronized. Iterator is fail-fast. Enumeration is not fail-fast. HashMap can contain one null key and multiple null values. Hashtable cannot contain any null key or null value. - What is the difference between HashSet and HashMap? HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated.
-
What is the difference between Comparable and Comparator ?
Comparable Comparator Comparable provides only one sort of sequence. Comparator provides multiple sort of sequences. It provides one method named compareTo(). It provides one method named compare(). It is found in java.lang package. it is found in java.util package. If we implement Comparable interface, actual class is modified. Actual class is not modified. - What is the difference between HashMap and TreeMap? HashMap maintains no order but TreeMap maintains ascending order.
- What is the difference between Collection and Collections? Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.
- What is the advantage of Properties file? If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.
- What does the hashCode() method? The hashCode() method returns a hash code value (an integer number). The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same. But, it is possible that two hash code numbers can have different or same keys.
- Why we override equals() method?
The equals method is used to check whether two objects are same or not.
It needs to be overridden if we want to check the objects based on property.
For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.
- What is the advantage of generic collection? If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.
- What is hash-collision in Hashtable and how it is handled in Java? Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.
- What is the Dictionary class? The Dictionary class provides the capability to store key-value pairs.
- What is the default size of load factor in hashing based collection? The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
-
How to synchronize List, Set and Map elements?
Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
- public static List synchronizedList(List l){}
- public static Set synchronizedSet(Set s){}
- public static SortedSet synchronizedSortedSet(SortedSet s){}
- public static Map synchronizedMap(Map m){}
- public static SortedMap synchronizedSortedMap(SortedMap m){}
Java Collections Interview questions
Hibernate Interview Questions
- What is Hibernate ?
- Briefly explain Hibernate Architecture ?
- What is the use of ORM ?
- What is Java Persistence API(JPA) ?
- What is JDBC ?
- Why are you using hibernate when we have JDBC ?
- What are the advantages of hibernate ?
- Tell me drawbacks or disadvantages of hibernate ?
- Mention design patterns used in hibernate ?
- What is the general flow of Hibernate communication with RDBMS?
- How do you map Java Objects with Database tables?
- What are the most common methods of Hibernate configuration?
- What is HQL ?
- What is hibernate configuration file ?
- What is hibernate mapping file ?
- What is the root node in hbm.xml file ?
- Some important tags or elements used in hbm.xml ? Following are the important tags of hibernate.cfg.xml:
- Mention some important annotations used in hiberante mapping ?
- What are the core interfaces of hibernate ? or What are the key components/elements/objects of hibernate ?
- What are the key components of hibernate Configuration Object ?
- Name some properties required to configure database in standalone situation ?
- Some important methods and their usage ? Session.beginTransaction method begins a unit of work and returns the associated Transaction object. Session.createCriteria creates a new Criteria instance, for the given entity class, or a superclass of an entity class. Session.createQuery creates a new instance of Query for the given HQL query string. Session.createSQLQuery creates a new instance of SQLQuery for the given SQL query string. Session.delete removes a persistent instance from the datastore. Session.get returns the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance. Session.refresh re-reads the state of the given instance from the underlying database. Session.save saves the state of the given instance from the underlying database. Session.update updates the state of the given instance from the underlying database. Session.saveOrUpdate either saves(Object) or updates(Object) the given instance.
- What is meant by persistent class in hibernate ?
- What are the best practices hibernate recommend for persistant classes ?
- What is meant by serializable ?
- What are the states of object in hibernate ?
- Whether Session Factory and Session are thread safe objects ?
- Difference between openSession and getCurrentSession ?
- Difference between session.save() and session.persist() methods ?
- Difference between get() and load() methods in hibernate ?
- Difference between update() and merge() methods in hibernate ?
- Difference between save() , saveOrUpdate() , persist() methods ?
- Mention the types of association mapping available in hibernate ?
- How do you implement associations or relationships in hibernate ?
- Mention the inheritance models in hibernate ?
- What is meant by immutable class ? How can you make a class immutable in hibernate ?
- What is meant by automatic dirty check in hibernate ?
- Which association's are possible with Collections interface or with Collection classes ?
- What is hibernate Proxy ?
- What is meant by lazy loading in hibernate ?
- What is meant by hibernate caching ?
- What is meant by first level cache ?
- What is meant by second level cache ?
- What is meant by Query cache in hiberante ?
- Mention collection types in hibernate ?
- What is bag collection in hibernate ?
- How to fetch ordered collection from database in hibernate ?
- How can Hibernate be configured to access an instance variable directly and not through a setter method ?
- Difference between ordered collection and sorted collection ? Which one is better in hibernate ?
- Tell me about joins in hibernate ?
- What is native sql query ? Can we execute them in hibernate ?
- What is the advantage of native sql query support in hibernate ?
- What is Named SQL Query ?
- What are the Mandatory things for a java object to become Hibernate Entity object ?
- What is Entity class ?
- What happens if we make our Entity class as final in hibenate ?
- Define cascade and inverse option in one-many mapping?
- Explain about log4j logging in hibernate ?
- How to log SQL queries into log files in hibernate ?
- What is transaction Management ? How it works in hibernate ?
- What is Cascading ? Mention different types of Cascading ?
- How to configure application server JNDI DataSource with Hibernate Framework ?
- How to integrate Spring and Hibernate frameworks ?
- What is hibernate Validator Framework ?
- What are concurrency strategies ?
- What is N+1 Select problem in hibernate ? Mention some strategies to solve it ?
- How to implement Optimistic locking in Database?
- What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.
- What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.
- What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
- What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
- How do you define sequence generated primary key in hibernate?
- Define HibernateTemplate? org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
- What are the benefits does HibernateTemplate provide? The benefits of HibernateTemplate are : HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session. Common functions are simplified to single method calls. Sessions are automatically closed. Exceptions are automatically caught and converted to runtime exceptions.
- How do you switch between relational databases without code changes? Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
- If you want to see the Hibernate generated SQL statements on console, what should we do? In Hibernate configuration file set as follows:
- What are derived properties? The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.
- What is component mapping in Hibernate? A component is an object saved as a value, not as a reference. A component can be saved directly without needing to declare interfaces or identifier properties. Required to define an empty constructor. Shared references not supported.
- What is Hibernate Criteria API ? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. Example : List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston")) .addOrder(Order.asc("name") ) .list();
- How do you invoke Stored Procedures?
The general flow of Hibernate communication with RDBMS is : Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files Create session factory from configuration object Get one session from this session factory Create HQL Query Execute query to get list containing Java objects
First we need to write Java domain objects (beans with setter and getter). Write hbm.xml, where we map java class to table and database columns to Java class variables. Example :
The most common methods of Hibernate configuration are: Programmatic configuration XML configuration (hibernate.cfg.xml)
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.
HQL provides four ways of expressing (inner and outer) joins:- An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.
cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
A org.hibernate.Session is designed to represent a single unit of work (a single atmoic piece of work to be performed. Sample code of handling transaction from hibernate session. Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit();
You can implement optimistic locks in your DB table in this way (This is how optimistic locking is done in Hibernate): - Add integer "version" column to your table. - Increase value of this column with each update of corresponding row. - To obtain lock, just read "version" value of row. - Add "version = obtained_version" condition to where clause of your update statement. - Verify number of affected rows after update. If no rows were affected - someone has already modified your entry. Your update should look like UPDATE mytable SET name = 'Andy', version = 3 WHERE id = 1 and version = 2;
Usingtag. Example:- SEQUENCE_NAME
{ ? = call selectAllEmployees() }
Disadvantages of Hibernate
Slower than JDBC: Hibernate is slower than pure JDBC as it generates lot of SQL statements in runtime.
Lots of API to learn: A lot of effort is required to learn Hibernate. So, not very easy to learn hibernate easily.
Not suitable for Batch processing: It advisable to use pure JDBC for batch processing ,which takes less time for processing than hibernate.
Debugging: Sometimes debugging and performance tuning becomes difficult.
Not suitable for Small projects : For small projects having few tables it is useless to work with hibernate.
Does not allow multiple inserts : Hibernate does not allow some type of queries which are supported by JDBC.
For example: It does not allow to insert multiple objects (persistent data) to same table using single query.
Developer has to write separate query to insert each object into database.
Generates complex quires with many joins : For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.
Advantages of Hibernate
Hibernate is an ORM (object relational mapping) tool which is better than JDBC.
Hibernate framework is opensource under the LGPL license and lightweight because it uses POJO classes for data transfer between application and database.
Hibernate is Easy to maintain and it will increases productivity.
Hibernate has versioning and time stamp feature with this we can know how many number of times data is modified.
Hibernate has its own query language, i.e hibernate query language which is database independent so that it supports various databases.
Hibernate supports collections(List,Set,Map).
Hibernate supports inheritance, i.e if we save the derived class object, then its base class object will also be stored into the database which indicates inheritance.
Hibernate supports polymorphism
Hibernate supports associations by managing the data stored across multiple tables by applying relations.
Hibernate has an exception translator , which converts checked exceptions of JDBC in to unchecked exceptions of hibernate. So all exceptions in hibernate are unchecked exceptions , so no need to handle exceptions explicitly by writing try, catch blocks or no need to use throws keyword next to method.
Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One.
- Hibernate supports Lazy loading , annotations along with XML.
Hibernate supports caching mechanism so that the number of interactions between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.
Hibernate has capability to generate primary keys automatically while we are storing the records into database.
Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API.
Pagination in hibernate is quite simple.
Hibernate Architecture
Hibernate application has four layers.
- Java application layer.
- Hibernate framework layer
- Backhand api layer
- Database layer
About JDBC , JTA , JNDI
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI).
JDBC provides a basic level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate.
JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
Hibernate Objects:The Hibernate architecture includes many objects as shown in above detailed view.
- Configuration
- SessionFactory
- Session
- TransactionFactory
- Query
- Criteria
- Configuration Object:
It is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization.
It represents a configuration or properties file required by the Hibernate. The Configuration object provides two key components:
- Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
- Class Mapping Setup : This component creates the connection between the Java classes and database tables.
-
SessionFactory:
Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session.
-
Session:
The session object provides an interface between the application and data stored in the database.
It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.
It is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.This object should not be kept open for a long time because they are not usually thread safe.
-
Transaction:
The transaction object specifies the atomic unit of work that deals with with the database and most of the RDBMS supports transaction functionality. The org.hibernate.Transaction interface provides methods for transaction management.
Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.
-
TransactionFactory:
It is a factory of Transaction objects. It is optional.
-
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.
-
Criteria Object:
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
-
ConnectionProvider:
It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. It is optional.
Hibernate Introduction
What is Hibernate ?
1) Hibernate framework is an Object-relational mapping (ORM) tool which interacts with the database tables.
2) It is open source , light weight , ORM (Object Relational Mapping) tool given by Gavin King.
3) It is called as ORM tool because it maps application domain model objects (POJO class objects) to the relational database tables with the help of a mapping file(xml).
4) It is purely for persistance and simplifies CRUD(Creating , Reading , Updating , Deleting) operations. It internally uses JDBC API to interact with database.
5) It is suitable for all types of applications (Desktop , mobile , stand alone apps) and can run with or with our server.
ORACLE ATG INSTALLATION AND CONFIGURATION
Here in this page we will discuss how to set up Oracle ATG in our local system and configure it.
Steps to be Followed :
1. First set JAVA_HOME and PATH Environment variables.
Where JAVA_HOME points to your JDK directory and PATH point to your
JDK / bin directory.
Note : Install JDK in any of your root directory like C drive not in program files
and your directories should be like below.
JAVA_HOME="C:\Java\jdk1.8.0_xx".
PATH+="C:\Java\jdk1.8.0_xx\bin".
For PATH variable add the JDK/bin directory by using ";" (semicolon);
Where xx denotes your java version update number.
Set the above Environment variables in your system.
For in detail how to install JAVA and environment variables in your system .
Please go to : How to Install Java and Environment variables.
2. Install Weblogic in your system and start the Weblogic server.
On Linux, enter: ./startWebLogic.sh
On Windows, start : startWebLogic.cmd file
Featured Post
H1B Visa Stamping at US Consulate
H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...
-
Ques 1 : Which declaration of the main method below would allow a class to be started as a standalone program. (A) public static int main(c...
-
1. Two Sum Two Sum Solution 2. LRU Cache LRU Cache Solution 3. Number Of Islands 4. Longest Palindromic Substring 5. Lowest...
-
basics Linux fundamentals like system calls , strace , linux mange memory, shared memory, kernel using, boot process, DNS resolving ( how t...