Maven 2 Exemple Hibernate 3.2 MySQL (annotation)

Maven 2 + Hibernate 3.2 + Exemple MySQL (annotation)

Note
Cet article est obsolète et certaines informations ne sont plus valides dans le dernier développement d'Hibernate. Vous devriez vous référer à ce dernier tutoriel -Maven 3 + Hibernate 3.6.3 + Oracle 11g Example (Annotation).

Ce didacticiel modifiera lesMaven 2 + Hibernate 3.2 + MySQL Example (XML mapping)précédents et remplacera le fichier de mappage XML Hibernate par le code d'annotation.

Outils et technologies utilisés dans cet article:

  1. Maven 2.2.1

  2. JDK 1.6.0_13

  3. Hibernate 3.2.3.GA

  4. MySQL 5.0

1. Créer une infrastructure de projet

Créer une infrastructure de projet enMaven + Hibernate (XML mapping file) + MySQL Example

2. Ajouter un référentiel JBoss

Le référentiel JBoss danspom.xml est requis pour télécharger la bibliothèque d'annotations Hibernate.

 
    
      JBoss repository
      http://repository.jboss.com/maven2/
    
  

3. Ajouter une dépendance d'annotation Hibernate

Ajoutez les dépendances hibernate-annotations et hibernate-commons-annotations danspom.xml.

    
        hibernate-annotations
        hibernate-annotations
        3.3.0.GA
    

    
        hibernate-commons-annotations
        hibernate-commons-annotations
        3.0.0.GA
    

Fichier: pom.xml


  4.0.0
  com.example.common
  HibernateExample
  jar
  1.0-SNAPSHOT
  HibernateExample
  http://maven.apache.org

  
    
      JBoss repository
      http://repository.jboss.com/maven2/
    
  

  

    
    
        mysql
        mysql-connector-java
        5.1.9
    

    
    
        hibernate
        hibernate3
        3.2.3.GA
    

    
    
        hibernate-annotations
        hibernate-annotations
        3.3.0.GA
    

    
        hibernate-commons-annotations
        hibernate-commons-annotations
        3.0.0.GA
    

    
    
        dom4j
        dom4j
        1.6.1
    

    
        commons-logging
        commons-logging
        1.1.1
    

    
        commons-collections
        commons-collections
        3.2.1
    

    
        cglib
        cglib
        2.2
    
    

    
        javax.transaction
        jta
        1.1
    

  

4. Mettre à jour le chemin d'accès aux classes du projet

Exécutez «mvn eclipse:eclipse» dans l'invite de commande pour télécharger la bibliothèque de dépendances et mettre à jour le chemin de classe du projet Eclipse.

5. Mettre à jour HibernateUtil.java

Mettez à jour «HibernateUtil» pour utiliser «AnnotationConfiguration» au lieu de «Configuration» pour créer la fabrique de session Hibernate.

Utilise auparavant «Configuration» - Pour le fichier de mappage XML Hibernate

return new Configuration().configure().buildSessionFactory();

Remplacez-le par «AnnotationConfiguration» - Pour la prise en charge des annotations d'hibernation

return new AnnotationConfiguration().configure().buildSessionFactory();

Fichier: HibernateUtil.java

package com.example.persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();

        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}

6. Mettre à jour la classe de modèle

Mettez à jour «Stock.java» pour utiliser l'annotation comme suit:

Stock.java
package com.example.common;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock", catalog = "example", uniqueConstraints = {
        @UniqueConstraint(columnNames = "STOCK_NAME"),
        @UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {

    private Integer stockId;
    private String stockCode;
    private String stockName;

    public Stock() {
    }

    public Stock(String stockCode, String stockName) {
        this.stockCode = stockCode;
        this.stockName = stockName;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "STOCK_ID", unique = true, nullable = false)
    public Integer getStockId() {
        return this.stockId;
    }

    public void setStockId(Integer stockId) {
        this.stockId = stockId;
    }

    @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
    public String getStockCode() {
        return this.stockCode;
    }

    public void setStockCode(String stockCode) {
        this.stockCode = stockCode;
    }

    @Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
    public String getStockName() {
        return this.stockName;
    }

    public void setStockName(String stockName) {
        this.stockName = stockName;
    }

}

7. Supprimer le fichier de mappage XML Hibernate existant

Supprimez le fichier de mappage XML Hibernate existant - «Stock.hbm.xml», ce n'est plus nécessaire.

8. Mettre à jour le fichier de configuration Hibernate

Mettez à jour le fichier de configuration Hibernate - hibernate.cfg.xml.

Auparavant, il avait le fichier de mappage XML Hibernate avec la balise «ressource de mappage»

Changez-le en classe de modèle avec la balise «mapping class»

Fichier: hibernate.cfg.xml



    
        false
        com.mysql.jdbc.Driver
        password
        jdbc:mysql://localhost:3306/example
        root
        org.hibernate.dialect.MySQLDialect
        true
        
    

9. Revoir la structure du projet

Il semble que peu de fichiers aient été modifiés, vérifiez-le et assurez-vous que la structure des dossiers est la suivante:

maven_hibernate_annotation_mysql

10. Exécutez-le et voyez la sortie

Exécutez votre App.java, il insérera un nouvel enregistrement dans la table "Stock". Le résultat doit être identique à l'exemple de fichier de mappage XML Hibernate précédent.

Maven + Hibernate + MySQL
...
Hibernate: insert into example.stock (STOCK_CODE, STOCK_NAME) values (?, ?)

Terminé.