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>
Related
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.
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>
I am doing a simple hibernate program in which I use Attribute override and Embedded object keys and I got this error:
Exception in thread "main" org.hibernate.MappingException: Repeated
column in mapping for entity: com.hibernate.Model.Employee column:
pincode (should be mapped with insert="false" update="false")
Employee.java
package com.hibernate.Model;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String LastName;
private String email;
private String phoneNo;
#Embedded
#AttributeOverrides({
#AttributeOverride (name="City" , column=#Column(name="OFFICE_CITY")),
#AttributeOverride (name="State", column=#Column(name="OFFICE_STATE")),
#AttributeOverride (name="Country", column=#Column(name="OFFICE_COUNTRY")),
#AttributeOverride (name="pinCode", column=#Column(name="OFFICE_PINCODE"))})
private Address officeAddress;
#Embedded
private Address homeAddress;
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) {
LastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Address getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
}
Address.java
package com.hibernate.Model;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String City;
private String State;
private String Country;
private String pincode;
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
Hibernate.jsp
package com.hibernate.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.Model.Address;
import com.hibernate.Model.Employee;
public class HibernateTest {
public static void main(String[] args) {
Employee emp = new Employee();
Address addr=new Address();
emp.setFirstName("Vikas");
emp.setLastName("Bhardwaj");
emp.setEmail("bhardwajvikas93#gmail.com");
emp.setPhoneNo("9741178304");
addr.setCity("MEHRE");
addr.setCountry("INDIA");
addr.setState("HIMACHAL");
addr.setPincode("174305");
emp.setHomeAddress(addr);
Address addr2 = new Address();
addr2.setCity("Bangalore");
addr2.setCountry("INDIA");
addr2.setState("KARNATKA");
addr2.setPincode("560008");
emp.setOfficeAddress(addr2);
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session ssn = sf.openSession();
ssn.beginTransaction();
ssn.save(emp);
ssn.getTransaction().commit();
ssn.close();
}
}
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.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/HibernateDb</property>
<property name="connection.username">root</property>
<property name="connection.password">vikas</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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>
<!-- Names the annotated entity class -->
<mapping class="com.hibernate.Model.Employee"/>
<mapping class="com.hibernate.Model.Address"/>
</session-factory>
</hibernate-configuration>
In this program by embedable, I am printing both member variables in one table.
The task is with address class, I am printing two addresses. One is for home address and one is for office address by using AttributeOverrides but it gives me the error mentioned above.
You need to specify a valid property name pincode
#AttributeOverride (name="pinCode", column=#Column(name="OFFICE_PINCODE"))
need to change to
#AttributeOverride (name="pincode", column=#Column(name="OFFICE_PINCODE"))
Try to specify #AttributeOverrides for homeAddress, if it will not help.
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!
I created an inner enum "UserType" inside my class "User", which is used to determine if an instance of a User is a BASIC, a DEPARTMENT_EXCLUSIVE, or a SUPERUSER. Here's a snippet of the code:
public class User {
private String id, lastName, firstName, middleName, password;
private UserType userType;
public void setId(String id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public void setPassword(String password) {
this.password = Encryption.encrypt(password);
}
public void setUserType(UserType userType) {
this.userType = userType;
}
public String getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getPassword() {
return password;
}
public UserType getUserType() {
return userType;
}
public enum UserType {
BASIC, DEPARTMENT_HEAD, SUPERUSER;
}
}
Now, I want to save the instantiated object to my MySQL database using an ORM. I'm using Hibernate. Here's my Hibernate mapping file snippet inside the class tag:
<id name="id" type="string" column="id"/>
<property name="lastName" column="lastName" type="string" not-null="true"/>
<property name="firstName" column="firstName" type="string"/>
<property name="middleName" column="middleName" type="string"/>
<property name="password" column="password" type="string" not-null="true"/>
<property name="userType" column="userType" not-null="true">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">com.fileManagement.dataDesign.User.UserType</param>
<param name="type">12</param>
<param name="useNamed">true</param>
</type>
</property>
I ran some tests and an exception was throw, telling that the enum couldn't be found. Here's the test code:
SessionFactory f = HibernateUtil.getSessionFactory();
Session s = f.openSession();
Transaction t = s.beginTransaction();
User user = new User();
user.setId("0090713");
user.setLastName("Nocos");
user.setFirstName("Warren");
user.setMiddleName("Manlangit");
user.setPassword("wang1234");
user.setUserType(UserType.DEPARTMENT_HEAD);
s.save(user);
t.commit();
s.close();
f.close();
And here's the snippet of the exception stack trace :
Caused by: org.hibernate.HibernateException: Enum class not found
at org.hibernate.type.EnumType.setParameterValues(EnumType.java:244)
at org.hibernate.type.TypeFactory.injectParameters(TypeFactory.java:131)
at org.hibernate.type.TypeFactory.custom(TypeFactory.java:214)
... 12 more
Caused by: java.lang.ClassNotFoundException: com.fileManagement.dataDesign.User.UserType
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
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:340)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:171)
at org.hibernate.type.EnumType.setParameterValues(EnumType.java:241)
... 14 more
I tried making the enum as an outer one and it worked well, but I really want to place this inside the "User" class as an inner one due to a design choice, since it's only usable on that class. Is it possible to do that way? If yes, how?
As mentioned in my comments, try declaring the enum class in mapping file as:
com.fileManagement.dataDesign.User$UserType
Generally if we want to access any inner classes in Hibernate then we need to use the $ symbol.