Hibernate.cfg.xml nicht ins src - Verzeichnis?

ich habe mir eine ganz kleine Anwendung mit Hibernate erstellt

package de.kunitz.dao;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.HibernateTemplate;

import de.kunitz.dto.User;

public class Test {
    private HibernateTemplate template = null;
    
	public static void main(String[] args) {
		   //creating configuration  
		   Configuration cfg=new Configuration();    
		   cfg.configure("hibernate.cfg.xml"); 
		
		   //creating seession factory object    
		   SessionFactory factory=cfg.buildSessionFactory();   
		   
		   //creating session object    
		   Session session=factory.openSession(); 
		   
		   //creating transaction object    
		   Transaction t=session.beginTransaction();
		   
		   User user = new User(null, new Date(), true, false, "ABCDEFGHIJKL", "Sascha", "Kunitz", "test@test.de", "pH5qF");

		   session.persist(user);
		    
		   t.commit();
		   session.close();    
		   
		   System.out.println("User saved");
	}

}

im src - Verzichnis befindet sich die hibernate.cfg.xml.

Beim Ausführen wird mir aber gemeldet

260 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
269 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.10.Final
274 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
278 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
283 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
360 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: hibernate.cfg.xml
360 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: hibernate.cfg.xml
Exception in thread “main” org.hibernate.HibernateException: hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2176)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2157)
at de.kunitz.dao.Test.main(Test.java:19)

gehört das hibernate.cfg.xml nicht ins root - Verzeichnis?

Falls du mit Eclipse arbeitest: So weit ich weiß, muss die hibernate.cfg.xml ins src-Verzeichnis deines Projektes.
Dann wäre das richtig.

Vielleicht ein Tippfehler?

*** Edit ***

Noch mal richtig hingeguckt. Ja! Du hast einen Tippfehler drin.
Richtig muss es in Zeile 20 heißen:
cfg.configure("/hibernate.cfg.xml");

Danke erstmal L-ectron-X. Ich habe es mal ausgetestet und auch Projekt neu aufgesetzt unter Eclipse Kepler. Es scheint auch ohne “/” zu funktionieren. Allerdings habe ich jetzt ein anderes Problem.

Ich habe folgende MySQL Tabelle
[sql]
– phpMyAdmin SQL Dump
– version 3.5.2.2
http://www.phpmyadmin.net

– Host: 127.0.0.1
– Erstellungszeit: 30. Apr 2014 um 01:26
– Server Version: 5.5.27
– PHP-Version: 5.4.7

SET SQL_MODE=“NO_AUTO_VALUE_ON_ZERO”;
SET time_zone = “+00:00”;

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT /;
/
!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS /;
/
!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION /;
/
!40101 SET NAMES utf8 */;


– Datenbank: test



– Tabellenstruktur für Tabelle user

CREATE TABLE IF NOT EXISTS user (
id int(11) NOT NULL AUTO_INCREMENT,
created_by int(11) DEFAULT NULL,
created_at timestamp NULL DEFAULT NULL,
blocked tinyint(1) NOT NULL,
deleted tinyint(1) NOT NULL,
activcode varchar(255) NOT NULL,
firstname varchar(255) NOT NULL,
lastname varchar(255) NOT NULL,
email varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY activcode (activcode),
UNIQUE KEY idx_login (email,password),
UNIQUE KEY email (email),
KEY blocked (blocked),
KEY deleted (deleted)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT /;
/
!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS /;
/
!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
[/sql]

die Klasse User.java sieht wie folgt aus

package de.kunitz.dto;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.annotations.*;

@Entity
@Table(
    appliesTo = "user",
    indexes = { @Index(name="idx_login", columnNames = { "email", "password" } ) } )    
public class User implements Serializable {
       private static final long serialVersionUID = 1L;

       private long 	id;

 	   private User 	created_by;
	   private Date		created_at = new Date();

 	   private boolean  blocked = false;
	   private boolean  deleted = false;
	   private String	activcode;  

	   private String 	firstname;
	   private String   lastname;		   
	   private String 	email;
	   private String 	password;	
	   
	   public User(User created_by, Date created_at, boolean blocked,
			boolean deleted, String activcode, String firstname,
			String lastname, String email, String password) {
		    super();
		
		    this.created_by 	= created_by;
		    this.created_at 	= created_at;
		    this.blocked 		= blocked;
		    this.deleted 		= deleted;
		    this.activcode 		= activcode;
		    this.firstname 		= firstname;
		    this.lastname 		= lastname;
		    this.email 			= email;
		    this.password 		= password;
	   }

	   @Id	   
	   @Column(name="id", unique = true, nullable = false)
	   @GeneratedValue(strategy = GenerationType.AUTO)
	   public long getId() {
	   	      return id;
	   }

	   public void setId(int id) {
	          this.id = id;
	   }

	   @Column(name="created_by")
	   public User getCreatedBy() {
	   	      return created_by;
	   }	

	   public void setCreatedBy(User user) {
	   	      created_by = user;
	   }	

	   @Column(name="created_at")
	   public Date getCreatedAt() {
	   	      return created_at;
	   }	

	   public void setCreatedAt(Date date) {
	   	      created_at = date;
	   }	

	   @Column(name="blocked", nullable = false)
	   @Index(name = "idx_blocked")
	   public boolean isBlocked() {
	   	      return blocked;
	   }	

	   public void setBlocked(boolean blocked) {
	   	      this.blocked = blocked;
	   }	

	   @Column(name="deleted", nullable = false)
	   @Index(name = "idx_deleted")
	   public boolean isDeleted() {
	   	      return deleted;
	   }	

	   public void setDeleted(boolean deleted) {
	   	      this.deleted = deleted;
	   }	

	   @Column(name="activcode", unique = true, nullable = false)
	   @Index(name = "idx_activcode")
	   public String getActivcode() {
	   	      return activcode;
	   }	

	   public void setActivcode(String code) {
	   	      this.activcode = code;
	   }	

	   @Column(name="firstname", nullable = false)
	   public String getFirstname() {
	          return firstname;
	   }
	 
	   public void setFirstname(String name) {
	          this.firstname = name;
	   }

	   @Column(name="lastname")
	   public String getLastname() {
	          return lastname;
	   }
	 
	   public void setLastname(String name) {
	          this.lastname = name;
	   }

	   @Column(name="email", unique = true, nullable = false)
	   @Index(name = "idx_email")	   
	   public String getEmail() {
	          return email;
	   }
	 
	   public void setEmail(String address) {
	          this.email = address;
	   }

	   @Column(name="password", nullable = false)
	   public String getPassword() {
	          return password;
	   }
	 
	   public void setPassword(String password) {
	          this.password = password;
	   }

	@Override
	public String toString() {
		return "User [id=" + id + ", created_by=" + created_by
				+ ", created_at=" + created_at + ", blocked=" + blocked
				+ ", deleted=" + deleted + ", activcode=" + activcode
				+ ", firstname=" + firstname + ", lastname=" + lastname
				+ ", email=" + email + ", password=" + password + "]";
	}
	   
	   
}

die zugehörige hibernate.cfg.xml
[xml]

<?xml version="1.0" encoding="UTF-8"?> org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull root [/xml]

meine Hauptklasse

package de.kunitz.dao;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.HibernateTemplate;

import de.kunitz.dto.User;

public class Test {
    private HibernateTemplate template = null;
    
	public static void main(String[] args) {
		   //creating configuration  
		   Configuration cfg=new Configuration();    
		   cfg.configure("hibernate.cfg.xml"); 
		
		   //creating seession factory object    
		   SessionFactory factory=cfg.buildSessionFactory();   
		   
		   //creating session object    
		   Session session=factory.openSession(); 
		   
		   //creating transaction object    
		   Transaction t=session.beginTransaction();
		   
		   User user = new User(null, new Date(), true, false, "ABCDEFGHIJKL", "Sascha", "Kunitz", "test@test.de", "pH5qF");
		   System.out.println( user.toString() );
		   
		   session.persist(user);
		   // System.out.println("User saved");
		   
		   t.commit();
		   session.close();    
		   
		   System.out.println("User saved");
	}

}

Beim ausführen erhalte ich die Fehlermeldung


179 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
196 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.10.Final
198 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
205 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
209 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
301 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: hibernate.cfg.xml
301 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: hibernate.cfg.xml
374 [main] WARN org.hibernate.util.DTDEntityResolver - recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
400 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
453 [main] INFO org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
459 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
464 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
464 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
464 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
472 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull
472 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root}
793 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
813 [main] INFO org.hibernate.cfg.SettingsFactory - Database ->
       name : MySQL
    version : 5.5.27
      major : 5
      minor : 5
813 [main] INFO org.hibernate.cfg.SettingsFactory - Driver ->
       name : MySQL-AB JDBC Driver
    version : mysql-connector-java-5.1.23 ( Revision: ${bzr.revision-id} )
      major : 5
      minor : 1
815 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
816 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
816 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
816 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
816 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
816 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
817 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
817 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
817 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
817 [main] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
817 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
817 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
817 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
817 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
818 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
820 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
820 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
820 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
820 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
820 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
820 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
821 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
822 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
826 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
826 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
826 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
826 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
826 [main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
861 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_materialized_blob] overrides previous : org.hibernate.type.WrappedMaterializedBlobType@130f889
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType@188e820
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [clob] overrides previous : org.hibernate.type.ClobType@1490758
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Clob] overrides previous : org.hibernate.type.ClobType@1490758
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_characters_clob] overrides previous : org.hibernate.type.CharacterArrayClobType@1df177
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [materialized_clob] overrides previous : org.hibernate.type.MaterializedClobType@6fa74d
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [blob] overrides previous : org.hibernate.type.BlobType@f08448
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Blob] overrides previous : org.hibernate.type.BlobType@f08448
868 [main] INFO org.hibernate.type.BasicTypeRegistry - Type registration [characters_clob] overrides previous : org.hibernate.type.PrimitiveCharacterArrayClobType@16438c9
998 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
Exception in thread "main" org.hibernate.MappingException: Unknown entity: de.kunitz.dto.User
	at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
	at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1494)
	at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:202)
	at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:531)
	at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:112)
	at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:71)
	at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
	at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
	at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
	at de.kunitz.dao.Test.main(Test.java:33)
User [id=0, created_by=null, created_at=Wed Apr 30 01:24:36 CEST 2014, blocked=true, deleted=false, activcode=ABCDEFGHIJKL, firstname=Sascha, lastname=Kunitz, email=test@test.de, password=pH5qF]

Datenbank läuft. Die Datenbank “test” ist unter User = “root” / PWD = “” erreichbar. Die Tabelle “user” existiert. Es befinden sich keine Daten in der Tabelle.
Daten werden aber nicht geschrieben. Keine Ahnung was


Exception in thread "main" org.hibernate.MappingException: Unknown entity: de.kunitz.dto.User

mir sagen will, zumal die gesetzten Daten am Ende korrekt ausgegeben werden und die Zeile


at de.kunitz.dao.Test.main(Test.java:33)

die Zeile

session.persist(user);

betrifft.

Verwende die Entity-Annotation aus dem Package “javax.persistence.Entity”.

http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html#entity-hibspec-entity

@javax.persistence.Entity is still mandatory, @org.hibernate.annotations.Entity is not a replacement.

Diese Warnung ließe sich auch leicht vermeiden:

 [main] WARN org.hibernate.util.DTDEntityResolver - recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 

ja