Hibernate Mapping Exception, working with annotations - java

I'm trying to work with Hibernate and MySQL. I created some test instances and tried to save them, but ran into an
hibernate.MappingException: Unknown entity: ....Category.
The Category class looks as follows:
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "categories_table")
public class Category {
#Id
#Column
private String code;
#Column
private String name;
#OneToMany(mappedBy = "category")
private Set<Addon> addons;
the hibernate.cfg.xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/xa04?createDatabaseIfNotExist=true</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>

You need to update your config with appropriate mapping(s) containing fully-qualified class names or wildacrds:
<hibernate-configuration>
<session-factory>
...
<mapping class="com.mypackage.Category" />
</session-factory>
</hibernate-configuration>

Related

Warning shown when creating hibernate.cfg.xml in Eclipse

Here is my code in file named hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.url">jdbc:mysql://localhost:3306/HeartJar</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/heartjar/bean/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
There was a waining saying Stream not availableat line 2
Although warnings don't have bad influences to my project.But Understanding how to solve the problem is useful for me,a beginner in JavaWeb.Thank you for your answer

ERROR: No suitable driver found for jdbc:mysql://localhost:3306/test

I am getting no suitable driver exception. Connection is not created.
package org.srtmun.student.dao.impl;
import javax.transaction.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.srtmun.student.dao.RegestrationDAO;
import org.srtmun.student.hibernateplugin.HibernatePlug;
import org.srtmun.student.model.Registration;
public class RegistrationDaoImpl implements RegestrationDAO{
public void addStudent(Registration register) {
System.out.println("RegistrationDaoImpl class1");
SessionFactory factory = HibernatePlug.getFactory();
System.out.println("1");
Session session=factory.openSession();
org.hibernate.Transaction tx=session.beginTransaction();
session.save(register);
tx.commit();
session.close();
}
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Registration.hbm.xml" />
</session-factory>
</hibernate-configuration>
This is my code and and iam facing the Same issue.
You need to add this property to the hibernate.cfg.xml
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
And you need to have mysql-connector-java jar at the class path.
Your transaction code is not correct (you don't use rollback, for an example). Refer this for how to properly work with that.

Automatic Table creation - Hibernate

I am trying to recreate my Oracle database in SQLite using Hibernate. I have used the hbm2ddl tag value as "create". Still my SQLite DB is not getting created. Could someone please help me with this ? I have posted below my cfg.xml file
<!-- language: xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class"> org.sqlite.JDBC </property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.username"></property>
<property name="hibernate.dialect"> org.hibernate.dialect.SQLiteDialect </property>
<property name="connection.url">jdbc:sqlite:resources/newdb.db</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.order_updates">true</property>
<property name="hibernate.order_inserts">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
Try to replace this:
<property name="connection.url">jdbc:sqlite:resources/newdb.db</property>
with:
<property name="hibernate.connection.url">jdbc:sqlite:resources/newdb.db</property>
You're missing to write hibernate in the property.
And add this line:
<property name="current_session_context_class">thread</property>
In case you have entity write them like this:
<mapping class="path.to.your.Entity"/>
I think this is what you need,
First the persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence-unit name="foo-persist" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.this.is.entity.foo</class>
<class>com.this.is.entity.foo</class>
<class>com.this.is.entity.foo</class>
<jta-data-source>foo-persist</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
</properties>
</persistence-unit>
Second is the following class which contains the properties needed by the persistence-unit:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class CommonService {
EntityManager em;
public static final String PERSISTENT_UNIT = "foo-persist";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(Config.PERSISTENT_UNIT);
Map properties = new HashMap();
public Map getProperties() {
return properties;
}
public EntityManager getEntityManager() {
properties.put("javax.persistence.jdbc.url", "");
properties.put("javax.persistence.jdbc.user", "");
properties.put("javax.persistence.jdbc.password", "");
properties.put("javax.persistence.jdbc.driver", "org.sqlite.JDBC");
properties.put("eclipselink.logging.level", "OFF");
properties.put("javax.persistence.schema-generation.database.action", "create");
properties.put("javax.persistence.schema-generation.create-script-source", "META-INF/script.sql");
properties.put("javax.persistence.sql-load-script-source", "META-INF/script.sql");
emf = Persistence.createEntityManagerFactory(Config.PERSISTENT_UNIT, properties);
return em = (EntityManager) emf.createEntityManager();
}
}

Invalid Mapping with Hibernate

I've i run into an exeption while trying to use Hibernate 4.3.x with java on netbeans, the exption is:
Exception in thread "main" java.lang.ExceptionInInitializerError
at teste.ConectaJavaDB.main(ConectaJavaDB.java:17)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource model/Equipe.hbm.xml
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3764)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXmlQueue(Configuration.java:3753)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3741)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at conexao.HibernateUtil.buildSessionFactory(HibernateUtil.java:25)
at conexao.HibernateUtil.<clinit>(HibernateUtil.java:14)
... 1 more
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping model.Equipe
at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2837)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:178)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3761)
... 7 more
(the second error says about duplicate mapping, but i dindt mapped twice)
by reading the exeption, it's possible to see that the problem is in the mapping xml of the class Equipe, the XML contains:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="model">
<class name="model.Equipe" table="equipe">
<id name="id" type="int" column="ID" >
<generator class="increment"/>
</id>
<property name="nome"/>
<property name="dataNascimento"/>
<property name="email"/>
<property name="enderecoWeb"/>
<property name="fone"/>
</class>
</hibernate-mapping>
And the class:
package model;
import java.util.Date;
public class Equipe {
private int id;
private String nome;
private Date dataNascimento;
private String email;
private String enderecoWeb;
private String fone;
[..]getters and setters[..]
Hibernate.cgf
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<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://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">app</property>
<property name="hibernate.connection.password">app</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="model.Jogador"/>
<mapping resource="model/Equipe.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I can't seem to find the error, the hole code is posted on Bitbucket above, thanks!
Hole code: https://bitbucket.org/angelorodem/progapl_ii_272278_2015/src
You invoked configuration.configure() twice. Remove the second invocation, or just copy paste the code below:
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="model.Jogador"/> (remove this)
<mapping resource="model/Equipe.hbm.xml"/>
try this:
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="model/Equipe.hbm.xml"/>

Use Two hibernate.cfg.xml files in a Application

how to specify two hibernate configurations for a one application,
i have created two hibernate files and mention them in SessionFactory.util
hibernateMaster.cfg.xml file is working fine..
but when shut down Master database server and try to use application with hibernateMaster.cfg.xml and retrieve data it gives me "null"
but if i restart the Application it is working fine with hibernateMaster.cfg.xml file
here are my hibernate files
hibernateMaster.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.232.143:3306/cps</property>
<property name="hibernate.connection.username">gaiz</property>
<property name="hibernate.connection.password">mysql</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="lib/driver/mappings/Patient.hbm.xml"/>
<mapping resource="lib/driver/mappings/Allergy.hbm.xml"/>
<mapping resource="lib/driver/mappings/Hospital.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatStaff.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatWard.hbm.xml"/>
<mapping resource="lib/driver/mappings/User.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserRole.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserLog.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernateSlave.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.232.144:3306/cps</property>
<property name="hibernate.connection.username">gaiz2</property>
<property name="hibernate.connection.password">mysql</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="lib/driver/mappings/Patient.hbm.xml"/>
<mapping resource="lib/driver/mappings/Allergy.hbm.xml"/>
<mapping resource="lib/driver/mappings/Hospital.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatStaff.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatWard.hbm.xml"/>
<mapping resource="lib/driver/mappings/User.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserRole.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserLog.hbm.xml"/>
</session-factory>
</hibernate-configuration>
SessionFactoryUtil.java
package lib;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import core.resources.statisticalResource;
public class SessionFactoryUtil {
//This class creates a session factory object by looking at the hibernate configuration (hibernate.cfg.xml)
private static SessionFactory sesFactory;
private static ServiceRegistry sesRegistry;
static Configuration cfg;
static{
try{
cfg= new Configuration().configure("lib/hibernateMaster.cfg.xml");
sesRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sesFactory=cfg.buildSessionFactory(sesRegistry);
try{
Session session = SessionFactoryUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
System.out.println("Connected to Master Database Server");
}
catch(Throwable ex){
cfg= new Configuration().configure("lib/hibernateSlave.cfg.xml");
sesRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sesFactory=cfg.buildSessionFactory(sesRegistry);
System.out.println("Connected to Slave Database Server");
}
}
catch(Throwable ex){
System.out.println("Master & Slave Database Error.");
System.err.println("Initial SessionFactory Creation Failed"+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sesFactory;
}
}
i dnt knw whether i have done something wrong on have done something wrong in SessionFactoryUtil.java .
Your problem is that you initialize your factory in a static way.
static{
...
}
That code is executed only once, when you start your application. That way when you shut down your master server hibernate stills asking for it.
You should initialize both configurations and use the main, if exists, or secondary in other case. You can do this in the getSessionFactory() method, that is executed each time the method is call, but not in an static initializer.

Categories

Resources