The Situation
Ok, so I am learning Hibernate(from 2 days so pardon any blunder), I am using mysql database and just trying tocreate a table Employee and make an entry in database(A demonstration).
Here are the codes
POJO:
package com.sopra.pojo;
import javax.persistence.*;
#Entity
#Table(name = "EMPLOYEE")
public class Employee {
#Id
private int Id;
private String firstName;
private String lastName;
private int salary;
public int getId() {
return Id;
}
public void setId(int id) {
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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
hibernate.cfg.xml which is in src
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name = "hibernate.hbm2ddl.auto">create</property>
<mapping class="com.sopra.pojo.Employee" />
</session-factory>
</hibernate-configuration>
EmployeeDBManager.java
package com.sopra.pojo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmployeeDBManager {
public static void main(String[] args) {
Employee e = new Employee();
e.setFirstName("Salim");
e.setId(672);
e.setLastName("Shamim");
e.setSalary(266);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(e);
tx.commit();
session.close();
}
}
The Error
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.employee' doesn't exist
I've tried
use this in cfg file : <property name="hibernate.hbm2ddl.auto">update</property>
What is interesting is when I manually create the table in mysql using workbench, hibernate does drops it as when i use drop command it says the table doesn't exists.
I can't figure out where the glitch might be(newbie and internet didn't helped).
Please mention any additional details required in comments.
Please help!
Thanks.
I made it worked, I am not sure if it's a proper answer but since it got it working I am posting it as an answer.
I made two changes
I was using hibernate version 5.2.12 so I changed it to 4.2.0 and added jars from two more folders which earlier I hadn't (In summary I have now imported Jars from :optional, provided & required folder in hibernate user library)
I overlooked a url mistake which was
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
In the dtd url I have not added www. It should have been
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">`
So, my mistake.
Anyway, comments regarding improving this answer and why it made it work are deeply appreciated.
add different auto option of hibernate,
Use instead of create , update or create-drop
<property name="hibernate.hbm2ddl.auto">update</property>
or
<property name="hibernate.hbm2ddl.auto">create-drop</property>
You can read more about it here
Related
for testing purpose i wrote very small code,which repeatedly throws exception related to jdbc driver.
package sally;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class MainClass {
public static void main(String args[]){
try{
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Employee ee=new Employee("abx","asd",2000);
session.save(ee);
tx.commit();
}catch(Exception e){
e.printStackTrace();
}
}
}
This is my ben/pojo class for mapping
package sally;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
<?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="sally.Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
and this is cfg file for pojo class:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="sally.Employee"></mapping>
</session-factory>
but every time i am running the code it throws exxception :
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
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 sally.MainClass.main(MainClass.java:12)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
... 5 more
can any body tell whats wrong here???
this is db column list : first_name last_name salary.
You need to put the mysql JDBC driver JAR on your classpath
name for the driver class must be updated as well as server time zone (for me this is insane but it has to be done
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/hibernate?serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
</session-factory>
</hibernate-configuration>
org.hibernate.exception.JDBCConnectionException: Cannot open connection It occurs when you have not started the xampp and MySql.
I am trying to run a simple java project to see the working of hibernate but when i am executing my code (StoreData.java) it gives a hibernate exception, i am using oracle 11g R2 and eclipse galileo , my oracle SID is "orcl" connection name is "mysql" username is "sys" password is "oracle". Here is the code:
Employee.java:
*package com.persist;
public class Employee {
private int id;
private String firstName;
private String lastName;
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;
}
}*
employee.hbm.xml :
*<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.persist.Employee" table="Emp">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>*
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="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:orcl</property>
<property name="connection.username">sys</property>
<property name="connectio.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>*
StoreData.java :
*package com.DAO;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.persist.Employee;
public class StoreData {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration cf = new Configuration();
cf.configure("hibernate.cfg.xml");
SessionFactory factory =cf.buildSessionFactory();
Session session =factory.openSession();
Transaction t =session.beginTransaction();
Employee e = new Employee();
e.setId(1);
e.setFirstName("samar");
e.setLastName("singh");
session.persist(e);
t.commit();
session.close();
System.out.println("successfully saved");
}
}*
console:
*log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
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 com.DAO.StoreData.main(StoreData.java:27)
Caused by: java.sql.SQLException: invalid arguments in call
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
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*
project hierarchy :
Try with below property:
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:Oracle:thin:#localhost:1521:orcl</property>
<property name="connection.username">sys</property>
<property name="connection.password">oracle</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
Try finding the latest ojdbc jar,old ojdbc14 jar wont work with latest db,I got the same issue i have used ojdbc7 jar problem solved
This is my first time trying out Hibernate with Eclipse and the following are the things I did:
Created a Java Bean called Student.java which is as follows:
package com.jwt.hibernate;
public class Student {
private long id;
private String name;
private String degree;
private String roll;
private String phone;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Created a mapping file, Student.hbm.xml as follows:
<hibernate-mapping>
<class name="com.jwt.hibernate.Student" table="student">
<id column="ID" name="id" type="long" />
<property column="name" name="name" type="string" />
<property column="degree" name="degree" type="string" />
<property column="roll" name="roll" type="string" />
<property column="phone" name="phone" type="string" />
</class>
</hibernate-mapping>
3. Created the hibernate configuration file, hibernate.cfg.xml as follows:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetutorial</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</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>
<mapping resource="com/jwt/hibernate/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Created the class SimpleTest.java which is as follows:
package com.jwt.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class SimpleTest {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Student student = new Student();
student.setName("Mukesh");
student.setRoll("101");
student.setPhone("8888");
student.setDegree("B.E");
Transaction tx = session.beginTransaction();
session.save(student);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
Now, when I try to run SimpleTest, I get the following error:
**INFO: HHH000412: Hibernate Core {4.3.7.Final}
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.hibernate.cfg.Configuration.reset(Configuration.java:326)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:291)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:295)
at com.jwt.hibernate.SimpleTest.main(SimpleTest.java:11)
Caused by: java.lang.NullPointerException
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
at org.hibernate.cfg.Environment.<clinit>(Environment.java:221)
... 4 more**
I double checked and made sure that all the configuration and jar files were added to the classpath. So that is not the problem. I would really appreciate some insights as to what may have caused this problem and inturn, how to solve it.
Thanks in advance!
I would recommend updating to later version of SLF4J.
Or
Your Hibernate.cfg.xml is not on classpath. What folder is it in?
Edit :
Caused by: java.lang.NullPointerException
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
This is actual exception in your code, If your Hibernate.cfg.xml is loaded then check for SELF4J version, Don't use user library to take your jar files, put all libraries in your lib folder and then configure those in class path.
You may find a Java Configuration of Hibernate to be more friendly. Here is an example of one that I did (Note: there are Spring annotations like #Autowired and #PostConstruct in this class so don't get confused):
public class HibernateConfigBean {
private static final Logger logger = Logger.getLogger(HibernateConfigBean.class);
#Autowired private Environment environment;
private SessionFactory sessionFactory;
private Configuration configuration;
#PostConstruct
private void init(){
configuration = new Configuration();
configuration.setProperty("hibernate.dialect", environment.getProperty("hibernate.dialect"));
configuration.setProperty("hibernate.connection.driver_class", environment.getProperty("hibernate.connection.driver_class"));
configuration.setProperty("hibernate.connection.url", environment.getProperty("hibernate.connection.url"));
configuration.setProperty("hibernate.connection.username", environment.getProperty("db_username"));
configuration.setProperty("hibernate.connection.password", environment.getProperty("db_password"));
//Add additional Annotated Classes here
configuration.addAnnotatedClass(UserEntity.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public SessionFactory getSessionFactory(){
return sessionFactory;
}
//This should be visible outside of the package as it's only used by the GenerateDbSchema class
void generateSchema() throws Exception {
try{
new SchemaExport(configuration).create(false, true);
} catch (RuntimeException re){
throw new Exception(re);
}
}
}
Then I just put my values into a properties file :-)
I want to learn how Hibernate works, so found this tutorial. But i get this error:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at mypackage.StoreData.main(StoreData.java:14)
Caused by: org.dom4j.DocumentException: Connection refused: connect Nested exception: Connection refused: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
... 2 more
I found out, that many people have the same issue with the same tutorial. For example link, or another link.
Another issue is, that it takes far to long to show the error after starting the programm(40 sek).
Here is my main class:
package mypackage;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class StoreData {
public static void main(String[] args) {
try {
// creating configuration object
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");// populates the data of the
// configuration file
// creating seession factory object
SessionFactory factory = cfg.buildSessionFactory();
// creating session object
Session session = factory.openSession();
// creating transaction object
Transaction transaction = session.beginTransaction();
Employee e1 = new Employee();
e1.setId(115);
e1.setFirstName("Elvis");
e1.setLastName("Presley");
session.persist(e1);// persisting the object
transaction.commit();// transaction is committed
session.close();
System.out.println("successfully saved");
}catch (HibernateException ex) {
ex.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
Hibernate configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://127.0.0.1:1433;databaseName=hibernatetutorial;</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
Employee 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-mapping>
<class name="mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
and Employee.java:
package mypackage;
public class Employee {
private int id;
private String firstName;
private String lastName;
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;
}
}
And this are my jars and all files.
Someone knows what is the issue here?
in your Hibernate configuration file, mapping is commented, and
<property name="hibernate.hbm2ddl.auto">create_drop</property>
is supposed to be update, not create_drop
I was facing the same error. In my case with another hibernate maven tutorial, I just forgot to run the service like this:
mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial"
In my hibernate programme I am getting the following exception:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: An AnnotationConfiguration instance is required to use
My Hibernate.cfg.config file is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mayank</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show-sql">true></property>
<property name="hbm2ddl.auto">update</property>
<mapping class="one.Student"/>
</session-factory>
</hibernate-configuration>
The Student file is
package one;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Student
{
#Id
private Long id;
private int roll;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(Long id, int roll, String name) {
super();
this.id = id;
this.roll = roll;
this.name = name;
}
public Student() {
// TODO Auto-generated constructor stub
}
}
What does the Exception mean and what am I doing wrong?
In place of Configuration cfg = new Configuration();
we need to use AnnotationConfiguration
cfg = new AnnotationConfiguration();
For XML File: Configuration
For Annotation: AnnotationConfiguration
In my case I downloaded dtd file locally on my machine under path(D:/Praful_WorkSpace/firstHibernate/src/hibernate-configuration-3.0.dtd) and then I mentioned that path in the xml file declaration. I followed same thing for both the xml files.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"file:///D:/Praful_WorkSpace/firstHibernate/src/hibernate-configuration-3.0.dtd">
(1)Add the dependency in Maven's pom.xml
<dependency>
<groupId>hibernate-annotations</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.0.GA</version>
</dependency>
(2)Use AnnotationConfiguration to build session factory
Normal Hibernate XML file mapping is using Configuration()
return new Configuration().configure().buildSessionFactory();
For Hibernate annotation, you have to change it to AnnotationConfiguration
return new AnnotationConfiguration().configure().buildSessionFactory();