hi all,
I want to register the employee.
in employee registration form i am having field Role where rolename from database should be displayed.
The id of the role should be stored in employee table.
I am getting this error
org.hibernate.PropertyValueException: not-null property references a null or transient value: com.vc_inloop.hibernate.beans.Employee.role
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:72)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:265)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:167)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:114)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:530)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:518)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:514)
at com.vc_inloop.hibernate.dao.EmployeeDAO.addEmployee(EmployeeDAO.java:82)
at com.vc_inloop.struts.action.EmployeeAction.execute(EmployeeAction.java:37)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:210)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:870)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:685)
at java.lang.Thread.run(Unknown Source)
please help me
thank u in advance.....
//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 package="com.vc_inloop.hibernate.beans">
<class name="Employee" table="employee">
<id name="userid" column="UserId" type="int">
<generator class="increment"></generator>
</id>
<property name="employeename" column="EmployeeName" type="string"></property>
<property name="designation" column="Designation" type="string"></property>
<property name="location" column="Location" type="string"></property>
<property name="employeemobile" column="EmployeeMobile" type="long"></property>
<property name="employeetelo" column="EmployeeTelO" type="long"></property>
<property name="employeetelh" column="EmployeeTelH" type="long"></property>
<property name="employeeemail" column="EmployeeEMail" type="string"></property>
<property name="password" column="Pass" type="string"></property>
<many-to-one name="role" class="Role"
column="RoleId"
unique="true"
not-null="true"/>
</class>
</hibernate-mapping>
//Role.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.vc_inloop.hibernate.beans.Role" table="role">
<id name="roleid" column="RoleId" type="int">
<generator class="increment"></generator>
</id>
<property name="rolename" column="RoleName" type="string"></property>
</class>
</hibernate-mapping>
//AdminEmployeeRegistration.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Employee Registration</title>
<link href="<%= request.getContextPath() %>/css/bookstyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="login" class="boxed">
<h2 class="title" align="center">Employee Registration</h2>
<h2 class="title">Note:<font color="#FF0000">* Mandatory field</font></h2>
</div>
<hr />
<div id="content">
<form action="<%= request.getContextPath() %>/employeeRegister.do" name="Empform" method="get">
<fieldset><legend style="text-align:left">Details</legend>
<table width="100%" border="0" align="center">
<tr>
<td width="17%"><label for="inputtext1"><b>Employee Name<font color="#FF0000">*</font>:</b></label></td>
<td width="34%"><input id="inputtext3" type="text" name="EmployeeName" size="32" value="" /></td>
</tr>
<tr>
<td width="17%"><label for="inputtext1"><b>Designation<font color="#FF0000">*</font>:</b></label></td>
<td width="34%"><select name="EmployeeDesig"><option value="-">Select Designation</option>
<option value="D1">Designation 1</option>
<option value="D2">Designation 2</option>
<option value="D3">Designation 3</option>
</select>
</td>
<td width="17%"><label for="inputtext1"><b>Role<font color="#FF0000">*</font>:</b></label></td>
<td width="34%"><select name="EmployeeRole"><option value="-">Select Role</option>
<option value="1">Admin</option>
<option value="2">Project Manager</option>
<option value="3">Finance Manager</option>
<option value="4">Senior Manager</option>
<option value="5">Indian Head of Operation</option>
<option value="6">Finance Executive</option>
</select></td>
</tr>
<tr>
<td width="17%"><label for="inputtext1"><b>Location<font color="#FF0000">*</font>:</b></label></td>
<td width="34%"><select name="EmployeeCountry"><option value="-">Others</option>
<option value="AU">Australia</option>
<option value="CA">Canada</option>
<option value="CH">China</option>
<option value="IN" selected="selected">India</option>
<option value="SI">Singapore</option>
<option value="TH">Thailand</option>
<option value="UK">United Kingdom</option>
<option value="US">United States</option>
</select> </td>
<td width="17%"><label for="inputtext1"><b>Password<font color="#FF0000">*</font>:</b></label></td>
<td width="34%"><input id="inputtext3" type="text" name="EmployeePassword" size="32" value="" /></td>
</tr>
</table>
</fieldset>
<fieldset><legend style="text-align:left">Contact</legend>
<table width="100%" border="0" align="center">
<tr>
<td width="17%"><label for="inputtext1"><b>Mobile:</b></label> </td>
<td width="34%"><input id="inputtext3" type="text" name="Employeemobile" value="" size="32"/></td>
<td width="17%"><label for="inputtext1"><b>E-mail<font color="#FF0000">*</font>:</b></label> </td>
<td width="32%"><input id="inputtext3" type="text" name="EmployeeEmail" value="" size="32"/></td>
</tr>
<tr>
<td width="17%"><label for="inputtext1"><b>Telephone(Off)<font color="#FF0000">*</font>:</b></label> </td>
<td width="34%"><input id="inputtext3" type="text" name="EmployeeTelephone1" value="" size="32"/></td>
<td width="17%"><label for="inputtext1"><b>Telephone(Home):</b></label> </td>
<td width="32%"><input id="inputtext3" type="text" name="EmployeeTelephone2" value="" size="32"/></td>
</tr>
</table>
</fieldset>
<br />
<table width="50%" border="0" align="center">
<tr align="left">
<td width="40%"> </td>
<td width="60%"><input id="inputsubmit1" type="submit" name="Submit" value="Submit" />
<input id="inputsubmit1" type="submit" name="Clear" value="Clear" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
//EmployeeAction.java
package com.vc_inloop.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.vc_inloop.hibernate.beans.Employee;
import com.vc_inloop.hibernate.beans.Role;
import com.vc_inloop.hibernate.dao.EmployeeDAO;
import com.vc_inloop.hibernate.dao.RoleDAO;
public class EmployeeAction extends Action {
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)throws Exception{
Role r=RoleDAO.findById();
String str=null;
Employee emp = new Employee();
emp.setEmployeename(request.getParameter("EmployeeName"));
emp.setDesignation(request.getParameter("EmployeeDesig"));
emp.setRole(r);
emp.setLocation(request.getParameter("EmployeeCountry"));
emp.setEmployeemobile(Long.parseLong(request.getParameter("Employeemobile")));
emp.setEmployeeemail(request.getParameter("EmployeeEmail"));
emp.setEmployeetelo(Long.parseLong(request.getParameter("EmployeeTelephone1")));
emp.setEmployeetelh(Long.parseLong(request.getParameter("EmployeeTelephone2")));
emp.setPassword(request.getParameter("EmployeePassword"));
EmployeeDAO ed=new EmployeeDAO();
try{
if(ed.addEmployee(emp)){
System.out.println("Enter to employee");
str="Registered";
}
}catch(Exception e){e.printStackTrace();}
return mapping.findForward(str);
}
}
//RoleDAO.java
package com.vc_inloop.hibernate.dao;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import com.vc_inloop.hibernate.beans.Employee;
import com.vc_inloop.hibernate.beans.Role;
import com.vc_inloop.hibernate.plugin.HibernateUtil;
public class RoleDAO {
static List data_list = getData();
static SessionFactory sf = null;
static Role r = null;
static Session session = null;
public static List getData() {
List result = null;
Transaction tx = null;
try {
SessionFactory sf = HibernateUtil.createSessionFactory();
Session session = sf.openSession();
tx = session.beginTransaction();
result = session.createQuery("from Employee").list();
tx.commit();
session.close();
} catch (HibernateException e) {
e.printStackTrace();
tx.commit();
}
return result;
}
public static boolean setEmployee(Employee emp) {
Transaction tx = null;
try {
SessionFactory sf = HibernateUtil.createSessionFactory();
Session session = sf.openSession();
tx = session.beginTransaction();
tx.commit();
session.close();
return true;
} catch (HibernateException e) {
e.printStackTrace();
tx.rollback();
}
return false;
}
public static Role findById(){
try{
int roleid = 0;
sf = HibernateUtil.createSessionFactory();
System.out.println(":"+sf);
session = sf.openSession();
System.out.println(session);
// verifying of user
Query query = session
.createQuery("from Role r where r.roleid=?");
query.setParameter(0, roleid);
if (query.list().size()!= 0) {
// query.list() this gets bunch of data from DB and return in
// list form
// get(0) it returns first element of that list
r = (Role) query.list().get(0);
}
System.out.println(query.list());
} catch (HibernateException e) {
e.printStackTrace();
}finally{
if(null!= session)session.close();
}
return r;
}
/*public static boolean findById(Role role){
Transaction tx=null;
try{
SessionFactory sf= (SessionFactory) HibernateUtil.getSession();
Session session = sf.openSession();
tx=session.getTransaction();
tx.commit();
session.close();
return true;
}catch (HibernateException e){
e.printStackTrace();
}
return false;
}*/
}
//Employee.java
package com.vc_inloop.hibernate.beans;
public class Role{
/**
*
*/
private static final long serialVersionUID = 1L;
public int roleid;
private String rolename=null;
public Role( String rolename) {
this.rolename = rolename;
}
public Role(int roleid, String rolename) {
this.roleid = roleid;
this.rolename = rolename;
}
public Role() {
}
public int getRoleid() {
return roleid;
}
public void setRoleid(int roleid) {
this.roleid = roleid;
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
}
//HibernateUtil.java
package com.vc_inloop.hibernate.plugin;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory createSessionFactory() {
System.out.println("SEssion factory creation");
return sessionFactory = new Configuration().configure().buildSessionFactory();
}
public static Session getSession() {
return sessionFactory.openSession();
}
}
/*import javax.naming.InitialContext;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
*//**
* @author hennebrueder This class garanties that only one single SessionFactory
* is instanciated and that the configuration is done thread safe as
* singleton. Actually it only wraps the Hibernate SessionFactory.
* When a JNDI name is configured the session is bound to to JNDI,
* else it is only saved locally.
* You are free to use any kind of JTA or Thread transactionFactories.
*//*
public class InitSessionFactory {
public static void main(String args[]){
getSessionFactory();
}
*//**
* Default constructor.
*//*
public static SessionFactory getSessionFactory(){
Configuration cfg=new Configuration();
cfg=cfg.configure();
return cfg.buildSessionFactory();
}
private InitSessionFactory() {
}
*//**
* Location of hibernate.cfg.xml file. NOTICE: Location should be on the
* classpath as Hibernate uses #resourceAsStream style lookup for its
* configuration file. That is place the config file in a Java package - the
* default location is the default Java package.<br>
* <br>
* Examples: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
*//*
private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
*//** The single instance of hibernate configuration *//*
private static final Configuration cfg = new Configuration();
*//** The single instance of hibernate SessionFactory *//*
private static org.hibernate.SessionFactory sessionFactory;
*//**
* initialises the configuration if not yet done and returns the current
* instance
*
* @return
*//*
public static SessionFactory getInstance() {
if (sessionFactory == null)
initSessionFactory();
return sessionFactory;
}
*//**
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*//*
public Session openSession() {
return sessionFactory.getCurrentSession();
}
*//**
* The behaviour of this method depends on the session context you have
* configured. This factory is intended to be used with a hibernate.cfg.xml
* including the following property <property
* name="current_session_context_class">thread</property> This would return
* the current open session or if this does not exist, will create a new
* session
*
* @return
*//*
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
*//**
* initializes the sessionfactory in a safe way even if more than one thread
* tries to build a sessionFactory
*//*
private static synchronized void initSessionFactory() {
* [laliluna] check again for null because sessionFactory may have been
* initialized between the last check and now
*
Logger log = Logger.getLogger(InitSessionFactory.class);
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
String sessionFactoryJndiName = cfg
.getProperty(Environment.SESSION_FACTORY_NAME);
if (sessionFactoryJndiName != null) {
cfg.buildSessionFactory();
log.debug("get a jndi session factory");
sessionFactory = (SessionFactory) (new InitialContext())
.lookup(sessionFactoryJndiName);
} else{
log.debug("classic factory");
sessionFactory = cfg.buildSessionFactory();
}
} catch (Exception e) {
System.err
.println("%%%% Error Creating HibernateSessionFactory %%%%");
e.printStackTrace();
throw new HibernateException(
"Could not initialize the Hibernate configuration");
}
}
}
public static void close(){
if (sessionFactory != null)
sessionFactory.close();
sessionFactory = null;
}
*/
/*import java.net.URL;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernatePlugin {
private Configuration config;
private static SessionFactory factory;
private String path = "/hibernate.cfg.xml";
private static Class clazz = HibernatePlugin.class;
public static final String KEY_NAME = clazz.getName();
private static Log log = LogFactory.getLog(clazz);
public void setPath(String path) {
this.path = path;
}
public void init(ActionServlet servlet, ModuleConfig modConfig)
throws ServletException {
try {
URL url = HibernatePlugin.class.getResource(path);
config = new Configuration().configure(url);
factory = config.buildSessionFactory();
servlet.getServletContext().setAttribute(KEY_NAME, factory);
} catch (MappingException e) {
log.error("mapping error", e);
throw new ServletException();
} catch (HibernateException e) {
log.error("hibernate error", e);
throw new ServletException();
}
}
public void destroy() {
try {
factory.close();
} catch (HibernateException e) {
log.error("unable to close factory", e);
}
}
public static SessionFactory getSessionFactory() {
System.out.println("SESSION FACTOTY:enter");
SessionFactory s;
s=((HibernatePlugin) factory).getSessionFactory();
factory
System.out.println("SESSION FACTOTY:"+s);
return s;
}
}*/
//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>
<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/inloop
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping resource="com/vc_inloop/hibernate/hbm/Employee.hbm.xml" />
<mapping resource="com/vc_inloop/hibernate/hbm/Role.hbm.xml" />
<mapping resource="com/vc_inloop/hibernate/hbm/Client.hbm.xml" />
<mapping resource="com/vc_inloop/hibernate/hbm/Country.hbm.xml" />
<mapping resource="com/vc_inloop/hibernate/hbm/Currency.hbm.xml" />
</session-factory>
</hibernate-configuration>
|