Google

Dec 7, 2010

15+ Hibernate Interview Questions and Answers: Overview

If you ask me  to list two frameworks that are very prevalently used in Java projects and very popular in job interviews, it would be (1) Spring framework (2) Hibernate framework.

Q. How will you configure Hibernate?
A. The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively, hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.
 
Q. What is a SessionFactory? Is it a thread-safe object?
A. SessionFactory is Hibernate's concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

SessionFactory sessionFactory = new Configuration( ).configure( ).buildSessionfactory( );


Q. What is a Session? Can you share a session object between different threads?
A. Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession( ) method.

public class HibernateUtil { 

    public static final ThreadLocal local = new ThreadLocal(); 

    public static Session currentSession() throws HibernateException { 
         Session session = (Session) local.get(); 
         //open a new session if this thread has no session 
        if(session == null) { 
            session = sessionFactory.openSession(); 
            local.set(session); 
       } 
        return session; 
    } 
} 


It is also vital that you close your session after your unit of work completes.

Note: Keep your Hibernate Session API handy. Quite often, hibernate is used with Spring framework, using the Template design pattern.


Q. Explain hibernate object states? Explain hibernate objects life cycle?
A.

Persistent objects and collections are short lived single threaded objects, which store the persistent state. These objects  synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List  etc or define your own synchronization points with session.flush(), transaction.commit() calls). If you remove an item  from a persistent collection like a Set, it will be removed from the database either immediately or when flush() or commit() is called depending on your flush strategy. They are Plain Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated session is closed, persistent objects become detached objects and are free to use directly as data transfer objects in any application layers like business layer, presentation layer etc.  

Detached objects and collections are instances of persistent objects that were associated with a session but currently not associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc. and become persistent objects.

Transient objects and collections are instances of persistent objects that were never associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Transient objects become persistent objects when associated to a session by calling methods like session.save( ), session.persist( )  etc.


Q. What are the benefits of detached objects?
A.

Pros:
  • When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.
Cons:
  • In general, working with detached objects is quite cumbersome, and it is better not to clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.
  • Also from pure rich domain driven design perspective, it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.


Q. When does an object become detached?
A.

Session session1 = sessionFactory.openSession();
Car myCar = session1.get(Car.class, carId);//”myCar” is a persistent object at this stage.
session1.close();          //once the session is closed “myCar” becomes a detached object

you can now pass the “myCar” object all the way upto the presentation tier. It can be modified without any effect to your database table.

myCar.setColor(“Red”);    //no effect on the database

When you are ready to persist this change to the database, it can be reattached to another session as shown below:

Session session2 = sessionFactory.openSession(); 
Transaction tx = session2.beginTransaction();
session2.update(myCar);           //detached object ”myCar” gets re-attached 
tx.commit();                      //change is synchronized with the database.
session2.close()


Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?
A.
  • Hibernate uses the "version" property, if there is one.
  • If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
  • Write your own strategy with Interceptor.isUnsaved( ).
Note: When you reattach detached objects, you need to make sure that the dependent objects are reattached as well.


Note: Extracted from my book "Java/J2EE Job Interview Companion".


More Hibernate Related Interview Questions and Answers


If you want to get a better handle on Hibernate

Labels:

Dec 3, 2010

Handy tips to get some work experience on your Java/JEE CV

You can't get a job if you don't have enough experience, but how do you get an experience, if no one is willing to give you one? This is a vicious cycle, and you need to break it by offering what the companies are looking for -- Experience

If the market is hot, a well-rounded candidate with a decent resume and little or no experience could easily walk into an interview. But, during a difficult job market with economic meltdowns, one needs to have a highly effective resume with at least 1- 2 year experience or more. So, how do you beat this catch-22 situation?

Try for voluntary work through a number of different avenues discussed in Job Hunting Tips. Smaller companies, charitable organizations, and community services  are more keen to get people on a voluntary basis.  Voluntary work shows commitment and initiative, even if it is not mentally stimulating. It can increase your industry knowledge, give you the much needed hands-on experience, enhance your soft skills, and give you something to write on your resume without any prolonged gap of employment. Since the task of applying for a paid full-time position can take up considerable time, you could start working voluntarily 2-3 days a week, even weekends if required. Even if it does not involve Java/JEE, provided you can gain any other sought-after technical skills like SQL, XML, domain knowledge, and software development processes and methodologies that are easily transferable to your future dream job.

Now, on a more positive note, while gaining hands-on experience and learning on the job, you will likely uncover paid opportunities by being an excellent contributor with enthusiasm and personal growth or by networking with similar professionals you would not have met otherwise. Voluntary work is generally a win/win situation for both the employer and the employee. Even though larger brand name organizations may look more impressive on your resume and can give you a greater chance of potential internal paid opportunities, smaller companies are more likely to offer you a voluntary work, and also in general, you will not only get to learn more things faster, but also your efforts will get noticed and recognized quicker. You can even try contacting your local charities for any potential openings in IT. Don't be too concerned about the size or brand name of the organization, but pay more attention to type of skills, experience, and capabilities you will be gaining. Brand name or popularity may take you to the interview stage, but cannot guarantee success in interviews without the right knowledge, skills, capabilities, and experience. If you properly use the guidelines in my Java/JEE Resume Companion, you can draw on your other strengths and achievements to look more impressive on your resume than to just rely on brand name or popularity.

Contribute to open-source projects to gain much needed hands-on experience in sought-after technologies and frameworks. The choices are plenty ranging from widely used products such as NetBeans, Eclipse, GlassFish, etc to smaller hobby projects, which have been open-sourced by other developers. Pick the one depending on your level of experience, interest, and motivation. If your motivation is to learn Spring & Hibernate, then pick a project that uses both. How do you benefit from open-source project contributions?

  • Gives you a pretty good big picture of different technologies, tools and frameworks used in a typical application. A typical Java application uses Eclipse, NetBeans, or similar IDE, Java, JUnit, Log4j, Ant, Maven2, Spring, Hibernate, Apache commons library, etc. Try to analyze and understand how all these pieces fit together.
  • You get to read a lot of code and learn from it. You can not only learn the best practices, but also can learn to identify potential issues.
  • Write your own small programs just to learn the language and libraries (APIs) used in the open source projects. For example, Java APIs and Apache commons library that has very useful utility methods such as StringUtils, CollectionUtils, MapUtils, BeanComparator, Validate, etc. Observe the coding and formatting standards.
  • learn how to use the tools like CVS, SVN, Eclipse, Maven2, Net Beans, etc.
  • Experiment by making changes to your local copy of the code. Try going through JEE deployment descriptors, Spring, and Hibernate configuration files to understand how different pieces are wired up.
Here are some useful links to get started:


Self-taught projects and tutorials to build up confidence and acquire some level of experience with the sought-after technologies and frameworks. Some open-source projects can be a bit overwhelming for some beginners. So, choose carefully. Alternatively, you could take up some self-taught projects by using sought-after technologies and frameworks. While this can be an easier option, it is not easy to be disciplined and looks less impressive on your resume compared to open-source contribution. Having said that, this option is better than not doing anything at all. It at least, shows commitment and initiative with some level of familiarity with popular technologies and frameworks. Improve credibility by providing your URL or mentioning availability of your source code. What is even better is that, if your self-taught project is based on a creative idea and if you think it can be useful to others, you can open-source it or even try selling it.

Each approach has its own pros and cons. If you are a beginner and looking for work, voluntary work will not only give you the experience employers are looking for, but also can open doors for paid job opportunities. If you are already in an employment, and either not mentally challenged or not acquiring the required skills and experience, try contributing to open-source projects. If you are not in much luck with first two options, and sitting idly or you have a bright idea, then try working on a self-taught project, while looking for a paid job.


-->

Labels: ,

Handy job hunting tips in tough times for Java/JEE professionals




If the market is hot, a well-rounded candidate with a decent resume and little or no experience could easily walk into an interview. But, during a difficult job market with economic melt downs, one needs to explore other avenues. Job hunting can be emotionally exhausting, especially if the search lasts for a long time. You can increase your chances of finding a job by casting a wide net, writing an effective resume, practicing your interview technique, and brushing up on the fundamentals. If you rely only on advertised positions through newspapers and online jobsites, you are not only expending 100% of you effort on 10% to 30% of the possibilities, but also will be competing with many other professionals who use the same avenue. Finding a job is a numbers game, but you must also have a marketing plan. There are hundreds, if not thousands of people sending e-mails to every recruiter in the country or mass-mailing resumes to hundreds of companies hoping that they will find an opening without a plan to sell themselves effectively. You need to somehow standout from the rest with a good marketing plan (i.e. a resume & a cover letter) or try to get a foot in the door through networking. Even with networking, you need to have good resume/CV.  Your resume must highlight your technical and softskills. It must also address how you can add value, and how you differ from someone who has done the same thing and have similar qualifications as you. If you are not sure, check my Java/JEE resume companion.

A real job search has the following main avenues. Tap into both published and hidden job markets.

Published Job Market: Review job leads via printed news papers, journals, online job banks, recruiter websites, Java forums, etc.

Hidden Job Market:

Networking: Start by asking your existing network, past employers, recruitment agents, colleagues, friends, etc. Next, expand your network through paid or unpaid work in your field, registering with online network sites like http://www.linkedin.com/, joining relevant professional associations and attending conferences. Here are some Java related links to start with:


Also, do your research by searching on google for "Java community", "Java symposiums", "Java user groups" , "Java discussion Groups", etc.

Unsolicited applications: Sending employers a cover letter and a resume to express your interest in working for them. If you wish to use this method, it is important to target each application carefully, and to follow up with a phone call or call before sending the application to ensure that some contact has been made prior to your details appearing before someone in print.

Cold calling or direct contact: Cold calling (over the phone or in person) means approaching employers directly and preferably by establishing relationships with people who work for the organization through previous networking activities, to make this technique less daunting. I generally prefer building up good rapport with selected recruitment agents who had represented me in the past, and getting him/her to do the door knocking on my behalf. Carefully prepare what you are going to say and be ready to answer some preliminary questions about what you have to offer the organization. Have your resume up to date and tailored to the job you are targeting.


Reseach the market

Research the market to identify the sought-after technologies/frameworks and gain some familiarity or hands-on-experience on those.

Keep your knowldge up to date by visiting the industry specific forums like


Give yourself an edge on the market place


Develop an online portfolio and a persona (e.g. blogging, networking via LinkedIn.com, etc)  to give your prospective employers a complete picture of who you are -– your experience, your education, your accomplishments, your skill sets -– and what you have the potential to become -– much more than just a cover letter and resume can provide. You can use your career portfolio in job interviews to showcase a point, to illustrate the depth of your skills and experience, or to use as a tool to get a second interview. You can provide a link to your blog (if it is professional enough) on your resume to showcase your capabilities, true potential, values, and most importantly the passion.

Creating your portfolio:

Building an online persona


Self-publishing books


Develop your soft-skills

The technical know-how needs to be complemented with good soft-skills.

Labels: