openSession(), getCurrentSession(), beginTransaction(), lazy load - java

I have a simple java web application that receive some information from database and display that information in web browser. Hibernate is used to interact with database in servlets and jsp files. All work as I want, but I don't understand some things.
Database is simple - 2 tables: Question and Answer. Relationship between tables is one-to-many: one Question can have many Answers.
This is code of java classes Question and Answer:
Question.java
package app;
import java.util.Set;
public class Question {
Long id = null;
String text = "";
Set<Answer> answers = null;
public Question() {
}
public void setId(Long id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public void setAnswers(Set<Answer> answers) {
this.answers = answers;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
public Set<Answer> getAnswers() {
return answers;
}
}
Answer.java
package app;
public class Answer {
Long id = null;
String text = "";
Question question = null;
public Answer() {
}
public void setId(Long id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public void setQuestion(Question question) {
this.question = question;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
public Question getQuestion() {
return question;
}
}
And this is configuration of Hibernate:
hibernate.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>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost;databaseName=Test</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="question.hbm.xml"/>
<mapping resource="answer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
question.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="app">
<class name="app.Question" table="Question">
<id column="id" name="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property column="text" name="text" not-null="true" type="java.lang.String"/>
<set name="answers">
<key column="question_id"/>
<one-to-many class="app.Answer"/>
</set>
</class>
</hibernate-mapping>
answer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="app">
<class name="app.Answer" table="Answer">
<id column="id" name="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property column="text" name="text" not-null="true" type="java.lang.String"/>
<many-to-one class="app.Question" column="question_id" name="question" not-null="true"/>
</class>
</hibernate-mapping>
So in Question there is a collection of Answers. Because of this there would be a lazy load of Answers. I want to use Hibernate objects in my jsp files, so I use this technique: the filter is used to create a session, and this session is used in both servlet and coresponding jsp file.
This is code of that my filter:
HibernateFilter.java
package app;
import java.io.IOException;
import javax.servlet.*;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateFilter implements Filter {
private SessionFactory sessionFactory;
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
try {
sessionFactory.getCurrentSession().beginTransaction();
chain.doFilter(request, response);
sessionFactory.getCurrentSession().getTransaction().commit();
} catch (Exception ex) {
sessionFactory.getCurrentSession().getTransaction().rollback();
ex.printStackTrace();
}
}
public void init(FilterConfig filterConfig) throws ServletException {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public void destroy() {
}
}
There are two servlets and two coresponding jsp files in my application - first ones display question with ID = 1, second ones display all questions. This is code of this servlets, coresponding jsp files and configuration of tomcat:
GetOneQuestion.java
package app;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class GetOneQuestion extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
Session session = new Configuration().configure()
.buildSessionFactory().getCurrentSession();
session.beginTransaction();
Question question = (Question)session.load(Question.class, 1L);
//session.getTransaction().commit();
request.setAttribute("oneQuestion", question);
} catch (Exception ex) {
ex.printStackTrace();
request.setAttribute("oneQuestion", null);
}
RequestDispatcher view = request.getRequestDispatcher("/oneQuestion.jsp");
view.forward(request, response);
}
}
oneQuestion.jsp
<%#page import="app.Answer"%>
<%#page import="app.Question"%>
<html>
<body>
<%
Question question = (Question)request.getAttribute("oneQuestion");
out.print("<br>" + question.getText() + "<br><br>");
%>
</body>
</html>
GetAllQuestion.java
package app;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.List;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class GetAllQuestion extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
Session session = new Configuration().configure()
.buildSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from Question");
List all = query.list();
request.setAttribute("allQuestion", all);
} catch (Exception ex) {
ex.printStackTrace();
request.setAttribute("allQuestion", null);
}
RequestDispatcher view = request.getRequestDispatcher("/allQuestion.jsp");
view.forward(request, response);
}
}
allQuestion.jsp
<%#page import="app.Answer"%>
<%#page import="app.Question"%>
<%#page import="java.util.List"%>
<html>
<body>
<%
List all = (List)request.getAttribute("allQuestion");
for (Object object : all) {
Question question = (Question)object;
out.print("<br>Question " + question.getId());
for (Answer answer : question.getAnswers()) {
out.print("<br>" + answer.getText() + "<br>");
}
}
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<filter>
<filter-name>HibernateFilter</filter-name>
<filter-class>app.HibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>getAllQuestion</servlet-name>
<servlet-class>app.GetAllQuestion</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getAllQuestion</servlet-name>
<url-pattern>/getAllQuestion</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getOneQuestion</servlet-name>
<servlet-class>app.GetOneQuestion</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getOneQuestion</servlet-name>
<url-pattern>/getOneQuestion</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Question
1) Why I need to call "session.beginTransaction()" method in servlets even if I already call "session.beginTransaction()" in filter? If I call one servler from another I also have to call this method in second servlet? Or I have to call this method before every interaction with database?
2) I don't call "sessionFactory.getCurrentSession().openSession()" or "sessionFactory.getCurrentSession().getCurrentSession()" in filter but I call "sessionFactory.getCurrentSession().getCurrentSession()" in servlet and still obtain session which seem to be create in filter. How this can be?
3) If I uncomment line "session.getTransaction().commit();" in GetOneQuestion class from jsp file I receive LazyInitializationException: "could not initialize proxy - no Session" even if there is no lazy load in this jsp file because I don't use any Answer object there. What cause this Exception? Session must be open for any interaction with Hibernate object even if there is no lazy load?

You need to configure a session factory one time (!) on the application startup, not in an every servlet.
You need to close session in the filter after a transaction commit.
You don't need create a transaction in the servlet (or you don't need create a transaction in the filter).
You can store a session factory in the static field of the application initializer class and get current session from it in servlets.
About your questions
Because you do a mistake. You create a new session factory in the servlet.
You obtain a new session (because of your incorrect session factory creation). In the normal situation getCurrentSession() return a session bound to the current thread by ThreadLocal(Not always, It depends of configuration).
You have LazyInitializationException with question.getAnswers().

Related

Cannot upload my Web Applicartion in Jboss7 EAP7 EAP

I must to test this web app, but when I try to deploy on JBoss 7 EAP this is the error, maybe I forgot something?
This is the exception that the application throws:
Cannot upload deployment: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL" =>
"org.jboss.msc.service.StartException in service jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL: WFLYSRV0153:
Failed to process phase INSTALL of deployment \"WebAppGuestbooks.war\" Caused by:
org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0041: Component class it.matteo.nesea.ejb.GuestDao for
component GuestDao has errors:
WFLYJPA0033: Can't find a persistence unit named null in deployment
\"WebAppGuestbooks.war\""},"WFLYCTL0180: Services with missing/unavailable dependencies" =>
["jboss.deployment.unit.\"WebAppGuestbooks.war\".weld.weldClassIntrospector is missing
[jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]","jboss.deployment.unit.\"WebAppGuestbooks.war\".batch.environment
is missing [jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]"]}
This is my persistence.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="GuestbookPU" transaction-type="JTA">
<class>it.matteo.nesea.dao.jpa</class>
<properties>
<property name="javax.persistence.jdbc.url" value="$objectdb/db/guests.odb"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
this is the Ejb GuestDAO:
package it.matteo.nesea.ejb;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import it.matteo.nesea.dao.jpa.Guest;
#Stateless
public class GuestDao {
// Injected database connection:
#PersistenceContext private EntityManager em;
// Stores a new guest:
public void persist(Guest guest) {
em.persist(guest);
}
// Retrieves all the guests:
public List<Guest> getAllGuests() {
TypedQuery<Guest> query = em.createQuery(
"SELECT g FROM Guest g ORDER BY g.id", Guest.class);
return query.getResultList();
}
}
this is Jpa POJO Class Guest:
package it.matteo.nesea.dao.jpa;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Guest implements Serializable {
private static final long serialVersionUID = 1L;
// Persistent Fields:
#Id
#GeneratedValue
Long id;
private String name;
private Date signingDate;
// Constructors:
public Guest() {
}
public Guest(String name) {
this.name = name;
this.signingDate = new Date(System.currentTimeMillis());
}
// String Representation:
#Override
public String toString() {
return name + " (signed on " + signingDate + ")";
}
}
This is a Servlet GuestServlet:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.matteo.nesea.dao.jpa.Guest;
import it.matteo.nesea.ejb.GuestDao;
#WebServlet(name="GuestServlet", urlPatterns={"/guest"})
public class GuestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Injected DAO EJB:
#EJB GuestDao guestDao;
#Override
protected void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Display the list of guests:
request.setAttribute("guests", guestDao.getAllGuests());
request.getRequestDispatcher("/guest.jsp").forward(request, response);
}
#Override
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle a new guest:
String name = request.getParameter("name");
if (name != null)
guestDao.persist(new Guest(name));
// Display the list of guests:
doGet(request, response);
}
}
This is a JSP Page:
<%#page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#page import="java.util.*,it.matteo.nesea.dao.jpa.Guest"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JPA Guest Book Web Application</title>
</head>
<body>
<form method="POST" action="guest">
Name: <input type="text" name="name" />
<input type="submit" value="Add" />
</form>
<hr><ol> <%
#SuppressWarnings("unchecked")
List<Guest> guests = (List<Guest>)request.getAttribute("guests");
if (guests != null) {
for (Guest guest : guests) { %>
<li> <%= guest %> </li> <%
}
} %>
</ol></hr>
</body>
This is the path of Project
Your persistence.xml file is in the wrong place. The JPA uses a convention to find your persistence.xml so you have put the file in the right place.
According to the Oracle docs:
The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit.
If you package the persistent unit as a set of classes in an EJB JAR file, persistence.xml should be put in the EJB JAR’s META-INF directory.
If you package the persistence unit as a set of classes in a WAR file, persistence.xml should be located in the WAR file’s WEB-INF/classes/META-INF directory.
In your case when the persistence.xml file is in src/META-INF/ (if you use MAVEN the path is src/resources/META-INF) its going to be packaged in your war in the WEB-INF/classes/META-INF folder, funcioning as the root of the persistence unit.

Got Exception in thread "main" org.hibernate.HibernateException: hibernate.cgf.xml not found while running hibernate application

My Hibernate Application needs to retrieve the data stored in MySQL database.But i was successful in saving data into DB, but failed in retrieving.
Error Log
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: hibernate.cgf.xml not found
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2035)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2016)
at mypack.DataInsertion.getInfo(DataInsertion.java:39)
at mypack.DataInsertion.main(DataInsertion.java:12)
hibernate.cfg.xml (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>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibdb</property>
<property name="connection.user">root</property>
<property name="connection.password">admin</property>
<!-- Related to the connection END -->
<!-- Related to the hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Related to the hibernate properties END -->
<!-- List of XML mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user.hbm.xml (Mapping file)
<?xml version="1.0"?> <!-- Mapping File to POJO Class -->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="mypack.DataProvider" table="user_info">
<id name="user_id" column="id">
<generator class="assigned"/>
</id>
<property name="user_name" column = "name" />
<property name="user_address" column = "address" />
</class>
</hibernate-mapping>
DataProvider.java (POJO Class)
package mypack; //POJO Class
public class DataProvider {
private int user_id;
private String user_name;
private String user_address;
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_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
}
DataInsertion.java (Implementation Logic)
package mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataInsertion {
public static void main(String[] args) {
//new DataInsertion().insertInfo();
new DataInsertion().getInfo();
}
public void insertInfo()
{
Configuration con = new Configuration(); //interation with hib
con.configure("hibernate.cfg.xml"); //registering to xml
SessionFactory SF = con.buildSessionFactory(); //creating session
Session session = SF.openSession(); //opening new session
DataProvider provider = new DataProvider();
provider.setUser_id(1);
provider.setUser_name("Goutham");
provider.setUser_address("Hunsur");
Transaction TR = session.beginTransaction();
session.save(provider);
System.out.println("Object saved successfully");
TR.commit(); //saving transaction
session.close();
SF.close();
}
public void getInfo()
{
Configuration con = new Configuration();
con.configure("hibernate.cgf.xml");
SessionFactory SF = con.buildSessionFactory();
Session session = SF.openSession();
Object obj = session.load(DataProvider.class,new Integer(1)); //We are binding data into obj from DataProvider class
DataProvider dp = (DataProvider) obj; //Typecasting into DataProvider
System.out.println("Name:"+dp.getUser_name());
System.out.println("Address:"+dp.getUser_address());
session.close();
SF.close();
}
}
Please Advise me,
Thanks.
you have wrong file name with typo hibernate.cgf.xml should be hibernate.cfg.xml
You have given wrong name hibernate.cgf.xml in getInfo method. That is why you are facing issue

Working with Hibernate 3 and Struts 2. The cgf file is not getting read. Is it because of the JARS?

This is my `DAO
package com.sheeba;
import com.sheeba.LeavePojo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
public class LeaveDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction trans;
List<LeavePojo> myList = new ArrayList<LeavePojo>();
// LeavePojo pojoObj=new LeavePojo();
public String saveToDb(LeavePojo pojoObj) {
try {
System.out.println("inside saveToDb method-before query");
System.out.println("bank id" + pojoObj.getBank_id());
// Serializable isSaved =session.save(pojoObj);
System.out.println("session" + session);
session.saveOrUpdate(pojoObj);
// System.out.println("llllllllllllllllllllllll"+session.save(pojoObj).getClass().getName());
} catch (Exception e) {
e.printStackTrace();
}
return "SUCCESS";
}
public List<LeavePojo> retrieveData() {
myList = session.createQuery("from LeavePojo").list();
return myList;
}
/*public String fetchBankId()
{
try{
System.out.println("inside fetch bank id -- before query");
String hql = "SELECT l.bank_id FROM LeavePojo l";
Query query = session.createQuery(hql);
System.out.println("deeeeeeeeeeeeeeeeeeeeeee"+query.list());
List results = query.list();
System.out.println("RESSSSSSSSSSSUUUUUUUUUUUUUULLLLLLLLLTttasssss"+results);
}catch (Exception e) {
e.printStackTrace();
}
return"success";
}*/}
service
package com.sheeba;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sheeba.*;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
#ParentPackage("hibernate-default")
#InterceptorRef("basicStackHibernate")
public class LeaveService implements ModelDriven {
LeavePojo modobj = new LeavePojo();
LeaveDAO leaveDAO=new LeaveDAO();
//private LeaveDAO leaveDAO; // this is the dependency injection
public LeaveDAO getLeaveDAO() {
return leaveDAO;
}
public void setLeaveDAO(LeaveDAO leaveDAO) {
this.leaveDAO = leaveDAO;
}
public List<LeavePojo> myList = new ArrayList<LeavePojo>();
public List<LeavePojo> getMyList() {
return myList;
}
public void setMyList(List<LeavePojo> myList) {
this.myList = myList;
}
public List<LeavePojo> saveDetailsService(LeavePojo modobj) {
System.out.println("inside savedetails service");
leaveDAO.saveToDb(modobj);
myList = leaveDAO.retrieveData();
return myList;
}
#Override
public Object getModel() {
return modobj;
}
}
This is action
package com.sheeba;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class LeaveAction extends ActionSupport implements ModelDriven<LeavePojo> {
LeaveService ls=new LeaveService();
LeavePojo pojo =new LeavePojo();
public List<LeavePojo> myList = new ArrayList<LeavePojo>();
public List<LeavePojo> getMyList() {
return myList;
}
public void setMyList(List<LeavePojo> myList) {
this.myList = myList;
}
private String bank_id;
private String emp_name;
private String leaves_applied;
public String getBank_id() {
return bank_id;
}
public void setBank_id(String bank_id) {
this.bank_id = bank_id;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
public String getLeaves_applied() {
return leaves_applied;
}
public void setLeaves_applied(String leaves_applied) {
this.leaves_applied = leaves_applied;
}
public String getServiceLasyer(){
try{
System.out.println(pojo.getBank_id()+"is bank id");
myList=ls.saveDetailsService(pojo);
}catch(Exception e){
e.printStackTrace();
}
return SUCCESS;
}
#Override
public LeavePojo getModel() {
// TODO Auto-generated method stub
return pojo;
}
}
Have used these jars here /AAAAANEWPROJECT/WebContent/WEB-INF/lib/hibernate3.jar
/AAAAANEWPROJECT/WebContent/WEB-INF/lib/hibernate-annotations-3.2.1.ga.jar
/AAAAANEWPROJECT/WebContent/WEB-INF/lib/hibernate-core.jar
/AAAAANEWPROJECT/WebContent/WEB-INF/lib/struts2-fullhibernatecore-plugin-2.2.2-GA.jar. for hibernate.
struts:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="false" />
<package name="default" extends="struts-default,hibernate-default">
<action name="saveAction" class="com.sheeba.LeaveAction" method="getServiceLasyer">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
hib.config
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://10.112.178.78:1433;databaseName=Test_DB</property>
<property name="hibernate.connection.username">TestUser1</property>
<property name="connection.password">Test123</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="show_sql">true</property>
<mapping resource="LeavePojo.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hib.mapping:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping SYSTEM
"hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.sheeba.LeavePojo" table="LeavePojo">
<id name="bank_id" type="string" column="BANK_ID">
</id>
<property name="emp_name" column="EMP_NAME" type="string" />
<property name="leaves_applied" column="LEAVES_APPLIED" type="string" />
</class>
</hibernate-mapping>
I am not able to get the output. 404 error comes. Is there any problem with the jar?
I got it resolved! I downloaded from the sourceforge DTD and added it to my root directory which is SRC folder.
And, edited the hibernate.cfg.xml to be as below:
<!DOCTYPE hibernate-configuration SYSTEM
"hibernate-configuration-3.0.dtd">
by this way the application doesnt have to hit the URL but it points and finds the DTD in the src folder. this you can do when you are using your system online.
IT worked for me after hell a lot of researches!!

App gives 404 error on Tomcat when compiled in MySQL with Struts 2 and Hibernate on Eclipse

I am attempting to run a simple Struts app that presents fields for the user to enter which OS type and version they use with an optional field for notes. It will then present the results on a new page as an indexed list. It would be analogous to any basic contact organizer app but for listing OS info.
However, the IDE shows no errors at all. I think I am not connecting to the db correctly. This is the step I was most unsure of when setting up as well. Since there are specific frameworks, tools and such I am using, I was unable to find a tutorial that pertained specifically to setting up a db in my environment(not sure if there is a diff or if there is a universal approach).
Since this is the first app I have ever built in Java, my troubleshooting ability is pretty limited but I am giving it all I got! It is a big jump (for me) coming from Rails/JS and so a bit of guidance from you Jedis to a Padawan like me will go a long way. Anyway, since it can be tricky to jump into a Java code base(in my opinion), I'll be as precise as possible but feel free to drop me a line for elaboration, need to view a specific file, or if you just want a war file of my project to check it out in your own dev. environment (if that would be helpful).
I have everything installed and working, although JDBC is confusing to me. Is it something you install manually or you call it in your code as a dependency? When I try to compile and run using Tomcat 7, There are a few errors that basically say the same thing as the snippet below points out :
SEVERE: Dispatcher initialization failed
Unable to load configuration. - action - file:/Users/jasonrodriguez/Java/apache-tomcat-7.0.47/wtpwebapps/firstapp/WEB-INF/classes/struts.xml:14:74
at different points in the code base. So perhaps they are all connected to the same problem.
File Structure:
This is my hibernate.cfg.xml :
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 4.3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-4.3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/UserManager
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="net.jasonrodriguez.user.model.User" />
</session-factory>
This is my struts.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" extends="struts-default" namespace="/">
<action name="add"
class="net.jasonrodriguez.user.view.UserAction" method="add">
<result name="success" type="chain">index</result>
<result name="input" type="chain">index</result>
</action>
<action name="delete"
class="net.jasonrodriguez.user.view.UserAction" method="delete">
<result name="success" type="chain">index</result>
</action>
<action name="index"
class="net.jasonrodriguez.user.view.UserAction">
<result name="success">index.jsp</result>
</action>
</package>
</struts>
Here is my web.xml filter for Struts :
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Here is my controller :
package net.jasonrodriguez.user.controller;
import java.util.List;
import net.jasonrodriguez.user.model.User;
import net.jasonrodriguez.user.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
public class UserManager extends HibernateUtil {
public User add(User user) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
return user;
}
public User delete(Long id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User user = (User) session.load(User.class, id);
if(null != user) {
session.delete(user);
}
session.getTransaction().commit();
return user;
}
public List<User> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<User> users = null;
try {
users = (List<User>)session.createQuery("from User").list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return users;
}
}
This is my HibernateUtil.java :
package net.jasonrodriguez.user.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Here is my view action :
package net.jasonrodriguez.user.view;
import java.util.List;
import net.jasonrodriguez.user.controller.UserManager;
import net.jasonrodriguez.user.model.User;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 9149826260758390091L;
private User user;
private List<User> userList;
private Long id;
private UserManager userManager;
public UserAction() {
userManager = new UserManager();
}
public String execute() {
this.userList = userManager.list();
System.out.println("execute called");
return SUCCESS;
}
public String add() {
System.out.println(getUser());
try {
userManager.add(getUser());
} catch (Exception e) {
e.printStackTrace();
}
this.userList = userManager.list();
return SUCCESS;
}
public String delete() {
userManager.delete(getId());
return SUCCESS;
}
public User getUser() {
return user;
}
public List<User> getUserList() {
return userList;
}
public void setUser(User user) {
this.user = user;
}
public void setUserList(List<User> usersList) {
this.userList = usersList;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
When Tomcat is deployed, it gives me a web page with a 404 error saying it cannot locate the resource.
Change the filter class in web.xml to org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter. The FilderDispatcher is deprecated and as you using 2.3 DTD it should correspond to libraries.

Servlet threw java.lang.NullPointerException

I am using netbeans 7.4 with hibernate 3.6.10 to develop a web application.
I have surfed the net and read quite a number of site, I believe the error is caused by wrong configuration between hibernate and my servlet. As I am new to jsp, servlet and hibernate, I cannot figure out what have I did wrongly. Hope you guys can solve this problem.
Here comes the code.
hibernate.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>
<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/webasgdvd?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<mapping class="cart.hibernate.PaymentMethod" package="cart.hibernate" resource="cart/hibernate/PaymentMethod.hbm.xml"/>
</session-factory>
</hibernate-configuration>
PaymentMethod.java
package cart.hibernate;
public class PaymentMethod {
private int paymentMethodId;
private String paymentMethod;
public PaymentMethod(){
}
public PaymentMethod(String method){
this.paymentMethod = method;
}
public int getPaymentMethodId() {
return paymentMethodId;
}
public String getPaymentMethod(){
return paymentMethod;
}
public void setPaymentMethodId(int id) {
this.paymentMethodId = id;
}
public void setPaymentMethod(String method){
this.paymentMethod = method;
}
}
PaymentMethod.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cart.hibernate.PaymentMethod" table="payment_method">
<meta attribute="class-description">
This class contains the payment method detail.
</meta>
<id name="paymentMethodId" type="int" column="payment_method_id">
<generator class="native"/>
</id>
<property name="PaymentMethod" column="payment_method" type="string"/>
</class>
</hibernate-mapping>
ManagePaymentMethod.java
package cart.hibernate;
import java.util.List;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManagePaymentMethod {
private static SessionFactory factory;
public Integer addPaymentMethod(String methodName) {
Session session = factory.openSession(); // Error occur here <--
Transaction tx = null;
Integer paymentMethodId = null;
try {
tx = session.beginTransaction();
PaymentMethod payMethod = new PaymentMethod(methodName);
paymentMethodId = (Integer) session.save(payMethod);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return paymentMethodId;
}
}
addPaymentMethodServlet.java
package cart.hibernate;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class addPaymentMethodServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String method = request.getParameter("paymentMethod");
try {
ManagePaymentMethod manager = new ManagePaymentMethod();
Integer paymentMethodId = manager.addPaymentMethod(method);
// Receive from a jsp page and I have checked the value of method is correct
out.print("..."); // html page
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
When the servlet is called, exception is caught. The following is the error log
Nov 22, 2013 6:55:22 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [addPaymentMethodServlet] in context with path [/eShop] threw exception
java.lang.NullPointerException
at cart.hibernate.ManagePaymentMethod.addPaymentMethod(ManagePaymentMethod.java:93)
at cart.hibernate.addPaymentMethodServlet.processRequest(addPaymentMethodServlet.java:46)
at cart.hibernate.addPaymentMethodServlet.doPost(addPaymentMethodServlet.java:90)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
I have tested the addPaymentMethod() by executing a main() method in the ManagePaymentMethod.java. The addPaymentMethod() run correctly.
Moreover, the value that passed from jsp to addPaymentMethodServlet.java is correct.
If you have more details, please let me know.
in the line
Session session = factory.openSession();
facotory is null
You declared
private static SessionFactory factory;
And never initialized and using in addPaymentMethod method.

Categories