BugBlog.de

Der Debugger Blog fuer Entwickler und Developer

Java Tutorial: Hibernate, MySQL, Annotations

November23

Heute Morgen das Beispiel mit XML veröffentlicht, folgt jetzt das gleiche Beispiel mit Annotations. Diese sind erst seit Java 5 verfügbar und bieten den Vorteil man muss nicht immer zwei Dateien anpassen. Mit Annotations ist es möglich direkt im Java Code festzulegen wie das Objekt später in der Datenbank abgelegt wird.

Bereits in der Übersicht kann man sehen, das die Konfigurationsdatei für das Objekt wegfällt. Die Konfiguration die vorher in der der XML Datei vorgenommen wurde wird jetzt direkt in die Java Klasse implementiert. Natürlich entfällt dann auch die Angabe über die Konfigurationsdatei in der Hibernate Konfiguration.
Aber genug Geschwätz sehen wir uns das Objekt an:

JAVA:
  1. // File: Tisch.java
  2.  
  3. package obj;
  4.  
  5. import java.io.Serializable;
  6. import java.text.MessageFormat;
  7. import javax.persistence.Entity;
  8. import javax.persistence.GeneratedValue;
  9. import javax.persistence.GenerationType;
  10. import javax.persistence.Id;
  11. import javax.persistence.SequenceGenerator;
  12.  
  13. public class Tisch implements Serializable{
  14.  
  15.     private static final long serialVersionUID = 1L;
  16.  
  17.     @Id
  18.     @GeneratedValue(strategy=GenerationType.IDENTITY)
  19.     @SequenceGenerator(name = "tisch_gen", sequenceName = "tisch_id_seq")   
  20.     private Integer id;
  21.     private Integer Fuesse;
  22.     private String Material;
  23.    
  24.     public Tisch(){ }
  25.  
  26.     private Integer getId() {
  27.         return id;
  28.     }
  29.  
  30.     private void setId(Integer id) {
  31.         this.id = id;
  32.     }
  33.  
  34.     public Integer getFuesse() {
  35.         return Fuesse;
  36.     }
  37.  
  38.     public void setFuesse(Integer fuesse) {
  39.         Fuesse = fuesse;
  40.     }
  41.  
  42.     public String getMaterial() {
  43.         return Material;
  44.     }
  45.  
  46.     public void setMaterial(String material) {
  47.         this.Material = material;
  48.     }
  49.    
  50.     public String toString() {
  51.         return MessageFormat.format("{0}: Fuesse={1}, Material={2}", new Object[] {
  52.                 getClass().getSimpleName(), Fuesse, Material });
  53.     }
  54. }

Wie oben bereits oft erwähnt entfällt die Konfigurationsdatei. Also kommen wir gleich zu der Session.

JAVA:
  1. // File: SingSessionFactory.java
  2.  
  3. package hibe;
  4.  
  5. import org.hibernate.SessionFactory;
  6. import org.hibernate.cfg.AnnotationConfiguration;
  7. import org.hibernate.cfg.Configuration;
  8.  
  9. public class SingSessionFactory {
  10.  
  11.     /** The single instance of hibernate SessionFactory */
  12.     private static org.hibernate.SessionFactory sessionFactory;
  13.  
  14.     /**
  15.      * Default constructor. It is private to guaranty singleton
  16.      */
  17.     private SingSessionFactory() {
  18.     }
  19.  
  20.     static {
  21.         final AnnotationConfiguration cfg = new AnnotationConfiguration();
  22.         cfg.configure("/hibernate.cfg.xml");
  23.         sessionFactory = cfg.buildSessionFactory();
  24.     }
  25.     public static SessionFactory getInstance() {
  26.         return sessionFactory;
  27.     }
  28.  
  29. }

Die Main Klasse

JAVA:
  1. // File: HibeMySQL.java
  2.  
  3. package exa;
  4.  
  5. import hibe.SingSessionFactory;
  6. import org.apache.log4j.Logger;
  7. import org.hibernate.Session;
  8. import org.hibernate.Transaction;
  9.  
  10. import obj.Tisch;
  11.  
  12. public class HibeMySQL {
  13.  
  14.     private static Logger log = Logger.getLogger(HibeMySQL.class);
  15.    
  16.     public static void main(String[] args) {
  17.         Tisch wohnzimmer = new Tisch();
  18.         wohnzimmer.setMaterial("Eiche");
  19.         wohnzimmer.setFuesse(3);
  20.        
  21.         Session ses = SingSessionFactory.getInstance().getCurrentSession();
  22.         Transaction tx = ses.beginTransaction();
  23.        
  24.         ses.save(wohnzimmer);
  25.        
  26.         tx.commit();
  27.     }
  28. }

Die angepasste Konfiguration von Hibernate

XML:
  1. <!-- File: hibernate.cfg.xml -->
  2.  
  3. <?xml version='1.0' encoding='UTF-8'?>
  4. <!DOCTYPE hibernate-configuration PUBLIC
  5.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  6.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  7.          
  8. <hibernate-configuration>
  9.  
  10.   <session-factory>
  11.     <!--  MySQL connection -->
  12.       <property name="connection.url">jdbc:mysql://localhost:3306/bank</property>
  13.       <property name="connection.username">root</property>
  14.       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  15.       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  16.       <property name="connection.password"></property>
  17.  
  18.     <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
  19.     <property name="current_session_context_class">thread</property>
  20.     <property name="transaction.auto_close_session">true</property>
  21.    
  22.     <!-- this will show us all sql statements -->
  23.     <property name="show_sql">true</property>
  24.     <!-- this will create the database tables for us -->
  25.     <property name="hbm2ddl.auto">update</property>
  26.     <mapping class="obj.Tisch" />
  27.   </session-factory>
  28.  
  29. </hibernate-configuration>

Zur Vollständigkeit noch die Konfigurationsdatei von Log4J.

XML:
  1. # File: log4j.properties
  2.  
  3. ### direct log messages to stdout ###
  4. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  5. log4j.appender.stdout.Target=System.out
  6. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  7. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  8.  
  9. ### direct messages to file hibernate.log ###
  10. #log4j.appender.file=org.apache.log4j.FileAppender
  11. #log4j.appender.file.File=hibernate.log
  12. #log4j.appender.file.layout=org.apache.log4j.PatternLayout
  13. #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
  14.  
  15. ### set log levels - for more verbose logging change 'info' to 'debug' ###
  16.  
  17. log4j.rootLogger=debug, stdout
  18.  
  19. log4j.logger.org.hibernate=info
  20. #log4j.logger.org.hibernate=debug
  21.  
  22. ### log HQL query parser activity
  23. #log4j.logger.org.hibernate.hql.ast.AST=debug
  24.  
  25. ### log just the SQL
  26. log4j.logger.org.hibernate.SQL=debug
  27.  
  28. ### log JDBC bind parameters ###
  29. log4j.logger.org.hibernate.type=info
  30. #log4j.logger.org.hibernate.type=debug
  31.  
  32. ### log schema export/update ###
  33. log4j.logger.org.hibernate.tool.hbm2ddl=info
  34.  
  35. ### log HQL parse trees
  36. #log4j.logger.org.hibernate.hql=debug
  37.  
  38. ### log cache activity ###
  39. log4j.logger.org.hibernate.cache=info
  40.  
  41. ### log transaction activity
  42. #log4j.logger.org.hibernate.transaction=debug
  43.  
  44. ### log JDBC resource acquisition
  45. #log4j.logger.org.hibernate.jdbc=debug
  46.  
  47. ### enable the following line if you want to track down connection ###
  48. ### leakages when using DriverManagerConnectionProvider ###
  49. #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

Tags: , , , , , , , , ,
eBook: Java Tutorial: Hibernate, MySQL, Annotations eBook: Java Tutorial: Hibernate, MySQL, Annotations




One Comment to

“Java Tutorial: Hibernate, MySQL, Annotations”

  1. On December 26th, 2010 at 01:00 Maria Stützel Says:

    Wir haben es mal ausprobiert: novolinespielautomat ist ein gut funktionierender Trick zum Schlagen von Spielautomaten

Email will not be published

Website example

Your Comment: