Error "Mapping (RESOURCE) not found : HibernateExposed/Person.hbm.xml" - java

I'm new in Hibernate and I'm trying to create a little aplication in Java using Maven in IntelliJ Idea.
I'm having this error in title above, and answers of the same problem here on Stack did not helped me until now.
What is this file "Person.hbm.xml". I have to create it?
Once it is a mapping resource, Hibernate should not create it itself?
I'm getting this error when I run my little program:
Exception in thread "main" org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : HibernateExposed/Person.hbm.xml : origin(HibernateExposed/Person.hbm.xml)
at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:56)
at org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
at org.hibernate.boot.cfgxml.spi.MappingReference.apply(MappingReference.java:70)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:412)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:86)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at Persistencia.HibernateUtils.<init>(HibernateUtils.java:10)
at Main.Main.main(Main.java:16)
This is my class of database configuration: HibernateUtils:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
//Fábrica de sessões de banco de dados constante no padrão SINGLETON
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
And bellow, my entity class that I'm trying to persist:
import javax.persistence.Entity;
import java.sql.Date;
#Entity
public class Produto {
private String nome;
private int cod;
private float valor;
private Date dataValidade;
protected Produto() {
}
public Produto(String nome, int cod, float valor, Date dataValidade) {
this.nome = nome;
this.cod = cod;
this.valor = valor;
this.dataValidade = dataValidade;
}
/*public Produto getProdutoPorNome(String nome) {
Produto buscaResult = //Resultado da busca.
}
*/
public boolean excluirProduto(int cod) {
boolean deuCerto=false;
return deuCerto;
}
}
And my Main class:
package Main;
import Persistencia.HibernateUtils;
import ProcessoDeVenda.Produto;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Session sessao;
HibernateUtils hiber = new HibernateUtils();
SessionFactory session = hiber.getSessionFactory();
Produto produto;
try {
sessao = session.openSession();
Date data = new Date(05, 12, 2018);
float valor = (float) 42000.0;
produto = new Produto("Carro", 1, valor, (java.sql.Date) data);
System.out.println(produto.toString());
}catch (Exception sqlException) {
System.out.println(sqlException);
}
}
}
The project structure, with the location of hibernate.cfg.xml file.
And my hibernate.cfg.xml file content:
Look at the "mapping resource" tag.
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:~/PDV</property>
<property name="connection.username">Lucas</property>
<property name="connection.password">mypass</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="HibernateExposed/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
Now, i'm trying to map classes direct on hibernate.cfg.xml. (Why hibernate does not make this itself? I'm using anotations...)
I've deleted
<mapping resource="HibernateExposed/Person.hbm.xml" />
ANd in i'ts place I've mapped the class:
<mapping class="src.main.java.ProcessoDeVenda.Produto" />
And the error just changed to this:
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:417)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:86)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at Persistencia.HibernateUtils.<init>(HibernateUtils.java:10)
at Main.Main.main(Main.java:16)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:105)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.addConnections(DriverManagerConnectionProviderImpl.java:363)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:282)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:260)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections$Builder.build(DriverManagerConnectionProviderImpl.java:401)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:112)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:75)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
... 15 more
Caused by: org.h2.jdbc.JdbcSQLException: Database may be already in use: null. Possible solutions: close all other connection(s); use the server mode [90020-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:168)
at org.h2.mvstore.db.MVTableEngine$Store.convertIllegalStateException(MVTableEngine.java:188)
at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:168)
at org.h2.mvstore.db.MVTableEngine.init(MVTableEngine.java:100)
at org.h2.engine.Database.getPageStore(Database.java:2538)
at org.h2.engine.Database.open(Database.java:709)
at org.h2.engine.Database.openDatabase(Database.java:286)
at org.h2.engine.Database.<init>(Database.java:280)
at org.h2.engine.Engine.openSession(Engine.java:66)
at org.h2.engine.Engine.openSession(Engine.java:179)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:157)
at org.h2.engine.Engine.createSession(Engine.java:140)
at org.h2.engine.Engine.createSession(Engine.java:28)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:351)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:124)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:103)
at org.h2.Driver.connect(Driver.java:69)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 30 more
Caused by: java.lang.IllegalStateException: The file is locked: nio:C:/Users/Lucas_Pletsch/PDV.mv.db [1.4.197/7]
at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:870)
at org.h2.mvstore.FileStore.open(FileStore.java:173)
at org.h2.mvstore.MVStore.<init>(MVStore.java:350)
at org.h2.mvstore.MVStore$Builder.open(MVStore.java:2934)
at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:155)
... 45 more
This is my H2 database console, showing the configurations that I have passed to hibernate.cfg.xml, like JDBC URL, driver class...
I have imported H2 in POM.xml file of my project:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

You can either define entity mapping via annotations (I prefer this) or in an XML file. Based on the error it is looking for xml file Person.hbm.xml in folder HibernateExposed (see it from your config file <mapping resource="HibernateExposed/Person.hbm.xml" />). So you need to create Person.hbm.xml file with name of entity and all attributes. E.g.
<entity-mappings>
<entity class="your_package_name.Produto" name="Produto">
<attributes>
<property name="nome"
type="value"
not-null="value"
update="value"/>
//put all other attributes from Produto class
</attributes>
</entity>
</entity-mappings>
But in this case you do not need to use #Entity annotation. If you want to use annotations then change hibernate.cfg.xml to something like <mapping class="your_package_name.Produto"/>

I solved the problems configuring hibernate using hibernate.properties file, instead of hibernate.cfg.xml.
I used H2 in memory, using the jdbc URL (one of the defaults in H2): jdbc:h2:mem:test, configured at hibernate.properties. (More in this link: http://www.h2database.com/html/features.html#database_url)
I've follow all the steps of this tutorial for the solution: https://www.youtube.com/watch?v=MA4tM17H6_M

Related

I am using hibernate, no pom.xml or maven and getting the error?

This is my main class
package com.luv2code.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CreateStudentDemo {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create stydent object
System.out.println("Creating a new student object");
Student tempStudent = new Student("Paul", "Wall", "paulWall#gmail.com");
// start a transaction
session.beginTransaction();
// save student object
System.out.println("Saving student ");
session.save(tempStudent);
// commit the transaction
session.getTransaction().commit();
System.out.println("Done ...");
}
catch (Exception e) {
System.out.println("ERROOOOORRR");
}finally {
((SessionFactory) factory).close();
}
}
}
This is my hibernate configuration file
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password">hbstudent</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
this is the error I get
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at org.hibernate.boot.spi.XmlMappingBinderAccess.(XmlMappingBinderAccess.java:43)
at org.hibernate.boot.MetadataSources.(MetadataSources.java:87)
at org.hibernate.cfg.Configuration.(Configuration.java:123)
at org.hibernate.cfg.Configuration.(Configuration.java:118)
at com.luv2code.hibernate.demo.CreateStudentDemo.main(CreateStudentDemo.java:13)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
... 5 more
Java removed java.xml.bind from JAVA 9 and higher editions.
Here is the solution for same kind of issues:
Intellij: https://stackoverflow.com/a/73766451/18263761
Eclipse : https://stackoverflow.com/a/73766498/18263761

Unable to create table entry in php mysql db using below code in hibernate(using Ampps)

Issue - I am using mac OS Mojave, I have created one program which will create a table in the db named HibernateTutorials, I have installed Ampps and started it on 3306 port to create db. Now whenever i try to create table I am getting below error.
Error -
Mar 15, 2019 1:10:34 AM org.hibernate.Version logVersion
WARN: HHH000342: Could not obtain connection to query metadata : Unable to resolve name [org.hibernate.dialect.MySQDialect] as strategy [org.hibernate.dialect.Dialect]
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:84)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:474)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.gontuseries.hibernate.Main.main(Main.java:23)
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySQDialect] as strategy [org.hibernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:133)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:212)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:160)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:147)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:141)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:74)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:51)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 14 more
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.MySQDialect]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:136)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:129)
... 24 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.MySQDialect
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:133)
... 25 more
Please find the below classes I have created -
Main class -
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.fasterxml.classmate.AnnotationConfiguration;
public class Main {
public static void main(String[] args) {
Student_Info stu = new Student_Info();
stu.setName("Aniket");
stu.setRoll_no(1);
Configuration con = new Configuration().configure().addAnnotatedClass(Student_Info.class);
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(stu);
session.getTransaction().commit();
session.close();
sf.close();
}
}
Student_Info -
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="STUDENT_INFORMATION")
public class Student_Info {
#Id
private int roll_no;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
hibernate.cfg.xml -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/HibernateTutorials</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool(use the built in) -->
<property name="connection.pool_size">1</property>
<!-- sql dialect -->
<property name="dialect">org.hibernate.dialect.MySQDialect</property>
<!-- Disable the second level cache -->
<property name="cache.provider_clas">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed sql to stdout -->
<property name="show_sql">true</property>
<!-- Drop the existing tables and create new one -->
<property name="hbm2ddl.auto">create</property>
<!-- Mention here all the model classes along with their package name -->
<mapping class="com.gontuseries.hibernate.Student_Info" />
</session-factory>
</hibernate-configuration>
Note - please suggest if the problem is in configuration or in code as the code I think is good;
You have typing error in dialect configuration
org.hibernate.dialect.MySQDialect

Hibernate - persist automatically each relation

Maybe it is a simple question, but I can't find out this situation of relations in Hibernate.
I have these Entities:
#Entity
public class User {
...
#OneToMany(mappedBy = "user")
private Set<Conversation> posts = new HashSet<Conversation>();
...
}
#Entity
public class Conversation {
...
#OneToMany(mappedBy = "conversation")
private Set<Message> messages = new HashSet<Message>();
...
}
#Entity
public class Message { ... }
and then I want create User with Conversation and Message at once. Idea should be like this:
User user = new User();
user.getPosts().add(new Conversation(){
{
getMessages().add(new Message());
}
});
session.persist(user);
But just User is saved in database - why isn't it all? Because of default LAZY fetching? Could my idea be implemented somehow?
PS: Of course I know about the solution of persisting each of the entities, but I am used to do like this in other frameworks like nette or Django, so I can't get out of my head.
PPS: I found out that problem is in default CascadeType. Could it be set on globally, e.g. in Hibernate config XML? Is it a good idea (by performance point of view - it is persisted each time on "superpersist" or only in case of changes)?
PPPS: I also found out (opposite to Django) that I have to set FK ex-post for each item added to collection. It is natural (because of selected pure Set type), but new for me. Which approach would you recommend me? Required FK as argument in constructor on item Entity e.g.:
Class Message{
Message(Conversation conversation){
setConversation(conversation);
}
...
}
or make a method for adding where FK sets inside e.g.:
Class Conversation{
...
public void addMessage(Message msg){
msg.setConversation(this);
getMessages().add(msg);
}
...
}
?
Making Session + configure XML.
private final static String CFG = "hibernate-cfg.xml";
private final static String SCRIPT_FILE = "query.sql";
private static SessionFactory sessionFactory;
private static ServiceRegistry buildRegistry() {
return new StandardServiceRegistryBuilder()
.configure(CFG)
.build();
}
private static Metadata getMetaData() {
return new MetadataSources(buildRegistry()).getMetadataBuilder().build();
}
private static SessionFactory buildSessionFactory() {
return getMetaData().getSessionFactoryBuilder().build();
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
public static Session getSession(){
try {
return getSessionFactory().openSession();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
and the hibernate-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>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/learnme
</property>
<property name="connection.username">root</property>
<property name="connection.password"/>
<property name="connection.pool_size">100</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Display all generated SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="learnme.hibernate.entities.User"/>
<mapping class="learnme.hibernate.entities.Conversation"/>
<mapping class="learnme.hibernate.entities.Message"/>
</session-factory>
</hibernate-configuration>
According to this and this
you need to have this in your persistence.xml file to set it globally:
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<cascade-persist/>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
The mapping file has to be located either in the default location,
META-INF/orm.xml, or in another location that is specified explicitly
in the persistence unit definition (in persistence.xml).

Unable to Load Mapper Class in Hibernate

I'm very new to Hibernate. Followed by a youtube tutorial, I created a hibernate program but getting an error. Please find the Class and the error below. Solution for this will be highly grateful.
Error:
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Oct 29, 2016 4:36:53 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Oct 29, 2016 4:36:53 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in thread "main" org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [Emp.hbm.xml]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:104)
Main Function()
public static void main( String[ ] args ) throws ParseException {
Configuration cfg = new Configuration();
cfg.configure("Hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
String name2 = "yahoo";
LoginRegister lr = new LoginRegister();
lr.set_username(name2.toLowerCase()+"_user");
lr.set_password(name2.toLowerCase()+"_pass");
lr.set_last_update(new java.sql.Date(new SimpleDateFormat("yyyyMMdd").parse("20110210").getTime()));
s.save(lr);
s.flush();
tx.commit();
s.close();
}
POJO CLASS:
package dto;
import java.io.Serializable;
import java.sql.Date;
public class LoginRegister implements Serializable{
private int _id;
private String _username = null;
private String _password = null;
Date _last_update = null;
public LoginRegister(){}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_username() {
return _username;
}
public void set_username(String _username) {
this._username = _username;
}
public String get_password() {
return _password;
}
public void set_password(String _password) {
this._password = _password;
}
public Date get_last_update() {
return _last_update;
}
public void set_last_update(Date _last_update) {
this._last_update = _last_update;
}
public String toString(){
return
"Id : "+this._id+"\n"+
"Username : "+this._username+"\n"+
"Password : "+this._password+"\n"+
"Last Update : "+this._last_update;
}
}
Configuration File :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Connection -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- Driver -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Language Used (Dialect) : Here SQL -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><!-- URL -->
<property name="connection.username">root</property> <!-- Username -->
<property name="connection.password"></property> <!-- Password -->
<!-- To generate SQL Queries when running the program -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- For JDBC Transaction -->
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Auto Commit -->
<property name="hibernate.connection.autocommit">false</property>
<!-- Mapping Class -->
<mapping class ="Emp.hbm.xml" />
</session-factory>
</hibernate-configuration>
Entity Mapper File:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="qqqLoginRegister" table="qqqlogin_register">
<id name="_id" column="id" type="integer">
<generator class="assigned"/>
</id>
<property name="_userName" column="username" type="string"/>
<property name="_password" column="password" type="string"/>
<property name="_last_update" column="last_update" type="date"/>
</class>
</hibernate-mapping>
Locations :
Configuration FIle : srs\Hibernate.cfg.xml
Entity Mapper : src\Emp.hbm.xml
POJO : src\dto\LoginRegister.java
Main Class : src\dao\Index.java
As you are NOT using the Hibernate bean annoatations, in your Hibernate.cfg.xml file, you need to change <mapping class ="Emp.hbm.xml" /> to <mapping resource ="Emp.hbm.xml" />
Hibernate is an ORM framework which maps the Java Bean to a Relational database table and the mapping can be provided directly in the Java Bean Object (using Annotations) or can be provided separately through xml files (like how you did).
Hibernate SessionFactory mappings are compiled from various XML mapping files and <mapping resource is used to load those mapping files (in your case it is a single file which is Emp.hbm.xml file)
You can refer the below documentation for more details:
https://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

I am getting error for my first hibernate program, please help me to resolve the erros

Errors :
log4j:WARN No appenders could be found for logger
(org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize
the log4j system properly. Exception in thread "main"
org.hibernate.exception.GenericJDBCException: Cannot open connection
at
org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
at
org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at
org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at
org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at org.koushik.hibernate.HibernateTest.main(HibernateTest.java:20)
Caused by: org.postgresql.util.PSQLException: FATAL: database
"5432/hibernatedb" does not exist at
org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:691)
at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:207)
at
org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
at org.postgresql.jdbc.PgConnection.(PgConnection.java:159) at
org.postgresql.Driver.makeConnection(Driver.java:415) at
org.postgresql.Driver.connect(Driver.java:283) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
... 5 more
code
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration SYSTEM "hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost/5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> -->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="org.javabrains.koushik.dto.UserDetails" />
<!-- <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/> -->
</session-factory>
</hibernate-configuration>
UserDetails.java
package org.javabrains.koushik.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class UserDetails {
#Id
private int userID;
private String userName;
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
HibernateTest.java
package org.koushik.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.javabrains.koushik.dto.UserDetails;
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserID(1);
user.setUserName("First user");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
It looks like it may be an error in your connection URL. Shouldn't it be
jdbc:postgresql://localhost:5432/hibernatedb
?
Check your connection URL path it should be like this:
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
If this doesn't work then note that in PostgreSQL's case it's typical to use port 5432 if it is available. If it isn't, most installers will choose the next free port, usually 5433. So you may enter the property like this
<property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
If you still can't figure out then read this line in your stacktrace you may get the idea what #RemyG is trying to say:
org.postgresql.util.PSQLException: FATAL: database "5432/hibernatedb" does not exist at

Categories