Persistence and Hibernate
Persistent means stored in some kind of non-volatile storage medium, so typically on a disk. The idea is that turning off the machine doesn’t result in your data being lost although persistence alone doesn’t cover recovery or fault tolerance, which is supposed to protect from disks being damaged, systems being shut down ungracefully, etc.
Persistent classes (or persistence-capable classes, more correctly) just mean that there is a transparent mechanism that allows you to store an object of that class. (Volker leidl)
Building Hibernate Project
You can refer to the Using Maven to find out how to structure the project. Just be aware that you should include hibernate and JDBC driver libraries (ie orcle ojdbc) for your application.
The configuration file will be something like this
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<!– Database connection settings –>
<!– JDBC connection pool (use the built-in) –>
<!– Enable Hibernate’s automatic session context management –>
<!– Disable the second-level cache –>
<!– Echo all executed SQL to stdout –>
<!– Drop and re-create the database schema on startup –>
<!–Read from the mapping file–>
For more details about the database configuration could be found here
You also need a mapping file to map the object to database table.
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<class name="com.hongliang.firstHibernate.events.Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<property name="date" type="timestamp" column="EVENT_DATE"/>
Few things you should understand and beware for the mapping file
- You should provide the correct path for the class that need to be mapped.
- Make sure the name of the property match the one you had in your class.
- “table” will be the name in the database for the object and “Column” will be the column names in the table.
- The nested generator element specifies the identifier generation strategy, in this case we used native, which picks the best strategy depending on the configured database (dialect).
- Hibernate will try to determine the correct conversion and mapping type itself if the type attribute is not present in the mapping. In some cases this automatic detection (using Reflection on the Java class) might not have the default you expect or need and you need to specify it by yourself like type="timestamp"
This mapping file should be saved as Event.hbm.xml, right in the directory next to the Java class source file /folder. The naming of mapping files can be arbitrary, however the hbm.xml suffix is a convention in the Hibernate developer community.
List result = session.createQuery("from Event").list();
HQL is querying for object, there Event is the name of the Class not the table.