Reputation: 7401
EDIT: My apoligies. I am getting an error it seems. It goes like this: Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate.hibernate.Message
I made a simple testprogram that tests the persist() method of hibernate and the createQuery() method.
It communicates with 1 mySQL test database that has only one table called Message. This table has 2 columns namely id (primary key) and text. See image below for the settings in workbench.
This is the hibernate executable java file
package com.hibernate.hibernate;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
*
* @author maurice
*/
public class Hibernate {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Message message = new Message();
String hql = "FROM Message";
Query query = session.createQuery(hql);
List results = query.list();
System.out.print(results);
//message.setText("hoi");
//session.persist(message);
session.close();
}
}
This is the hibernateUtil file that configures and returns the sessionFactory
package com.hibernate.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
// loads configuration and mappings
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
// builds a session factory from the service registry
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
}
and here is the Annotated POJO that is to be persisted using hibernate.
package com.hibernate.hibernate;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author maurice
*/
@Entity
@Table(name = "message")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Message.findAll", query = "SELECT m FROM Message m"),
@NamedQuery(name = "Message.findById", query = "SELECT m FROM Message m WHERE m.id = :id"),
@NamedQuery(name = "Message.findByText", query = "SELECT m FROM Message m WHERE m.text = :text")})
public class Message implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(name = "text")
private String text;
public Message() {
}
public Message(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Message)) {
return false;
}
Message other = (Message) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.hibernate.hibernate.Message[ id=" + id + " ]";
}
}
Lastly, here is the hibernate.cfg.xml config file.
<?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/hibernate?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class = "com.hibernate.hibernate.Message"/>
</session-factory>
</hibernate-configuration>
Heres the logfile when i run the project. It gives no errors but just freezes
cd C:\book\Hibernate; "JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_71" cmd /c "\"\"C:\\Program Files\\NetBeans 8.1\\java\\maven\\bin\\mvn.bat\" -Dexec.args=\"-classpath %classpath com.hibernate.hibernate.Hibernate\" -Dexec.executable=\"C:\\Program Files\\Java\\jdk1.8.0_71\\bin\\java.exe\" -Dexec.classpathScope=runtime -Dmaven.ext.class.path=\"C:\\Program Files\\NetBeans 8.1\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 org.codehaus.mojo:exec-maven-plugin:1.2.1:exec\""
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...
------------------------------------------------------------------------
Building Hibernate 1.0-SNAPSHOT
------------------------------------------------------------------------
Downloading: file:C:\book\Hibernate/lib/unknown/binary/hibernate-jpamodelgen-4.3.1.Final/SNAPSHOT/maven-metadata.xml
Downloading: file:C:\book\Hibernate/lib/unknown/binary/hibernate-jpamodelgen-4.3.1.Final/SNAPSHOT/hibernate-jpamodelgen-4.3.1.Final-SNAPSHOT.pom
The POM for unknown.binary:hibernate-jpamodelgen-4.3.1.Final:jar:SNAPSHOT is missing, no dependency information available
Downloading: file:C:\book\Hibernate/lib/unknown/binary/mysql-connector-java-5.1.23-bin/SNAPSHOT/maven-metadata.xml
Downloading: file:C:\book\Hibernate/lib/unknown/binary/mysql-connector-java-5.1.23-bin/SNAPSHOT/mysql-connector-java-5.1.23-bin-SNAPSHOT.pom
The POM for unknown.binary:mysql-connector-java-5.1.23-bin:jar:SNAPSHOT is missing, no dependency information available
--- exec-maven-plugin:1.2.1:exec (default-cli) @ Hibernate ---
mrt 09, 2017 7:29:43 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
mrt 09, 2017 7:29:43 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
mrt 09, 2017 7:29:43 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
mrt 09, 2017 7:29:43 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
mrt 09, 2017 7:29:43 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
mrt 09, 2017 7:29:43 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
mrt 09, 2017 7:29:43 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
mrt 09, 2017 7:29:44 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?zeroDateTimeBehavior=convertToNull]
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=scott, password=****}
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
mrt 09, 2017 7:29:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
mrt 09, 2017 7:29:46 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
mrt 09, 2017 7:29:46 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
mrt 09, 2017 7:29:46 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: hibernate.message
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [id, text]
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
mrt 09, 2017 7:29:48 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
[]
Heres a visual example of what i mean with freezing, the loadbar just gets stuck.
Does anyone know what could be causing this? Any help would be appreciated thank you.
Upvotes: 0
Views: 1777
Reputation: 154020
I notice that you haven't closed the SessionFactory
at the end of your program:
sessionFactory.close();
Also, it's of paramount importance to always end the currently running database transaction. Therefore, you should call commit if everything went fine and call rollback in the catch block in case any exception was thrown.
To fix the error you got:
Unknown entity: com.hibernate.hibernate.Message
You need to let Hibernate know about that mapping:
configuration.addAnnotatedClass(Message.class);
Upvotes: 3