guys i am newbie in hibernate .. i am trying to use annotation in hibernate but it gives me an exception .. here is my code .. any suggestions .. thanks in advance
in hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>
<property name="connection.url">jdbc:mysql://localhost:3306/mydb </property>
<property name="connection.user">root </property>
<property name="connection.password">root</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialet">org.hibernate.dialet.MYSQLDialet</property>
<property name="hbm2ddl.auto">create</property>
<!-- Related to hibernate properties END-->
<!-- Related to mapping START-->
<mapping resource="user.hbm.xml" />
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>
DataProvider.java
import javax.persistence.*;
#Entity
#Table(name="dataprovider")
public class DataProvider {
#Id #GeneratedValue
#Column(name="id")
private int user_id;
#Column(name="name")
private String user_name;
#Column(name="description")
private String user_desc;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_desc() {
return user_desc;
}
public void setUser_desc(String user_desc) {
this.user_desc = user_desc;
}
}
in InsertData.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class InsertData {
private static SessionFactory factory;
public static void main(String[] args) {
factory = new AnnotationConfiguration().configure("hibernate.cfg.xml").addAnnotatedClass(DataProvider.class)
.buildSessionFactory();
new InsertData().insertInfo();
}
public void insertInfo() {
Session session = factory.openSession();
DataProvider provider = new DataProvider();
provider.setUser_id(121);
provider.setUser_name("name");
provider.setUser_desc("desc");
Transaction tr = session.beginTransaction();
session.save(provider);
System.out.println("Object Saved");
tr.commit();
session.close();
factory.close();
}
}
the exception
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.hibernate.cfg.annotations.Version.<clinit>(Version.java:12)
at org.hibernate.cfg.AnnotationConfiguration.<clinit>(AnnotationConfiguration.java:78)
at InsertData.main(InsertData.java:11)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
All dependencies required by Hibernate are not loaded, if you use maven all jars referenced are automatically loaded in the Application classpath.
As your error is clearly saying , you are missing a reference to the sl4j jar.
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=7&cad=rja&uact=8&ved=0ahUKEwiBxfuDrM_LAhWCVI4KHU2uBZYQFghAMAY&url=http%3A%2F%2Fmvnrepository.com%2Fartifact%2Forg.slf4j%2Fslf4j-api&usg=AFQjCNFZmEX-pLO1rqWxEyCRGohyjvgEFw
The exception is quite clear: the class org.slf4j.LoggerFactory is required by Hibernate, but was not found. You need to add the corresponding Library to your classpath, i.e. you need an slf4j.jar in addition to hibernate.jar.
Related
Hibernate 6.0.1 with PostgreSQL JDBC driver 42.3.5 causes the following exception:
java.lang.UnsupportedOperationException:
CteInsertStrategy can only be used with Dialects that support CTE that can take UPDATE or DELETE statements as well
at org.hibernate.query.sqm.mutation.internal.cte.CteInsertStrategy.<init>(CteInsertStrategy.java:123)
at org.hibernate.query.sqm.mutation.internal.cte.CteInsertStrategy.<init>(CteInsertStrategy.java:107)
at org.hibernate.dialect.PostgreSQLDialect.getFallbackSqmInsertStrategy(PostgreSQLDialect.java:704)
...
What's wrong and how can I fix the issue?
MyEntity.java
import jakarta.persistence.*;
#Entity
#Table(name = "my_entity")
public class MyEntity {
private Long id;
#Id
#SequenceGenerator(name = "id_sequence", sequenceName = "my_id_sequence")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "id_sequence")
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
}
MyTest.java
import static org.junit.Assert.assertNotNull;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.junit.*;
public class MyTest {
private static Configuration configuration;
private static SessionFactory sessionFactory;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
sessionFactory.close();
}
private Session session;
#Before
public void setUp() throws Exception {
session = sessionFactory.openSession();
}
#After
public void tearDown() throws Exception {
session.close();
}
#Test
public void test() {
Transaction transaction = session.beginTransaction();
MyEntity entity = new MyEntity();
session.persist(entity);
assertNotNull(entity.getId());
transaction.commit();
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/mydb</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_size">30</property>
<property name="hibernate.c3p0.timeout">120</property>
<property name="hibernate.c3p0.max_statements">100</property>
<mapping class="haba713.MyEntity" />
</session-factory>
</hibernate-configuration>
build.gradle
plugins {
id 'java-library'
}
repositories {
mavenCentral()
}
ext {
hibernateVersion = '6.0.1.Final'
}
dependencies {
implementation 'org.postgresql:postgresql:42.3.5'
implementation 'org.hibernate.orm:hibernate-c3p0:' + hibernateVersion
implementation 'org.hibernate.orm:hibernate-core:' + hibernateVersion
testImplementation 'junit:junit:4.13.2'
}
See the full source code here.
The use_jdbc_metadata_defaults configuration property must be true for Hibernate to detect the correct version of the PostgreSQL dialect.
Removing this line
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
from hibernate.cfg.xml resolves the issue.
(Thanks to Christian at Hibernate Zulip channel for sorting this out.)
The same error i got when used wrong hibernate dialect, in my case: org.hibernate.dialect.PostgreSQL9Dialect instead of org.hibernate.dialect.PostgreSQLDialect on PostgreSQL v12.
I'm just getting started trying to use Hibernate to create a PostgreSQL database but keep getting this exception:
org.hibernate.HibernateException: java.lang.IllegalArgumentException: max size attribute is mandatory
It happens when I run my main method on the line where I try to build a session factory but I can't find anything about this exception anywhere online. I'm wondering anyone has any ideas on what could be causing this.
Main Class:
package com.package.ingestor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
public static void main(String[] args){
Student user = new Student();
user.setStudentId(1);
user.setStudentName("Bri Guy");
user.setStudentAge(32);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
Hibernate Object:
package com.bossanova.ingestor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "student", uniqueConstraints={#UniqueConstraint(columnNames={"id"})})
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", length=11, nullable=false, unique=true)
private Integer studentId;
#Column(name = "name", length=20, nullable=true)
private String studentName;
#Column(name="age", length=5, nullable=true)
private Integer studentAge;
public Student() { }
public Student(Integer studId, String studName, Integer studAge) {
this.studentId = studId;
this.studentName = studName;
this.studentAge = studAge;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Integer getStudentAge() {
return studentAge;
}
public void setStudentAge(Integer studentAge) {
this.studentAge = studentAge;
}
#Override
public String toString() {
return "Student= Id: " + this.studentId + ", Name: " + this.studentName + ", Age: " + this.studentAge;
}
}
Config file:
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL95Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="com.bossanova.ingestor.Student"/>
</session-factory>
</hibernate-configuration>
I solved this for me by switching my Maven dependency from hibernate-agroal to hibernate-core.
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
If you are using hibernate-agroal add <type>pom</type> to your dependency
I am trying to write my first hibernate annotation application and below are the things that i did
package org.hibernate.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class Employee {
#Id
#GeneratedValue
Integer id;
#Column(name="Employee_Name")
String userName;
#Column(name="Address")
String age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
/**
* Hi this is to test java commenting
* #return
*/
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Hibernate.config.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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">$Ailaja12</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sessions</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<!-- <property name="show_sql">true</property> -->
<!-- <mapping resource="org/hibernate/pojo/Employee.xml"></mapping> -->
<mapping class="org.hibernate.pojo.Employee"/>
<mapping resource="org/hibernate/pojo/Item.xml"></mapping>
</session-factory>
</hibernate-configuration>
Client
package org.hibernate.client;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.pojo.Employee;
public class Client {
/**
* #param args
*/
public static void main(String[] args) {
//Starting hibernate environment in your application
Configuration conf = new Configuration();
//2 Loading hibernate configuration file
conf.configure("hibernate.cfg.xml");
SessionFactory factory=new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
//SessionFactory factory = conf.buildSessionFactory();
Session session = factory.getCurrentSession();
Employee ee = new Employee();
ee.setUserName("Kranthi");
//ee.setId(123);
ee.setAge("Dallas");
Transaction tx = session.beginTransaction();
session.save(ee);
tx.commit();
session.close();
factory.close();
}
}
I am getting below exception
Exception in thread "main" org.hibernate.MappingException: An AnnotationConfiguration instance is required to use
I tried by googling but none of them has worked
and below are the list of jars that i have used
antlr_2.7.6.jar
asm-3.3.1.jar
cglib-2.2.2.jar
domj-1.3.jar
ehcache.jar
hibernate-3.2.jar
javax.persistence.jar
jta.jar
mysql-connector.jar
commonlogging.jar
Add below jar to your class path: hibernate-annotations.3.3.0.GA.jar or add below dependency to your pom file,if you are using maven project
<dependency>
<groupId>hibernate-annotations</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.0.GA</version>
</dependency>
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 am trying to do a simple hibernate program. I am following the steps given in this tutorial.
The Error that I am getting is
org.hibernate.MappingNotFoundException: resource: org.manu.dtd.UserDetails not found
at org.hibernate.cfg.Configuration.addResource(Configuration.java:799)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2344)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2310)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2290)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2243)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2158)
at org.manu.dtd.TestHibernate.main(TestHibernate.java:16)
Here is my folder structure
My persitence class with annotations is
package org.manu.dtd;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class UserDetails {
#Id
private int userId;
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
My hibernate.cfg.xml file is
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="connection.username">user</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="org.manu.dtd.UserDetails"/>
</session-factory>
</hibernate-configuration>
And finally my main program is
package org.manu.dtd;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class TestHibernate {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(23);
user.setUserName("Renu");
System.out.println("setting values complete");
try {
SessionFactory sF = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sF.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
catch (HibernateException he) {
he.printStackTrace();
}
}
}
Can anyone please help me out to resolve this issue.
Well it looks it can be fixed even easier. You should use <mapping class=..> instead of <mapping resource=..> as resources is for mapping other xml files describing entities and such. Here is small example from the offical tutorials
Provide fully qualified name for hibernate configuration mapping file,
SessionFactory sF = new Configuration().
configure("/org/manu/dtd/hibernate.cfg.xml").buildSessionFactory();