I am using struts2-fullhibernatecore-plugin-2.2.2-GA.jar to inject a session in my DAO class like below:
public class UserDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
public List<User> getUsers() {
return session.createQuery("from user").list();
}
}
But I got
java.lang.NullPointerException
com.wudi.DAO.UserDAO.getUsers(UserDAO.java:28)
com.wudi.action.UserListAction.execute(UserListAction.java:24)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
...
According to debugging output, session and transaction in the UserDAO are null.
Some files for reference:
User.java:
#Entity
#Table(name = "user")
public class User implements Serializable {
#Id
#GeneratedValue
private int id;
#Column
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserListAction.java:
public class UserListAction extends ActionSupport {
private List<User> users;
private UserDAO userDAO = new UserDAO();
#Override
public String execute() throws Exception {
users = userDAO.getUsers();
return SUCCESS;
}
}
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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.pool_size">10</property>
<mapping class="com.wudi.model.User" />
</session-factory>
</hibernate-configuration>
If you want to use the Hibernate Session and Transaction injection capability, your action mapping package need to extend the package hibernate-default.
More details about hibernate-default package
The plugin provides a mapping package called hibernate-default. And this has three interceptor stacks indicated for injection capabilities:
basicStackHibernate: Like Struts2basickStack (NO validations!), but with Hibernate session and transaction injections capability.
defaultStackHibernate: Like Struts2 defaultStack, but without Struts2 validation methods (annotation and XML). Uses Hibernate Validation framework instead.
defaultStackHibernateStrutsValidation: Struts2 defaultStack+ plugin's basicStackHibernate.
This package extends the hibernate-default package, so all default Struts2 configurations can be used if you need.
hibernate-default package is abstract, so you can extends this with other. For example:
<package name="default" extends="hibernate-default,json-default" >
To use hibernate-default with an annotation configuration use
#ParentPackage("hibernate-default")
#InterceptorRef("basicStackHibernate")
public class YourAction extends ActionSupport {}
Related
I am using struts2-fullhibernatecore-plugin-2.2.2-GA.jar to inject a session in my DAO class like below:
public class UserDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
public List<User> getUsers() {
return session.createQuery("from user").list();
}
}
But I got
java.lang.NullPointerException
com.wudi.DAO.UserDAO.getUsers(UserDAO.java:28)
com.wudi.action.UserListAction.execute(UserListAction.java:24)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
...
According to debugging output, session and transaction in the UserDAO are null.
Some files for reference:
User.java:
#Entity
#Table(name = "user")
public class User implements Serializable {
#Id
#GeneratedValue
private int id;
#Column
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserListAction.java:
public class UserListAction extends ActionSupport {
private List<User> users;
private UserDAO userDAO = new UserDAO();
#Override
public String execute() throws Exception {
users = userDAO.getUsers();
return SUCCESS;
}
}
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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.pool_size">10</property>
<mapping class="com.wudi.model.User" />
</session-factory>
</hibernate-configuration>
If you want to use the Hibernate Session and Transaction injection capability, your action mapping package need to extend the package hibernate-default.
More details about hibernate-default package
The plugin provides a mapping package called hibernate-default. And this has three interceptor stacks indicated for injection capabilities:
basicStackHibernate: Like Struts2basickStack (NO validations!), but with Hibernate session and transaction injections capability.
defaultStackHibernate: Like Struts2 defaultStack, but without Struts2 validation methods (annotation and XML). Uses Hibernate Validation framework instead.
defaultStackHibernateStrutsValidation: Struts2 defaultStack+ plugin's basicStackHibernate.
This package extends the hibernate-default package, so all default Struts2 configurations can be used if you need.
hibernate-default package is abstract, so you can extends this with other. For example:
<package name="default" extends="hibernate-default,json-default" >
To use hibernate-default with an annotation configuration use
#ParentPackage("hibernate-default")
#InterceptorRef("basicStackHibernate")
public class YourAction extends ActionSupport {}
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 can't figure out why an object will not map via Annotations. No matter what I try, I always receive this error:
org.hibernate.MappingException: Unknown entity: com.hibernate.practice.Car
I was loosely following the tutorial here but can't seem to get anything working. I've tried to strip the object down to its bare bones (thinking that I was making an error in the code somewhere), but again, even with just an ID, and a name Column, I still fail to get this working.
My hibernate.cfg is from the Netbeans Hibernate tutorial.
<?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/practicedb?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">pass</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Also, per the instructions, I've added the HibernateUtil.java class.
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().addPackage("com.hibernate.practice").buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
I set up a simple class. It's a Car with an ID and a Name.
#Entity
public class Car {
#Id
#GeneratedValue
#GenericGenerator(name="increment", strategy="incrememnt")
private long id;
#Column(name="car_name")
private String name;
public Car() {
}
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;
}
}
And finally, I'm trying to test this stuff out like this:
#Test
public void testOutHibernate() {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Car car = new Car();
car.setName("red one");
session.save(car);
try {
Transaction t = session.beginTransaction();
session.save(car);
t.commit();
}
finally {
session.close();
}
session.close();
}
Without fail I get the Unknown Entity Exception. Is there something glaringly obvious that I'm missing?
You need to add your annotated class as follows -
sessionFactory = new AnnotationConfiguration()
.addAnnotatedClass(Car.class)
.addPackage("com.hibernate.practice")
.configure()
.buildSessionFactory();
You can find a discussion regarding the addPackage() method here - https://forum.hibernate.org/viewtopic.php?f=1&t=980723.
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();
I get tired of this for a long time. I do not know what caused this error. Here are my files:
Uzytkownik.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="Uzytkownik" table="uzytkownicy">
<id column="id" name="id" type="int"/>
<property column="login" generated="never" lazy="false" name="login" type="string"/>
<property column="haslo" generated="never" lazy="false" name="haslo" type="string"/>
</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 name="">
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/sprawozdania</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<mapping resource="com/vaannila/uzytkownik/Uzytkownik.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I use mysql 5.5.
I get the following error:
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.vaannila.util.HibernateUtil.<clinit>(HibernateUtil.java:14)
at com.vaannila.uzytkownik.Main.saveUzyt(Main.java:22)
at com.vaannila.uzytkownik.Main.main(Main.java:16)
Caused by: org.hibernate.MappingException: entity class not found: Uzytkownik
This are my classes:
main.java
package com.vaannila.uzytkownik;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import javax.persistence.Entity;
import com.vaannila.util.HibernateUtil;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
Main obj = new Main();
String uzytkownikLogin = obj.saveUzyt("Adam", "Malysz");
}
public String saveUzyt(String login, String haslo){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
String uzytLog = null;
try {
transaction = session.beginTransaction();
Uzytkownik uzyt = new Uzytkownik();
uzyt.setLogin(login);
uzyt.setHaslo(haslo);
uzytLog = (String) session.save(uzyt);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return uzytLog;
}
}
Uzytkownik.java:
package com.vaannila.uzytkownik;
// default package
// Generated 2011-07-14 13:39:18 by Hibernate Tools 3.4.0.CR1
/**
* Uzytkownik generated by hbm2java
*/
public class Uzytkownik implements java.io.Serializable {
private int id;
private String login;
private String haslo;
public Uzytkownik() {
}
public Uzytkownik(int id) {
this.id = id;
}
public Uzytkownik(int id, String login, String haslo) {
this.id = id;
this.login = login;
this.haslo = haslo;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public String getHaslo() {
return this.haslo;
}
public void setHaslo(String haslo) {
this.haslo = haslo;
}
}
HibernateUtil.java:
package com.vaannila.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Maybe your mapping file is not complete but other wise it should be:
<class name="com.vaannila.uzytkownik.Uzytkownik" table="uzytkownicy">
=> need to set fully qualified class name (with package)
I think it makes sense to specify full-qualified entity class name:
<class name="com.vaannila.uzytkownik.Uzytkownik" table="uzytkownicy">
Don't forget to mention your class using as a entity classes in hibernate configeration file using the mapping tag !!
Example:
<session-factory>
//database configeration goes here
<mapping class="org.fbis.models.Form3A"/>
</session-factory>
Stijn Geukens answers right,but I want to point out more information about this question.
There are two reasons I know causing this problem: entity class not found
First, As Stijn Geukens answers, Your Hibernate mapping is not right, the value of name attribute for the tag class should be the Java class with package ahead.
Second, if you have boolean filed in your Java class, this field can't start with is.Otherwise, the hibernate throws an exception getter method is not found... when run by Java Debug mode or Run mode.But when it comes to web project and you run your project as Server Application,the message becomes entity class not found.It made me puzzled for a long time.So do not name your boolean field with is ahead.