Saving values to mysql using struts2 - java

I am new to struts and was trying to save some values to DB (mysql) from jsp page using struts and hibernate.
But, the application is saving null value every time and auto increment ID is increasing.
My Database structure. :
Table Name | osdetail
-------------------------
Columns | os_name,
| os_version,
| id,
| created,
| notes.
The index.jsp page
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
    <title>OS Manager - Struts2 Hibernate Example</title>
</head>
<body>
 
<h1>OS Manager</h1>
<s:actionerror/>
 
<s:form action="add" method="post">
    <s:textfield name="osdetail.OSname" label="name"/>
    <s:textfield name="osdetail.OSversion" label="version"/>
    <s:textfield name="osdetail.OSnotes" label="notes"/>
    <s:submit value="Add OS Details" align="center"/>
</s:form>
 
 
<h2>OS Details</h2>
<table>
<tr>
    <th>OS Name</th>
    <th>OS Version</th>
    <th>OS Notes</th>
</tr>
<s:iterator value="osdetails_list" var="osdetail">
    <tr>
        <td><s:property value="OSname"/></td>
        <td><s:property value="OSversion"/></td>
        <td><s:property value="OSnotes"/></td>
    </tr>
</s:iterator>
</table>
</body>
</html>
My View : OSAction.java
package net.ajeet.os.view;
import java.util.List;
import net.ajeet.os.controller.OSManager;
import net.ajeet.os.model.OSDetail;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class OSAction extends ActionSupport implements ModelDriven<OSDetail> {
private static final long serialVersionUID = 9149826260758390091L;
private OSDetail osdetail= new OSDetail();
private List<OSDetail> osdetails_list;
private Long id;
private OSManager linkController= new OSManager();
#Override
public OSDetail getModel() {
return osdetail;
}
public OSAction() {
linkController = new OSManager();
}
public String execute() {
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String add() {
System.out.println("this is oS detail get ID"+osdetail.getId());
try {
//linkController.add(getOSDetail());
linkController.add(osdetail);
System.out.println("this is oS detail after add "+getOSDetail());
} catch (Exception e) {
e.printStackTrace();
}
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String delete() {
linkController.delete(getId());
return SUCCESS;
}
public OSDetail getOSDetail() {
return osdetail;
}
public List<OSDetail> getOSDetail_list() {
return osdetails_list;
}
public void setOSDetail(OSDetail osdetail) {
this.osdetail = osdetail;
}
public void setOSDetail_list(List<OSDetail> osdetails_list) {
this.osdetails_list = osdetails_list;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
My Model: OSDetail.java
package net.ajeet.os.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="osdetail")
public class OSDetail implements Serializable{
private static final long serialVersionUID = -8767337896773261247L;
private Long OSid;
private String OSname;
private String OSversion;
private String OSnotes;
private Date OScreated;
#Id
#GeneratedValue
#Column(name="id")
public Long getId() {
System.out.println("set os name is os id"+OSid);
return OSid;
}
#Column(name="os_name")
public String getOS_name() {
return OSname;
}
#Column(name="os_version")
public String getOS_version() {
return OSversion;
}
#Column(name="notes")
public String getNotes() {
return OSnotes;
}
#Column(name="created")
public Date getCreated() {
return OScreated;
}
public void setId(Long OSid) {
this.OSid = OSid;
}
public void setOS_name(String OSname) {
this.OSname = OSname;
}
public void setOS_version(String OSversion) {
this.OSversion = OSversion;
}
public void setNotes(String OSnotes) {
this.OSnotes = OSnotes;
}
public void setCreated(Date OScreated) {
this.OScreated = OScreated;
}
My Contoller :OSManager.java
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;
import net.ajeet.os.model.OSDetail;
import net.ajeet.os.util.HibernateUtil;
public class OSManager extends HibernateUtil {
public OSDetail add(OSDetail osdetail) {
System.out.println("value of the os in OSManager"+osdetail.getId());
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(osdetail);
session.getTransaction().commit();
return osdetail;
}
public OSDetail delete(Long id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
OSDetail osdetail = (OSDetail) session.load(OSDetail.class, id);
if(null != osdetail) {
session.delete(osdetail);
}
session.getTransaction().commit();
return osdetail;
}
#SuppressWarnings("unchecked")
public List<OSDetail> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<OSDetail> osdetails_list = null;
try {
osdetails_list = (List<OSDetail>)session.createQuery("from OSDetail").list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return osdetails_list;
}
}
The values saved in DB are always null...except the ID..Please help
Changed the Action...updated getter/setter
package net.ajeet.os.view;
import java.util.List;
import net.ajeet.os.controller.OSManager;
import net.ajeet.os.model.OSDetail;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class OSAction extends ActionSupport {
private static final long serialVersionUID = 9149826260758390091L;
public OSDetail osdetail= new OSDetail();
private List<OSDetail> osdetails_list;
public OSDetail getOsdetail() {
return osdetail;
}
public void setOsdetail(OSDetail osdetail) {
this.osdetail = osdetail;
}
private Long id;
private OSManager linkController= new OSManager();
/* #Override
public OSDetail getModel() {
return osdetail;
}*/
public OSAction() {
linkController = new OSManager();
}
public String execute() {
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String add() {
try {
linkController.add(getOsdetail());
//linkController.add(osdetail);
} catch (Exception e) {
e.printStackTrace();
}
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String delete() {
linkController.delete(getid());
return SUCCESS;
}
public List<OSDetail> getOsdetails_list() {
return osdetails_list;
}
public void setOsdetails_list(List<OSDetail> osdetails_list) {
this.osdetails_list = osdetails_list;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
}
Corrected OSDetail.java, automatically created getter/setter.
package net.ajeet.os.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="osdetail")
public class OSDetail implements Serializable{
private static final long serialVersionUID = -8767337896773261247L;
private Long OSid;
private String OSname;
private String OSversion;
private String OSnotes;
private Date OScreated;
#Id
#GeneratedValue
#Column(name="id")
public Long getOSid() {
return OSid;
}
public void setOSid(Long oSid) {
OSid = oSid;
}
#Column(name="os_name")
public String getOSname() {
return OSname;
}
public void setOSname(String oSname) {
OSname = oSname;
}
#Column(name="os_version")
public String getOSversion() {
return OSversion;
}
public void setOSversion(String oSversion) {
OSversion = oSversion;
System.out.println("value of the os in OSversion in setter"+OSversion);
}
#Column(name="notes")
public String getOSnotes() {
return OSnotes;
}
public void setOSnotes(String oSnotes) {
OSnotes = oSnotes;
}
#Column(name="created")
public Date getOScreated() {
return OScreated;
}
public void setOScreated(Date oScreated) {
OScreated = oScreated;
}
}
Adding struts.xml to
<?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.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" extends="struts-default" namespace="/">
<action name="add"
class="net.ajeet.os.view.OSAction" method="add">
<result name="success" type="chain">index</result>
<result name="input" type="chain">index</result>
</action>
<action name="index"
class="net.ajeet.os.view.OSAction">
<result name="success">index.jsp</result>
</action>
</package>
</struts>
And 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/test
</property>
<property name="connection.username">root</property>
<property name="connection.password">Asmita24</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</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.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">update</property>
<mapping class="net.ajeet.os.model.OSDetail" />
</session-factory>
</hibernate-configuration>

Your getter function is wrongly named for the variable osdetail. It should be getOsdetail() instead of getOSDetail(). That is the reason your values from the form are not set and the variable osdetail has blank values. Try changing it. Same goes for the setter method, it should be setOsdetail(). Also, to prevent making such mistake in fututre, you can generate your getter and setter functions automatically from eclipse instead of manually creating it.

I don't see anywhere in your OSAction the code to read the values from the jsp. And that is the reason why I think the values are going in as null in the DB.
I suppose it'll work if you get the details from the jsp and set it to osdetail before calling linkController.add(osdetail);.
I am not too well versed with ActionSupport but I think you can read the values from the jsp using getText() method...
Try adding these lines before linkController.add(osdetail); line...
osdetail.setOS_name(getText("osdetail.OSname"));
osdetail.setOS_version(getText("osdetail.OSversion"));
osdetail.setNotes(getText("osdetail.OSnotes"));

Related

Enity is not mapped - hibernate

I'm trying to create a small project with hibernate, but i got that error "Type is not mapped [select o from Type o]", I added mapping in hibernate.cfg.xml but still error.
Type.java:
package com.formation.gestionprojet.doa.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Type")
public class Type implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private Long id;
private String name;
private String description;
private String active;
public Type() {
super();
// TODO Auto-generated constructor stub
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
}
hibernate.org.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 setting -->
<property name ="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/gestion_projet?createDatabaseIfNotExist=true</property>
<property name="connection.username">root</property>
<property name= "connection.password">root</property>
<!-- Dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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>
<!-- Drope and re-create the database -->
<property name="hbm2ddl.auto">update</property>
<!-- mapping -->
<mapping class= "com.formation.gestionprojet.doa.entity.Type"/>
</session-factory>
</hibernate-configuration>
hibernateUtil.java:
package com.formation.gestionprojet.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
#SuppressWarnings("deprecation")
public class HibernateUtil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static
{
try
{
Configuration configuration = new Configuration();
configuration.configure("config/hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (HibernateException ex)
{
System.err.println("Error creating Session: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static Session openSession()
{
return sessionFactory.openSession();
}
public static Session getCurrentSession()
{
return sessionFactory.getCurrentSession();
}
public static void close(){
if(sessionFactory!=null){
sessionFactory.close();
}
}
}
Test.Java
package com.formation.gestionprojet.utils;
import org.hibernate.Session;
public class Test {
static Session session = HibernateUtil.openSession();
public static void main(String[] args) {
session.createQuery("select o from Type o").list();
}
}
First things first, Type is part of the JPA/Hibernate API. So consider renaming it, e.g. MyType or something similar.
Secondly, select is not mandatory in HQL. So you can simply et everything with only FROM clause.
Thirdly, try using fully qualified name of the class in the query.
"FROM com.formation.gestionprojet.doa.entity.MyType"

Hibernate - org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not mapped

I get this error while trying to make test query for my Database. I refer to the java class instead of table name but it doesn't help. Added mapping to cfg.xml too but without success. What can be the cause?
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"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/michal
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<property name="hibernate.hbm2ddl.auto">
</property>
<!-- List of XML mapping files -->
<mapping package="regularmikey.DatabaseSingleton"/>
<mapping class="regularmikey.DatabaseSingleton.Product" />
</session-factory>
</hibernate-configuration>
Product.java
package regularmikey.DatabaseSingleton;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "product")
public class Product {
#Column(name = "id")
#Id #GeneratedValue
private String id;
#Column(name = "name")
private String name;
#Column(name = "alloy")
private String alloy;
#Column(name = "weight")
private String weight;
#Column(name = "min_temp")
private String min_temp;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlloy() {
return alloy;
}
public void setAlloy(String alloy) {
this.alloy = alloy;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getMin_temp() {
return min_temp;
}
public void setMin_temp(String min_temp) {
this.min_temp = min_temp;
}
}
DBSession.java
package regularmikey.DatabaseSingleton;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class DBSession {
private static DBSession dbSession = null;
private SessionFactory sessionFactory = null;
private DBSession(){
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = (configuration.buildSessionFactory(serviceRegistry));
};
public static DBSession getInstance()
{
if(dbSession == null) {
dbSession = new DBSession();
}
return dbSession;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
}
App.java
package regularmikey.DatabaseSingleton;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class App
{
public static void main( String[] args )
{
DBSession dbFactory = DBSession.getInstance();
Session session = dbFactory.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List products = session.createQuery("FROM Product").list();
for (Iterator iterator =
products.iterator(); iterator.hasNext();){
Product product = (Product) iterator.next();
System.out.print("Name: " + product.getName());
System.out.print("Alloy: " + product.getAlloy());
System.out.println("Weight: " + product.getWeight());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}

push value error in CRUD application

I'm working on CRUD application where I'm supposed to design multiple forms. I'm trying to model the application based on example available here.
I was able to design first form without any issues. But I'm facing following error for second form
type Exception report
message An exception occurred processing JSP page /ctsFrmCaseStage.jsp at line 22
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /ctsFrmCaseStage.jsp at line 22
19: </head>
20: <body>
21: <s:form action="saveOrUpdateCaseStage">
22: <s:push value="casestage">
23: <s:hidden name="ccs_ID" />
24: <s:textfield name="ccs_CaseStageName" label="CaseStage Name" />
25: <s:textfield name="ccs_Description" label="Description" />
root cause
tag 'push', field 'value': You must specify a value to push on the stack. Example: person - [unknown location]
org.apache.struts2.components.Component.fieldError(Component.java:230)
org.apache.struts2.components.Component.findValue(Component.java:351)
org.apache.struts2.components.Push.start(Push.java:128)
org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupp ort.java:53)
I took following steps to design this form -
1) CaseStage.Java this is my domain object
2) CaseStageDAO - interface
3) CaseStageDAOImpl - has four methods to perform the various CRUD operations.
4) CaseStageAction - implements model driven interface
5) ctsFrmCaseStage.jsp - jsp form
Once this was done - I also included CaseStage class in hibernate.cfg.xml Mappings section.
I'd like to know what I've missed... please note I'm very new to struts and hibernate world. Thank you very much in advance
Following is the code in sequence from all
CaseStage.java
package com.tutorials4u.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
#Entity
#Table(name = "mcasecategory")
public class CaseStage {
private Long ccs_ID;
private int ccs_StageName, ccs_Description;
#Id
#GeneratedValue
#Column(name = "ccs_ID")
public Long getCcs_ID() {
return ccs_ID;
}
public void setCcs_ID(Long ccs_ID) {
this.ccs_ID = ccs_ID;
}
#Column(name = "ccs_StageName")
public int getCcs_StageName() {
return ccs_StageName;
}
public void setCcs_StageName(int ccs_StageName) {
this.ccs_StageName = ccs_StageName;
}
#Column(name = "ccs_Description")
public int getCcs_Description() {
return ccs_Description;
}
public void setCcs_Description(int ccs_Description) {
this.ccs_Description = ccs_Description;
}
}
CaseStage.DAO
package com.tutorials4u.dao;
import java.util.List;
import com.tutorials4u.domain.CaseStage;
public interface CaseStageDAO {
public List<CaseStage> listCaseStage();
public void saveOrUpdateCaseStage(CaseStage casestage);
public CaseStage listCaseStageById(Long casestageId);
public void deleteCaseStage(Long casestageId);
}
CaseStageDAOImpl.java
package com.tutorials4u.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.tutorials4u.domain.CaseStage;
public class CaseStageDAOImpl implements CaseStageDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
/**
* Used to save or update a casestage.
*/
#SuppressWarnings("unchecked")
public List<CaseStage> listCaseStage() {
List<CaseStage> courses = null;
try {
courses = session.createQuery("from CaseStage").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
public void saveOrUpdateCaseStage(CaseStage casestage) {
try {
session.saveOrUpdate(casestage);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to delete a user.
*/
public void deleteCaseStage(Long casestageId) {
try {
CaseStage casestage = (CaseStage) session.get(CaseStage.class, casestageId);
session.delete(casestage);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to list all the users.
*/
/**
* Used to list a single user by Id.
*/
public CaseStage listCaseStageById(Long casestageId) {
CaseStage casestage = null;
try {
casestage = (CaseStage) session.get(CaseStage.class, casestageId);
} catch (Exception e) {
e.printStackTrace();
}
return casestage;
}
}
CaseStageAction.java
package com.tutorials4u.web;
import static com.opensymphony.xwork2.Action.SUCCESS;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.tutorials4u.dao.CaseStageDAO;
import com.tutorials4u.dao.CaseStageDAOImpl;
import com.tutorials4u.domain.CaseStage;
public class CaseStageAction extends ActionSupport implements ModelDriven<CaseStage> {
private static final long serialVersionUID = -6659925652584240539L;
private CaseStage casestage = new CaseStage();
private List<CaseStage> casestageList = new ArrayList<CaseStage>();
private CaseStageDAO casestageDAO = new CaseStageDAOImpl();
public CaseStage getModel() {
return casestage;
}
/**
* To save or update casestage.
* #return String
*/
public String saveOrUpdate()
{
casestageDAO.saveOrUpdateCaseStage(casestage);
return SUCCESS;
}
/**
* To list all categories.
* #return String
*/
public String list()
{
casestageList = casestageDAO.listCaseStage();
return SUCCESS;
}
/**
* To delete a casestage.
* #return String
*/
public String delete()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
casestageDAO.deleteCaseStage(Long.parseLong(request.getParameter("ccs_ID")));
return SUCCESS;
}
/**
* To list a single casestage by Id.
* #return String
*/
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
casestage = casestageDAO.listCaseStageById(Long.parseLong(request.getParameter("ccs_ID")));
return SUCCESS;
}
public CaseStage getCaseStage() {
return casestage;
}
public void setCaseStage(CaseStage casestage) {
this.casestage = casestage;
}
public List<CaseStage> getCaseStageList() {
return casestageList;
}
public void setCaseStageList(List<CaseStage> casestageList) {
this.casestageList = casestageList;
}
}
ctsFrmCaseStage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
#import url(style.css);
</style>
</head>
<body>
<s:form action="saveOrUpdateCaseStage">
<s:push value="casestage">
<s:hidden name="ccs_ID" />
<s:textfield name="ccs_CaseStageName" label="CaseStage Name" />
<s:textfield name="ccs_Description" label="Description" />
<s:submit />
</s:push>
</s:form>
<s:if test="casestageList.size() > 0">
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>CaseStage Name</th>
<th>Description</th>
</tr>
<s:iterator value="casestageList" status="casestageStatus">
<tr
class="<s:if test="#casestageStatus.odd == true ">odd</s:if> <s:else>even</s:else>">
<td><s:property value="ccs_CaseStageName" /></td>
<td><s:property value="ccs_Description" /></td>
<td><s:url id="editURL" action="editCaseStage">
<s:param name="ccs_ID" value="%{ccs_ID}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteCaseStage">
<s:param name="ccs_ID" value="%{ccs_ID}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</s:if>
</body>
</html>
Category.java
package com.tutorials4u.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
#Entity
#Table(name = "cts_mcasecategory")
public class Category {
private Long ccg_ID;
private int ccg_CreateUser, ccg_ModifyUser;
private String ccg_CategoryName;
private String ccg_Description;
private Date ccg_CreateDate, ccg_ModifyDate;
private boolean ccg_DeleteFlag, ccg_ActiveFlag;
#Id
#GeneratedValue
#Column(name = "ccg_ID")
public Long getCcg_ID() {
return ccg_ID;
}
public void setCcg_ID(Long ccg_ID) {
this.ccg_ID = ccg_ID;
}
#Column(name = "ccg_CategoryName")
public String getCcg_CategoryName() {
return ccg_CategoryName;
}
public void setCcg_CategoryName(String ccg_CategoryName) {
this.ccg_CategoryName = ccg_CategoryName;
}
#Column(name = "ccg_Description")
public String getCcg_Description() {
return ccg_Description;
}
public void setCcg_Description(String ccg_Description) {
this.ccg_Description = ccg_Description;
}
#Column(name = "ccg_CreateUser")
public int getCcg_CreateUser() {
return ccg_CreateUser;
}
public void setCcg_CreateUser(int ccg_CreateUser) {
this.ccg_CreateUser = ccg_CreateUser;
}
#Column(name = "ccg_ModifyUser")
public int getCcg_ModifyUser() {
return ccg_ModifyUser;
}
public void setCcg_ModifyUser(int ccg_ModifyUser) {
this.ccg_ModifyUser = ccg_ModifyUser;
}
#Column(name = "ccg_CreateDate")
public Date getCcg_CreateDate() {
return ccg_CreateDate;
}
public void setCcg_CreateDate(Date ccg_CreateDate) {
this.ccg_CreateDate = ccg_CreateDate;
}
#Column(name = "ccg_ModifyDate")
public Date getCcg_ModifyDate() {
return ccg_ModifyDate;
}
public void setCcg_ModifyDate(Date ccg_ModifyDate) {
this.ccg_ModifyDate = ccg_ModifyDate;
}
#Column(name = "ccg_DeleteFlag")
public boolean isCcg_DeleteFlag() {
return ccg_DeleteFlag;
}
public void setCcg_DeleteFlag(boolean ccg_DeleteFlag) {
this.ccg_DeleteFlag = ccg_DeleteFlag;
}
#Column(name = "ccg_ActiveFlag")
public boolean isCcg_ActiveFlag() {
return ccg_ActiveFlag;
}
public void setCcg_ActiveFlag(boolean ccg_ActiveFlag) {
this.ccg_ActiveFlag = ccg_ActiveFlag;
}
}
Hibernate config
<?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/case_tracking_system </property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">nvj#123</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.tutorials4u.domain.User"/>
<mapping class="com.tutorials4u.domain.Category"/>
<mapping class="com.tutorials4u.domain.CaseStage"/>
</session-factory>
</hibernate-configuration>
Struts.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.url">jdbc:mysql://localhost:3306/case_tracking_system </property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">nvj#123</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.tutorials4u.domain.User"/>
<mapping class="com.tutorials4u.domain.Category"/>
<mapping class="com.tutorials4u.domain.CaseStage"/>
</session-factory>
</hibernate-configuration>
Struts 2 “push” tag is used to push value to the top of stack, so that
it can be access or reference easily
You will have an error caused by:
tag 'push', field 'value': You must specify a value to push on the stack. Example: person - [unknown location]
Solution :
Yo can add a bean (to specify the value to push on the stack) in your ctsFrmCaseStage.jsp page before <s:form tag like that:
<body>
<s:bean name="com.tutorials4u.domain.CaseStage" var="casestage" />
<s:form action="saveOrUpdateCaseStage">
<s:push value="casestage">
NB :
Struts 2 “bean” tag is used to instantiate a class in the JSP page.

How to give foreign key in Hibernate

This is My LOGIN1.java class
import java.io.Serializable;
public class LOGIN1 implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String Email;
private String Password;
private Registration registration;
public Registration getRegistration() {
return registration;
}
public void setRegistration(Registration registration) {
this.registration = registration;
}
public int getId()
{
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
This Is My Registration.java
import java.io.Serializable;
public class Registration implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String contact;
private String Name;
private String amount;
private LOGIN1 login1;
public LOGIN1 getLogin1() {
return login1;
}
public void setLogin1(LOGIN1 login1) {
this.login1 = login1;
}
public int getId()
{
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
This Is My LOGIN1.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="LOGIN1" table="LOGIN1">
<id name="id" column="id" type="integer">
<generator class="increment"/>
</id>
<property name="Email" column="EMAIL" type="string"></property>
<property name="Password" column="Password" type="string"></property>
<one-to-one name="registration" class="Registration" cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>
this is my Registration.hbm.xml
<id name="id" column="id" type="integer">
<generator class="foreign">
<param name="property">rg</param>
</generator>
</id>
<one-to-one name="login1" class="LOGIN1" constrained="true"></one-to-one>
<property name="Name" column="Name" type="string"></property>
<property name="contact" column="contct" type="string"></property>
<property name="amount" column="iamt" type="string"></property>
</class>
</hibernate-mapping>
This is my hibernate.cfg
<?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:1433;databaseName=HiberNate</property>
<property name="hibernate.connection.username">aaa</property>
<property name="hibernate.connection.password">aaa</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="show_sql">true</property>
<mapping resource="LOGIN1.hbm.xml"></mapping>
<mapping resource="Registration.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
This is My Hiberservlets
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
#WebServlet("/HiberServlet")
public class HiberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HiberServlet() {
}
#SuppressWarnings("deprecation")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
out.print("Hello");
String a,b,c,d,e;
a=request.getParameter("cnm");
b=request.getParameter("cntno");
c=request.getParameter("amt");
d=request.getParameter("eml");
e=request.getParameter("pwd");
Session s=HibernateUtil.openSession();
Transaction tx = s.beginTransaction();
try {
LOGIN1 ln=new LOGIN1();
ln.setEmail(d);
ln.setPassword(e);
s.save(ln);
Criteria cr=s.createCriteria(LOGIN1.class);
cr.add(Restrictions.eq("Email",d));
cr.add(Restrictions.eq("Password",e));
int i=ln.getId();
Registration rg=new Registration();
rg.setId(i);
rg.setName(a);
rg.setContact(b);
rg.setAmount(c);
s.save(rg);
tx.commit();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
if(s!=null)
{
s.flush();
s.close();
}
}
catch(HibernateException e)
{
System.out.print(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
i am trying This but its Give error like
java.lang.NullPointerException
org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:650)
org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4736)
org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:96)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
HiberServlet.doGet(HiberServlet.java:77)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
And i am Using eclipse.what is problem in this code.
This
org.hibernate.PropertyNotFoundException: field [LOGIN1] not found on Registration
indicates, that your mapping does not match your class. There is probably no LOGIN1 property in the class. If it exists at all it is probably called login1 in lower case letters

defining collections in hibernate through annotations

I am new to the concepts of hibernate and annotations .Currently I am making program on collections in hibernate.
Actually following is code of my program
person.class
package com;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "PesonSubjects")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#ElementCollection
private Set<Subjects> subjectList = new HashSet<Subjects>();
public Set<Subjects> getSubjectList() {
return subjectList;
}
public void setSubjectList(Set<Subjects> subjectList) {
this.subjectList = subjectList;
}
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;
}
}
MAIN class
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class Personmain {
/**
* #param args
*/
public static void main(String[] args) {
SessionFactory sessionfactory = new AnnotationConfiguration()
.configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
Person person = new Person();
person.setName("vikram");
Subjects subjects1 = new Subjects();
subjects1.setAuthor("xxxxxxxx");
subjects1.setISBN(10111);
subjects1.setName("mein kampf");
subjects1.setPublicationHouse("tmh");
person.getSubjectList().add(subjects1);
Subjects subjects2 = new Subjects();
subjects2.setAuthor("bbbbb");
subjects2.setISBN(10112);
subjects2.setName("harry porter");
subjects2.setPublicationHouse("William");
person.getSubjectList().add(subjects2);
session.save(person);
session.getTransaction().commit();
session.close();
}
}
subjects class
package com;
import javax.persistence.Embeddable;
#Embeddable
public class Subjects {
private int ISBN;
private String name;
private String Author;
private String publicationHouse;
public int getISBN() {
return ISBN;
}
public void setISBN(int iSBN) {
ISBN = iSBN;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return Author;
}
public void setAuthor(String author) {
Author = author;
}
public String getPublicationHouse() {
return publicationHouse;
}
public void setPublicationHouse(String publicationHouse) {
this.publicationHouse = publicationHouse;
}
}
my configuration file
<?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/AnnotationCollections</property>
<property name="connection.username">root</property>
<property name="connection.password">cccccccc</property>
<property name="hbm2ddl.auto">create</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="com.Person" />
</session-factory>
</hibernate-configuration>
Now through the program I want a collection of subjects to enter into a table (I am not annotating subjectList as i want it to be collection and not in tabular format)
ie it should store values in collection fomat
However I am getting the following error
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Set, for columns: [org.hibernate.mapping.Column(subjectList)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:266)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
at org.hibernate.mapping.Property.isValid(Property.java:185)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:410)
at org.hibernate.mapping.RootClass.validate(RootClass.java:192)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1099)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1284)
at com.Personmain.main(Personmain.java:14)
Is there something else to define ??
Thanks
For security's sake, keep both classes mapped:
<mapping class="com.Person" />
<mapping class="com.Subjects" />
Besides that, your code seems to be inferring the wrong access type.
Try adding:
#javax.persistence.Access(javax.persistence.AccessType.FIELD)
to Person. Like:
#Entity
#Table(name = "PesonSubjects")
#javax.persistence.Access(javax.persistence.AccessType.FIELD)
public class Person {
If that does not work, try adding to both Person and Subjects.

Categories