When trying to save Student using session, I get this error though I used
.addAnnotatedClass(Student.class)
in Configuration and used
<mapping class="com.hibernate_demo.models.Student"/>
in Hibernate.cfg.xml
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate_demo.models.Student
at org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl.entityPersister(MappingMetamodelImpl.java:589)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1450)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:36)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:30)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:632)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:625)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:620)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at jdk.proxy2/jdk.proxy2.$Proxy35.save(Unknown Source)
at com.hibernate_demo.application.CreateStudentDemo.main(CreateStudentDemo.java:24)
Student.java
package com.hibernate_demo.models;
import javax.persistence.*;
#Entity
#Table(name = "Student")
public class Student {
#Id
private long id;
#Column(name="first_name", nullable = false)
private String firstName;
#Column(name="last_name", nullable = false)
private String lastName;
#Column(name="email", nullable = false)
private String email;
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public Student() {}
public long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property
name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Hibernate</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.hibernate_demo.models.Student"/>
</session-factory>
</hibernate-configuration>
CreateStudentDemo.java
package com.hibernate_demo.application;
import com.hibernate_demo.models.Student;
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();
// Using session object to save Java object
try (factory; Session session = factory.getCurrentSession()) {
factory.openSession();
System.out.println("Creating new student object...");
Student tempStudent = new Student("Tomasz", "Jurek", "jur.tomasz13#gmail.com");
System.out.println("Begin transaction");
session.beginTransaction();
System.out.println("Saving student..");
session.save(tempStudent);
System.out.println("Commiting transaction");
session.getTransaction().commit();
System.out.println("Transaction commited");
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Hibernate-Demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Beta3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
</project>
Soo I used Hibernate 6.0.0.3 Beta Version, I changed it to latest non beta build (5.6.4.Final) and it worked.
Related
I am getting error when i run application.
This Is My Simple Hibernate Application.
When I Run My Application Is Eclipse IDE It Gives Me Error.
Error : org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
I Get This Error When I Run My Application.
This Is My Student Class.
Student.java
package com.nikunj.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
public Student() {
// super();
}
public Student(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
This Is My Hibernate Configuration XML File.
hibernate.cfg.xml
<!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 My Main Class.
CreateStudentDemo.java
package com.nikunj.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.nikunj.hibernate.demo.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
try {
// Create session factory
SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class)
.buildSessionFactory();
// Use the session object to save Java object
Session session = factory.getCurrentSession();
// Create a student object
System.out.println("Creating new student object...");
Student tempStudent = new Student("Nikunj", "Rathva", "Nikunjrathva108#gmail.com");
// Start a transaction
session.beginTransaction();
// Save the student object
System.out.println("Saving the student...");
session.save(tempStudent);
// Commit transaction
session.getTransaction().commit();
System.out.println("Done!");
factory.close();
} catch (Exception e) {
System.out.println("\n\n\nError : " + e + "\n\n\n");
e.printStackTrace();
}
}
}
```[Jar Files For Hibernate ORM][1]
[1]: https://i.stack.imgur.com/6iORy.png
I am working on writing a most minimal program to do CRUD operations on mysql using hibernate in Java.
I am following below tutorial at:
https://medium.com/#amrut.patil88/crud-with-java-hibernate-and-mysql-part-1-f6b1d6f7dbbf
I have created user in mysql and started it.
CreateStudentDemo.java is :
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
//import com.luv2code.hibernate.demo.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
//create a Session Factory
SessionFactory sessionFactory = new Configuration().
configure("hibernate.cfg.xml").
addAnnotatedClass(Student.class).
buildSessionFactory();
//create a Session
Session session = sessionFactory.getCurrentSession();
try{
System.out.println("Creating a new Student object...");
//create the Student object
Student student = new Student("Paul", "Walker","paul.walker#gmail.com");
//start a transaction
session.beginTransaction();
//Save the Student object to the database
session.save(student);
System.out.println("Java object saved to the database");
//commit the transaction
session.getTransaction().commit();
}finally{
sessionFactory.close();
}
}
}
Student.java is:
//package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name=”student”)
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name=”id”)
private int id;
#Column(name=”first_name”)
private String firstName;
#Column(name=”last_name”)
private String lastName;
#Column(name=”email”)
private String email;
public Student(){
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return “Student [id=” + id + “, firstName=” + firstName + “, lastName=” + lastName + “, email=” + email + “]”;
}
}
In Student.java,
my eclipse is showing error on : #Table(name=”student”)
"syntax error on tokens. delete these tokens".
Is it because some library/jar is not installed?
hibernate.cfg.xml is:
<!DOCTYPE hibernate-configuration SYSTEM
"classpath:hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory> <! — allows us to get session objects for connecting to the database -->
<! — JDBC Database connection settings -->
<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”connection.url”>jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false</property>
<property name=”connection.username”>hb_student2</property>
<property name=”connection.password”>Student123&$,</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>
I have created a project in eclipse and have copied "required" jars from hibernate downnload.
Now, when I run CreateStudentDemo.java, I get below error:
Jun 02, 2020 2:57:29 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.4.17.Final
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:234)
at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
at CreateStudentDemo.main(CreateStudentDemo.java:14)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,21]
Message: The content of elements must consist of well-formed character data or markup.]
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:485)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:463)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:435)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 5 more
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,21]
Message: The content of elements must consist of well-formed character data or markup.
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source)
at com.sun.xml.internal.stream.XMLEventReaderImpl.peek(Unknown Source)
at javax.xml.stream.util.EventReaderDelegate.peek(Unknown Source)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor$NamespaceAddingEventReader.peek(JaxbCfgProcessor.java:254)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXEventConnector.handleCharacters(StAXEventConnector.java:179)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(StAXEventConnector.java:141)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:460)
... 7 more
Please help.
I think it's because you are using a special character ” instead of ". there is big difference between them. so try to replace ” with " in all your code. this happens always especially if you copy code from a tutorial which is using wrong characters.
also in the XML file, for the comment it must be done this way <!-- comment --> and not <! — comment -->
copy paste, I replaced all of them for you :)
Student.java :
//package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Student(){
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
hibernate.cfg.xml :
<!DOCTYPE hibernate-configuration SYSTEM "classpath:hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- allows us to get session objects for connecting to the database -->
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false</property>
<property name="connection.username">hb_student2</property>
<property name="connection.password">Student123&$,</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 my project structure:
I have these following files:
context.xml
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource name="jdbc/sakila"
url="jdbc:mysql://localhost/sakila"
username="root"
password=""
driverClassName="com.mysql.jdbc.Driver"
type="javax.sql.DataSource"
maxActive="20" maxIdle="5" maxWait="10000"
/>
</Context>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="sakila" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>java:comp/env/jdbc/sakila</non-jta-data-source>
</persistence-unit>
</persistence>
And in a DAO class I can use:
EntityManagerFactory sakilaFactory = Persistence.createEntityManagerFactory("sakila");
EntityManager entityManager = sakilaFactory.createEntityManager();
which all works fine..
But I want to change my configuration to using .xml files and instead of EntityManager I want to use Session from Hibernate API.
I have looked at several tutorials on the web but I am only more confused. How should I use the .xml files for Hibernate configuration?
I am running the application on Tomcat and here is my dependencies from pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>provided</scope>
</dependency>
What I want to achieve is a proper Hibernate configuration, and using Session instead of EntityManager.
Edit #1: This is what my Actor class looks like:
package biz.tugay.model;
/* User: koray#tugay.biz Date: 06/08/15 Time: 09:17 */
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
#Table(name = "actor")
public class Actor {
private Integer actor_id;
private String first_name;
private String last_name;
private Timestamp last_update;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getActor_id() {
return actor_id;
}
public void setActor_id(Integer id) {
this.actor_id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Timestamp getLast_update() {
return last_update;
}
public void setLast_update(Timestamp last_update) {
this.last_update = last_update;
}
#Override
#Transient
public String toString() {
return "Actor{" +
"id=" + actor_id +
", first_name='" + first_name + '\'' +
", last_name='" + last_name + '\'' +
", last_update=" + last_update +
'}';
}
}
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:PORT/databasename</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">XXXX</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create </property>
<property name="hbm2ddl.auto">validate</property>
<mapping class="com.packageClass"/>
<mapping class="com.package.OtherClass"/>
</session-factory>
you should have the hibernate.cfg.xml - configuration file for hibernate; i gave you a template above.It should be placed in the src of your java resources. Now you can use annotations for persistance. And you should also add #Column annotation on every attribute in you actor class to map every attribute on an attribute from your table.Here is an example class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="useri")
public class User implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id_user;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="rol")
private String rol;
public Integer getId_user() {
return id_user;
}
public void setId_user(Integer id_user) {
this.id_user = id_user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRol() {
return rol;
}
public void setRol(String rol) {
this.rol = rol;
}
public User() {
}
}
I have been facing problem in using second level cache. following are the required source you need to find out what the problem is.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- a SessionFactory instance -->
<session-factory>
<!-- User / Password -->
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- Database / Dialect Settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate_001</property>
<property name="show_sql">true</property>
<!-- Second Level Cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- mapping files -->
<mapping class="com.example.bean.Employee"/>
</session-factory>
Employee Persistance Class
#Entity
#Cacheable
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
#Table(name="employee")
public class Employee {
#GeneratedValue
#Id
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
#Column(name="registration_date")
private String registrationDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(String registrationDate) {
this.registrationDate = registrationDate;
}
}
stacktrace
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
org.hibernate.HibernateException: could not instantiate RegionFactory [org.hibernate.cache.ehcache.EhCacheRegionFactory]
at org.hibernate.cfg.SettingsFactory.createRegionFactory(SettingsFactory.java:402)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:270)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2163)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2159)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1383)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
at com.example.dao.HibernateSessionFactory.getSessionFactory(HibernateSessionFactory.java:11)
at com.example.control.Main.main(Main.java:12)
Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.ehcache.EhCacheRegionFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:192)
at org.hibernate.cfg.SettingsFactory.createRegionFactory(SettingsFactory.java:397)
... 7 more
Couldn't create session factory
Assuming it's a maven based project, add below dependency in your pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.0.1.Final</version>
</dependency>
I am making a sample application using hibernate and h2 database. I have an entity class (actually more than 1, but let's start with making it work for 1 of them), which looks like that:
package ~path.examples.testjpa.domain;
import javax.persistence.*;
import java.util.*;
/**
* Created by Me on 2015-04-20.
*/
#Entity
#Table(name= "Persons")
public class Person {
#Id
#Column(nullable= false)
#GeneratedValue(strategy = GenerationType.AUTO)
protected int persId;
#Column(nullable= false, length = 50)
private String firstName;
#Column(nullable= false, length = 50)
private String surname;
#Column(nullable= true, length = 50)
private String emailAddress;
#OneToOne
private Account account;
#OneToMany(targetEntity = PhoneNumber.class)
List phoneNumberList;
public Person() {
// empty
}
public Person(int persId, String firstName, String surname, String emailAddress) {
this.persId = persId;
this.firstName = firstName;
this.surname = surname;
this.emailAddress = emailAddress;
}
public List getPhoneNumberList() {
return phoneNumberList;
}
public void setPhoneNumberList(List<PhoneNumber> phoneNumberList) {
this.phoneNumberList= phoneNumberList;
}
public int getPersId() {
return persId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
#Override
public String toString() {
return "Person [persId=" + persId + ", firstName=" + firstName + ", surname=" + surname + ", emailAddress=" + emailAddress + "]";
}
}
Here is my persistance.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="jpaTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:~/test" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.password" value="" />
<property name="schemaUpdate" value="true" />
</properties>
</persistence-unit>
</persistence>
and the jpaTest class, supposed to make the connection
package ~path.examples.service;
import ~path.examples.testjpa.domain.Person;
import javax.persistence.*;
/**
* Created by Me on 2015-04-22.
*/
public class JpaTest {
public static void main(String args[]) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jpaTest");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
Person person = new Person();
person.setFirstName("Charles");
person.setSurname("Dickens");
em.persist(person);
userTransaction.commit();
em.close();
entityManagerFactory.close();
}
}
When I try to run it, I get the following:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289)
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1371)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:60)
at eu.rivetgroup.examples.service.JpaTest.main(JpaTest.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1263)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:57)
... 6 more
Caused by: java.sql.SQLException: No suitable driver found for jdbc:h2:~/test
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:173)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:276)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
... 11 more
My guess is, that I'm missing something obvious, as I am an inexperienced user.
However, I looked at all the places that I could find, and so far no answer has seemed to help me
thanks for your help!