Hibernate and Java annotations
So….. I wanted to use something as neat and powerful as Rails’ ActiveRecord. I had used hibernate a bit a long time ago, and frankly I didn’t know about any alternatives. Some lame Googling didn’t come up with anything so I decided to have a look at the newest incarnation.
Now I have some principles, and one of them is that simple things should be easy. There should be a Hello World example so you can get your feet wet without reading a 600-page manual first.
Apparently, there are many others that write documentation that don’t feel that way. A complicating matter is that Hibernate started out using XML-files for configuration, and Annnotations (you know, all those tiddlybits starting with @ in your Java code) came pretty late.
I won’t go into how Hibernate is an JPA-implementation. That is not necessary for a beginner to know. You can also use Maven, but unless you are heavily invested into that technology, talking about that will only take you three steps back. So I won’t.
What is necessary however is this:
I’m assuming Eclipse, but Netbeans or IntelliJ work the same way.
- Download hibernate, and take all jars from ./lib/required and put into your project (I always put them into a ./lib subdir).
- Add those jars to your classpath (In Eclipse Right-click project – Build Path – Configure Build Path)
- Create a ./cfg subdir. Add that dir to your classpath the same way. This is necessary and a great place to put hibernate (and others like log4j2) config files. But if you absolutely want, you can add the classpath however you like, just make sure the app can locate the XML files.
- In ./cfg put a file hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name=”hibernate.dialect”> org.hibernate.dialect.MySQLDialect </property>
<property name=”hibernate.connection.driver_class”> com.mysql.jdbc.Driver </property>
<property name=”hibernate.connection.url”> jdbc:mysql://your_db_ip/your_schema</property>
<property name=”hibernate.connection.username”>your_db_username</property>
<property name=”hibernate.connection.password”>your_db_password</property>
<!– This statement will auto-create and update your tables from the Entity –>
<property name=”hibernate.hbm2ddl.auto”>update</property>
<!– List of Entity classes! Absolutely necessary! –>
<mapping class=”entity.Product”/>
<mapping class=”entity.Employee”/>
<!– The old XML way – not that we have commented out them!
<mapping resource=”Employee.hbm.xml”/>
<mapping resource=”Product.hbm.xml”/>
–>
</session-factory>
</hibernate-configuration>
- After this, call in ytou Java init:
try {sessionFactory = new Configuration().configure().buildSessionFactory();}
catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); }
Make sure this runs without errors, then go to next entry in this 2-part series !