cannot insert data to my table in database mysql - java

i have problem when insert to my database. here my setup for insert to my database.
First, I have method for getExecutionReport
first what i import
import com.dxtr.hibernate.DAOInsert;
import com.dxtr.hibernate.newOrderSingleEntity;
private void getExecutionReport(quickfix.Message message, String tipeMessage) {
// TODO Auto-generated method stub
try {
System.out.print("Message "+ message);
System.out.print("getExecutionReport "+tipeMessage);
newOrderSingleEntity newordersingleObj = new newOrderSingleEntity();
newordersingleObj.setSymbol(message.getString(Symbol.FIELD));
System.out.print(" symbol "+message.getString(Symbol.FIELD));
newordersingleObj.setMsgType(tipeMessage);
System.out.print(" tipeMessage "+tipeMessage);
newordersingleObj.setBodyLength(216);
System.out.print(" Body Length "+216);
newordersingleObj.setFixProtocol("FIX.4.2");
System.out.print("FixProtocol +FIX.4.2");
newordersingleObj.setTransactTime(message.getString(TransactTime.FIELD));
System.out.print(" time " +message.getString(TransactTime.FIELD));
newordersingleObj.setClOrdID(message.getString(ClOrdID.FIELD));
System.out.print(" ClOrdID "+message.getString(ClOrdID.FIELD));
newordersingleObj.setOrderID(message.getString(OrderID.FIELD));
System.out.print(" OrderID "+message.getString(OrderID.FIELD));
newordersingleObj.setExecID(message.getString(ExecID.FIELD));
System.out.print(" ExecID "+message.getString(ExecID.FIELD));
newordersingleObj.setExecTransType(message.getString(ExecTransType.FIELD));
System.out.print(" ExecTransType "+message.getString(ExecTransType.FIELD));
newordersingleObj.setOrdType(message.getString(OrdType.FIELD));
System.out.print(" OrdType "+message.getString(OrdType.FIELD));
newordersingleObj.setExecType(message.getString(ExecType.FIELD));
System.out.print(" ExecType "+message.getString(ExecType.FIELD));
newordersingleObj.setOrdStatus(message.getString(OrdStatus.FIELD));
System.out.print(" OrdStatus "+message.getString(OrdStatus.FIELD));
newordersingleObj.setSide(message.getInt(Side.FIELD));
System.out.print(" Side "+message.getInt(Side.FIELD));
newordersingleObj.setOrderQty(message.getDouble(OrderQty.FIELD));
System.out.print(" OrderQty "+message.getDouble(OrderQty.FIELD));
newordersingleObj.setLeavesQty(message.getDouble(LeavesQty.FIELD));
System.out.print(" LeavesQty "+message.getDouble(LeavesQty.FIELD));
newordersingleObj.setCumQty(message.getDouble(CumQty.FIELD));
System.out.print(" CumQty "+message.getDouble(CumQty.FIELD));
newordersingleObj.setLastShares(message.getInt(LastShares.FIELD));
System.out.print(" LastQty "+message.getInt(LastShares.FIELD));
System.out.print("sebelum insert ke db");
DAOInsert.newOrderSingleInsert(newordersingleObj);
} catch (FieldNotFound e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this code ok. but when i want to insert to my database my data cannot insert it.
here my entity
package com.dxtr.hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="New_Single_Order_Response",schema="dxtr_trades")
public class newOrderSingleEntity implements Serializable{
private static final long serialVersionUID = -1234424538928L;
#Id
#Column(name="response_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column(name="Fix_Protocol")
private String FixProtocol;
#Column(name="BodyLength")
private Integer BodyLength;
#Column(name="MsgSeqNum")
private Integer MsgSeqNum;
#Column(name="MsgType")
private String MsgType;
#Column(name="SenderCompId")
private String SenderCompId;
#Column(name="SendingTime")
private String SendingTime;
#Column(name="TargetCompID")
private String TargetCompID;
#Column(name="AveragePrice")
private Double AveragePrice;
#Column(name="ClOrdID")
private String ClOrdID;
#Column(name="CumQty")
private double CumQty;
#Column(name="Currency")
private String Currency;
#Column(name="ExecID")
private String ExecID;
#Column(name="LastShares")
private double LastShares;
#Column(name="OrderQty")
private Double OrderQty;
#Column(name="OrdStatus")
private String OrdStatus;
#Column(name="OrdType")
private String OrdType;
#Column(name="Side")
private Integer Side;
#Column(name="Symbol")
private String Symbol;
#Column(name="TransactTime")
private String TransactTime;
#Column(name="ExecType")
private String ExecType;
#Column(name="LeavesQty")
private double LeavesQty;
#Column(name="CheckSum")
private Integer CheckSum;
#Column(name="ExecTransType")
private String ExecTransType;
#Column(name="OrderID")
private String OrderID;
public Integer getResponse_ID() {
return this.id;
}
public void setResponse_ID(Integer id) {
this.id = id;
}
public String getFixProtocol() {
return this.FixProtocol;
}
public void setFixProtocol(String FixProtocol) {
this.FixProtocol = FixProtocol;
}
public Integer getBodyLength() {
return this.BodyLength;
}
public void setBodyLength(Integer BodyLength) {
this.BodyLength = BodyLength;
}
public Integer getMsgSeqNum() {
return this.MsgSeqNum;
}
public void setMsgSeqNum(Integer MsgSeqNum) {
this.MsgSeqNum = MsgSeqNum;
}
public String getMsgType() {
return this.MsgType;
}
public void setMsgType(String MsgType) {
this.MsgType = MsgType;
}
public String getSenderCompId() {
return this.SenderCompId;
}
public void setSenderCompId(String SenderCompId) {
this.SenderCompId = SenderCompId;
}
public String getSendingTime() {
return this.SendingTime;
}
public void setBodyLength(String SendingTime) {
this.SendingTime = SendingTime;
}
public String getTargetCompID() {
return this.TargetCompID;
}
public void setTargetCompID(String TargetCompID) {
this.TargetCompID = TargetCompID;
}
public Double getAveragePrice() {
return this.AveragePrice;
}
public void setAveragePrice(Double AveragePrice) {
this.AveragePrice = AveragePrice;
}
public String getClOrdID() {
return this.ClOrdID;
}
public void setClOrdID(String ClOrdID) {
this.ClOrdID = ClOrdID;
}
public double getCumQty() {
return this.CumQty;
}
public void setCumQty(double CumQty) {
this.CumQty = CumQty;
}
public String getCurrency() {
return this.Currency;
}
public void setCurrency(String Currency) {
this.Currency = Currency;
}
public String getExecID() {
return this.ExecID;
}
public void setExecID(String ExecID) {
this.ExecID = ExecID;
}
public double getLastShares() {
return this.LastShares;
}
public void setLastShares(double LastShares) {
this.LastShares = LastShares;
}
public Double getOrderQty() {
return this.OrderQty;
}
public void setOrderQty(Double OrderQty) {
this.OrderQty = OrderQty;
}
public String getExecType() {
return this.ExecType;
}
public void setExecType(String ExecType) {
this.ExecType = ExecType;
}
public String getOrdStatus() {
return this.OrdStatus;
}
public void setOrdStatus(String OrdStatus) {
this.OrdStatus = OrdStatus;
}
public String getOrdType() {
return this.OrdType;
}
public void setOrdType(String OrdType) {
this.OrdType = OrdType;
}
public Integer getSide() {
return this.Side;
}
public void setSide(Integer Side) {
this.Side = Side;
}
public String getSymbol() {
return this.Symbol;
}
public void setSymbol(String Symbol) {
this.Symbol = Symbol;
}
public String getTransactTime() {
return this.TransactTime;
}
public void setTransactTime(String TransactTime) {
this.TransactTime = TransactTime;
}
public double getLeavesQty() {
return this.LeavesQty;
}
public void setLeavesQty(double LeavesQty) {
this.LeavesQty = LeavesQty;
}
public Integer getCheckSum() {
return this.CheckSum;
}
public void setCheckSum(Integer CheckSum) {
this.CheckSum = CheckSum;
}
public String getExecTransType() {
return this.ExecTransType;
}
public void setExecTransType(String ExecTransType) {
this.ExecTransType = ExecTransType;
}
public String getOrderID() {
return this.OrderID;
}
public void setOrderID(String OrderID) {
this.OrderID = OrderID;
}
public String toString() {
return "OrderDetail?= Id: " + this.id + ", ClOrdID: " + this.ClOrdID + ", ExecID No.: " + this.ExecID + ", Symbol: " + this.Symbol;
}
}
and here my class for insert to database
package com.dxtr.hibernate;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import quickfix.StringField;
public class DAOInsert {
private DAOInsert dAOInsert;
static Session sessionObj;
static SessionFactory sessionFactoryObj;
public final static Logger logger = Logger.getLogger(DAOInsert.class);
// This Method Is Used To Create The Hibernate's SessionFactory Object
public static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
public static void newOrderSingleInsert(newOrderSingleEntity newordersingleObj){
int count = 0;
try {
System.out.print("sudah di DAOInsert");
// Getting Session Object From SessionFactory
sessionObj = buildSessionFactory().openSession();
// Getting Transaction Object From Session Object
sessionObj.beginTransaction();
sessionObj.persist(newordersingleObj);
System.out.print(sessionObj.contains(newordersingleObj));
// Creating Transaction Entities
// newordersingleObj = new NewOrderSingle();
//newordersingleObj.setFixProtocol("FIX.4.2");
//newordersingleObj.setBodyLength(250);
//sessionObj.save(newordersingleObj);
//Committing The Transactions To The Database
sessionObj.getTransaction().commit();
//logger.info("\nSuccessfully Created '" + count + "' Records In The Database!\n");
} catch(Exception e) {
if(null != sessionObj.getTransaction()) {
logger.info("\n.......Transaction Is Being Rolled Back.......\n");
sessionObj.getTransaction().rollback();
}
e.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
}
i have also set persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="FastMatch" transaction-type="RESOURCE_LOCAL">
<class>com.dxtr.hibernate.newOrderSingleEntity</class>
<properties>
<property name="eclipselink.logging.level" value="INFO"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://trades/tradesnew />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="eclipselink.logging.level.connection" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
and also i have hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://url/trades</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.dxtr.hibernate.newOrderSingleEntity"></mapping>
</session-factory>
</hibernate-configuration>
but when i want to insert to my database this data cannot insert it.. but i don't know where is the error... i have catch the error using
catch(Exception e) {
if(null != sessionObj.getTransaction()) {
logger.info("\n.......Transaction Is Being Rolled Back.......\n");
sessionObj.getTransaction().rollback();
}
e.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
but there is no error in my console print... so where is the problem from my code ?
for information i use mysql5.7 version and using aws
best regards,
Fuad

I would suggest you enable MySQL logs, then follow the instructions at https://dev.mysql.com/doc/refman/5.7/en/server-logs.html and be sure to flush the logs. The logs should be at /bar/log/MySQL

Related

How to properly use JPA/Hibernate?

I'm trying to understand annotations better with JPA / Hibernate and SQL Server.
I created a simple project: an abstract class named "Articles". Two classes inherit it: Ramette which adds a weight and Pen which adds a color. The code below is not working and I am unable to correct the errors. Do you have an idea? Thank you!
package fr.eni.hibernate.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
#Entity
#Table(name = "Articles")
#Inheritance( strategy = InheritanceType.SINGLE_TABLE )
#DiscriminatorColumn( name="type", discriminatorType = DiscriminatorType.STRING)
public abstract class Articles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idarticle")
private Integer idarticle;
#Column(name = "reference")
private String reference;
#Column(name = "marque")
private String marque ;
#Column(name = "designation")
private String designation;
#Column(name = "prixUnitaire")
private float prixUnitaire ;
#Column(name = "qteStock")
private int qteStock ;
public Articles() {
}
public Integer getIdArticle() {
return idarticle;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getMarque() {
return marque;
}
public void setMarque(String marque) {
this.marque = marque;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public float getPrixUnitaire() {
return prixUnitaire;
}
public void setPrixUnitaire(float prixUnitaire) {
this.prixUnitaire = prixUnitaire;
}
public int getQteStock() {
return qteStock;
}
public void setQteStock(int qteStock) {
this.qteStock = qteStock;
}
#Override
public String toString() {
return "Article [idArticle=" + idarticle + ", reference=" + reference + ", marque=" + marque + ", designation="
+ designation + ", prixUnitaire=" + prixUnitaire + ", qteStock=" + qteStock + "]";
}
}
package fr.eni.hibernate.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
#Entity
#DiscriminatorValue("Ramette")
public class Ramette extends Articles {
private static final long serialVersionUID = 1L;
private int grammage;
public Ramette() {
}
#Column(name = "grammage")
public int getGrammage() {
return grammage;
}
public void setGrammage(int grammage) {
this.grammage = grammage;
}
#Override
public String toString() {
return super.toString() + " Ramette [grammage=" + grammage + "]";
}
}
package fr.eni.hibernate.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
#Entity
#DiscriminatorValue("Stylo")
public class Stylo extends Articles {
private static final long serialVersionUID = 1L;
private String couleur;
public Stylo() {
}
#Column(name = "couleur")
public String getCouleur() {
return couleur;
}
public void setCouleur(String couleur) {
this.couleur = couleur;
}
#Override
public String toString() {
return super.toString() + " Stylo [couleur=" + couleur + "]";
}
}
package fr.eni.hibernate.entities;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
public class Main {
public static void main(String[] args) throws Exception {
EntityManagerFactory entityManagerFactory = null;
EntityManager entityManager = null;
try {
entityManagerFactory = Persistence.createEntityManagerFactory("WebStore");
entityManager = entityManagerFactory.createEntityManager();
TypedQuery<Articles> query = entityManager.createQuery("from Articles", Articles.class);
List<Articles> art = query.getResultList();
for (Articles article : art) {
System.out.println(art.getClass().getName());
System.out.println("\t" + article);
}
} finally {
if (entityManager != null)
entityManager.close();
if (entityManagerFactory != null)
entityManagerFactory.close();
}
}
}
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns<img src="images/smilies/icon_mad.gif" border="0" alt="" title=":x" class="inlineimg" />si="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"
version="2.0">
<persistence-unit name="WebStore">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>fr.eni.hibernate.entities.Articles</class>
<class>fr.eni.hibernate.entities.Stylo</class>
<class>fr.eni.hibernate.entities.Ramette</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:sqlserver://localhost;database=PAPETERIE_TEST" />
<property name="javax.persistence.jdbc.user" value="xx" />
<property name="javax.persistence.jdbc.password" value="x" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.SQLServerDialect" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
CREATE TABLE Articles
(
idarticle INT IDENTITY(1,1),
reference varchar(10) NOT NULL,
marque nvarchar(200) NOT NULL,
designation nvarchar(250) NOT NULL,
prixUnitaire float NOT NULL,
qteStock int NOT NULL,
grammage int NULL,
couleur nvarchar(50) NULL,
type nchar(10) NOT NULL,
CONSTRAINT PK_Articles PRIMARY KEY (idarticle)
)
INSERT INTO Articles (reference, marque, designation, prixUnitaire, qteStock, grammage, couleur, type)
VALUES ('Bic', 'BBOrange', 'Bic bille Orange', 1.2, 20, 0, 'Bleu', 'Stylo'),
('Bic', 'BBOrange', 'Bic bille Orange', 1.2, 20, 0,'noir', 'Stylo'),
('Clairef', 'CRA4S', 'Ramette A4 Sup', 9, 20, 80, null, 'Ramette');
This makes not much sense. This exception is only thrown when you have a discriminator in the table that has no match in the entity model. Maybe you have trailing spaces in the table?

Enity is not mapped [select o from Type o]

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();
}
}
solved ! the problem was the version of hibernate that I used so I change it, a change in HibernateUtil.

I can't get the currentSession

I'm a beginner in Java EE programming. I got this error message when I tried to save an employee in a database:
java.lang.NullPointerException
at ma.lezar.ge.dao.EmployeesDAO.getCurrentSession(EmployeesDAO.java:48)
at ma.lezar.ge.dao.EmployeesDAO.save(EmployeesDAO.java:59)
at ma.lezar.ge.service.ServiceEmployees.save(ServiceEmployees.java:26)
at ma.lezar.ge.bean.InscrirBean.valider(InscrirBean.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 28 more
This is employeeDAO.java
package ma.lezar.ge.dao;
import java.util.List;
import java.util.Set;
import ma.lezar.ge.model.Employees;
import org.hibernate.Hibernate;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository("EmployeesDAO")
#Transactional
public class EmployeesDAO implements IEmployeesDAO {
private static final Logger log = LoggerFactory
.getLogger(EmployeesDAO.class);
// property constants
public static final String NOM = "nom";
public static final String NUM = "num";
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
protected void initDao() {
// do nothing
}
public void save(Employees transientInstance) {
//System.out.println(getCurrentSession().toString());
// log.debug("saving Employees instance");
// try {
getCurrentSession().save(transientInstance);
// log.debug("save successful");
// } catch (RuntimeException re) {
// log.error("save failed", re);
// throw re;
// }
}
public void delete(Employees persistentInstance) {
log.debug("deleting Employees instance");
try {
getCurrentSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Employees findById(java.lang.Integer id) {
log.debug("getting Employees instance with id: " + id);
try {
Employees instance = (Employees) getCurrentSession().get(
"ma.lezar.ge.model.Employees", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findAll() {
log.debug("finding all Employees instances");
try {
String queryString = "from Employees";
Query queryObject = getCurrentSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public static EmployeesDAO getFromApplicationContext(ApplicationContext ctx) {
return (EmployeesDAO) ctx.getBean("EmployeesDAO");
}
}
Employee.java
package ma.lezar.ge.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Employees entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "employees", catalog = "gest_emp")
public class Employees implements java.io.Serializable {
// Fields
private Integer id;
private String nom;
private Integer num;
private Set<Compte> comptes = new HashSet<Compte>(0);
// Constructors
/** default constructor */
public Employees() {
}
/** minimal constructor */
public Employees(String nom, Integer num) {
this.nom = nom;
this.num = num;
}
/** full constructor */
public Employees(String nom, Integer num, Set<Compte> comptes) {
this.nom = nom;
this.num = num;
this.comptes = comptes;
}
// Property accessors
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "nom", nullable = false, length = 50)
public String getNom() {
return this.nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Column(name = "num", nullable = false)
public Integer getNum() {
return this.num;
}
public void setNum(Integer num) {
this.num = num;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "employees")
public Set<Compte> getComptes() {
return this.comptes;
}
public void setComptes(Set<Compte> comptes) {
this.comptes = comptes;
}
}
InscrirBean.java
package ma.lezar.ge.bean;
import java.io.Serializable;
import javax.ejb.EJB;
import org.springframework.beans.factory.annotation.Autowired;
import ma.lezar.ge.dao.EmployeesDAO;
import ma.lezar.ge.model.Employees;
import ma.lezar.ge.service.IServiceEmployees;
import ma.lezar.ge.service.ServiceEmployees;
public class InscrirBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Autowired
private ServiceEmployees serviceEmployees;
private String nom;
private Integer num;
public String valider()
{
serviceEmployees = new ServiceEmployees();
serviceEmployees.save(new Employees(nom, num));
return "success";
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}
ServiceEmployee.java
package ma.lezar.ge.service;
import java.util.List;
import javax.annotation.Resource;
import ma.lezar.ge.dao.EmployeesDAO;
import ma.lezar.ge.dao.IEmployeesDAO;
import ma.lezar.ge.model.Employees;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
#Service("serviceEmployees")
public class ServiceEmployees implements IServiceEmployees {
#Resource
private EmployeesDAO employeesDao;
public void save(Employees transientInstance) {
employeesDao = new EmployeesDAO();
employeesDao.save(transientInstance);
}
public void delete(Employees persistentInstance) {
employeesDao.delete(persistentInstance);
}
public Employees findById(java.lang.Integer id) {
Employees instance = (Employees) employeesDao.findById(id);
return instance;
}
public List findAll()
{
return employeesDao.findAll();
}
}
HibernateSessionFactory.java
package ma.lezar.ge.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {#link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* #return Session
* #throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* #throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="url"
value="jdbc:mysql://localhost:3306/gest_emp">
</property>
<property name="username" value="root"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>ma.lezar.ge.model.Compte</value>
<value>ma.lezar.ge.model.Employees</value></list>
</property></bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="CompteDAO" class="ma.lezar.ge.dao.CompteDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="EmployeesDAO" class="ma.lezar.ge.dao.EmployeesDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>
You're instantiating employeesDao yourself instead of letting Spring manage the DI for that class. Remove the statement
employeesDao = new EmployeesDAO();
in ServiceEmployees.

java hibernate the table not created even with <property name="hibernate.hbm2ddl.auto">update</property>

/**
* Description of bankbranchcontactdetailsBean
*
* #author Vishal Jain
*/
package com.beans;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Temporal;
import javax.persistence.UniqueConstraint;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.io.Serializable;
import java.util.Date;
#Entity(name = "bankbranchcontactdetails")
#Table(name = "bankbranchcontactdetails", schema = "stserptest", uniqueConstraints = { #UniqueConstraint(columnNames = "BankBranchContactId") })
#TableGenerator(name = "bankbranchcontactdetailsgen", table = "bankbranchcontactdetails", pkColumnName = "BankBranchContactId")
public class bankbranchcontactdetailsBean extends SuperBeanClass implements SuperBeanInterface, Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(columnDefinition="mysql->int(10) unsigned", name = "BankBranchContactId", precision = 10, scale = 0, nullable = false, unique = true)
private Integer Id;
#Column(columnDefinition="mysql->int(10) unsigned", name = "BankBranchId", precision = 10, scale= 0, nullable = false)
private Integer _BankBranchId;
#Column(columnDefinition="mysql->enum('Phone','Mobile','Fax','Telex')", name = "ContactType", length = 6, nullable = false)
private String _ContactType;
#Column(columnDefinition="mysql->varchar(20)", name = "Contact", length = 20, nullable = false)
private String _Contact;
public bankbranchcontactdetailsBean() {
_BankBranchId = 0;
_ContactType = "";
_Contact = "";
}
public bankbranchcontactdetailsBean(Integer __BankBranchId, String __ContactType, String __Contact, Integer __MyCompanyId) {
_BankBranchId = __BankBranchId;
_ContactType = __ContactType;
_Contact = __Contact;
_MyCompanyId = __MyCompanyId;
}
public int getBankBranchContactId() {
return Id;
}
public Integer getBankBranchId() {
return _BankBranchId;
}
public String getContactType() {
return _ContactType;
}
public String getContact() {
return _Contact;
}
public void setBankBranchContactId(int NewValue) {
Id = NewValue;
}
public void setBankBranchId(Integer NewValue) {
_BankBranchId = NewValue;
}
public void setContactType(String NewValue) {
_ContactType = NewValue;
}
public void setContact(String NewValue) {
_Contact = NewValue;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">MimosaTorpedo</property>
<property name="hibernate.default_schema">stserptest</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping class="com.stserp.beans.bankbranchcontactdetailsBean" />
</session-factory>
</hibernate-configuration>
/**
* Description of ManagerClass
*
* #author Vishal Jain
*/
package com.beans;
import java.util.ArrayList;
import javax.swing.JOptionPane;
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;
public class ManagerClass {
private static SessionFactory factory = null;
private static ManagerClass _ManagerClass = null;
public static SessionFactory createSessionFactory() {
SessionFactory sessionFactory;
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return factory;
}
public static ManagerClass getInstance() throws ExceptionInInitializerError {
try {
if (factory == null) {
factory = createSessionFactory();
}
if (_ManagerClass == null) {
_ManagerClass = new ManagerClass();
}
} catch (Throwable ex) {
JOptionPane.showMessageDialog(
null,
"Failed to create sessionFactory object...\n"
+ ex.getMessage(), "Error...", 0);
throw new ExceptionInInitializerError(ex);
} finally {
return _ManagerClass;
}
}
public ArrayList<Integer> SaveBeansList(Session session, String entityName,
ArrayList<? extends SuperBeanClass> BeansList)
throws HibernateException {
ArrayList<Integer> IDs = null;
try {
IDs = new ArrayList<Integer>();
for (SuperBeanClass element : BeansList) {
IDs.add((Integer) session.save(entityName, element));
}
} catch (HibernateException e) {
throw e;
}
return IDs;
}
public ArrayList<? extends SuperBeanClass> LoadTable(Session session,
String TableName) throws HibernateException {
ArrayList<? extends SuperBeanClass> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery("FROM " + TableName).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public ArrayList<?> LoadConditional(Session session, String _query)
throws HibernateException {
ArrayList<?> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery(_query).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public SuperBeanInterface LoadById(Session session, Class className,
Integer ID) throws HibernateException {
SuperBeanInterface BeanInterface = null;
try {
BeanInterface = (SuperBeanInterface) session.get(className, ID);
} catch (HibernateException e) {
throw e;
}
return BeanInterface;
}
public void DeleteById(Session session, Class className, Integer ID)
throws HibernateException {
try {
session.delete(session.get(className, ID));
} catch (HibernateException e) {
throw e;
}
}
}
/**
* Description of SuperBeanClass
*
* #author Vishal Jain
*/
package com.beans;
public class SuperBeanClass {
public SuperBeanClass() {
}
}
/**
* Description of SuperBeanInterface
*
* #author Vishal Jain
*/
package com.beans;
public interface SuperBeanInterface {
}
I dont know what wrong I am doing, but even though the code gets executed fine, the Table named 'bankbranchcontactdetails' does not get created, here. The database I am using is MySQL. Can anybody help me with that
Trying Changing Column Definitions here, is a good idea. The Problem was with the database specific directions 'mysql->'. I am might be using it wrongly. But for now I tried removing it and it worked.

Hibernate Query Syntax exception : org.hibernate.hql.ast.QuerySyntaxException: unexpected token

I have a query where i am joining two tables ROuteMaster and RouteHalts.
When i perform inner join i am getting
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1,
column 169 [SELECT rm.id , rm.routeCode , rm.startPlaceId , rm.endPlaceId ,
rm.active, rm.linkedRoute FROM com.oprs.pojo.routes.RouteMaster rm INNER JOIN
RouteHalts rh on rm.id = rh.routeId WHERE rh.placeId = :PlaceId
ORDER BY rm.id ASC]
I searched through the site and found similar question and the response for it. the question referred was
Hibernate: org.hibernate.hql.ast.QuerySyntaxException: unexpected token
I have many-to-one mapping in RouteHalts for RouteMaster, I have defined getter and setter methods for RouteMaster in RouteHalts
<many-to-one name="RouteMaster" class="com.oprs.pojo.routes.RouteMaster"
fetch="join"
foreign-key="id" column="ROUTE_ID" insert="false"
update="false" lazy="false" />
but still getting the same error. Can please some one guide me.
Mapping files
<hibernate-mapping package="com.oprs.pojo.routes">
<!-- Hibernate mapping for RouteMaster table -->
<class name="RouteMaster" table="OPRS_ROUTE_MASTER">
<id name="id" column="ROUTE_ID" type="java.lang.Long">
<generator class="assigned" />
</id>
<property name="startPlaceId" column="START_PLACE_ID"/>
<property name="endPlaceId" column="END_PLACE_ID"/>
<property name="routeCode" column="ROUTE_CODE"/>
<property name="routeName" column="ROUTE_NAME"/>
<property name="active" column="IS_ACTIVE"/>
<property name="linkedRoute" column="LINKED_ROUTE"/>
<property name="returnRouteId" column="RET_ROUTE_ID"/>
<!-- Auditor Information -->
<component name="auditor" class="com.oprs.pojo.base.Auditor">
<property name="createdBy" column="CREATED_BY" />
<property name="createdDate" column="CREATED_DATE" />
<property name="modifiedBy" column="MODIFIED_BY" />
<property name="modifiedDate" column="MODIFIED_DATE" />
</component>
<many-to-one name="RouteHalts" class="com.oprs.pojo.routes.RouteHalts" fetch="join"
foreign-key="routeId" column="ROUTE_ID" insert="false"
update="false" lazy="false" />
</class>
<!-- Hibernate mapping for RouteHalts table -->
<class name="RouteHalts" table="OPRS_ROUTE_HALTS">
<id name="id" column="HALTS_ID" type="java.lang.Long">
<generator class="assigned" />
</id>
<property name="routeId" column="ROUTE_ID"/>
<property name="placeId" column="PLACE_ID"/>
<property name="seqNo" column="SEQ_NO"/>
<property name="distanceKM" column="DISTANCE_KM"/>
<property name="border" column="IS_BORDER"/>
<property name="tolls" column="NO_OF_TOLLS"/>
<!-- Auditor Information -->
<component name="auditor" class="com.oprs.pojo.base.Auditor">
<property name="createdBy" column="CREATED_BY" />
<property name="createdDate" column="CREATED_DATE" />
<property name="modifiedBy" column="MODIFIED_BY" />
<property name="modifiedDate" column="MODIFIED_DATE" />
</component>
</class>
POJO of Route Master
public class RouteMaster extends Persistent {
private static final long serialVersionUID = -5710336066048392949L;
private Long startPlaceId;
private Long endPlaceId;
private Long returnRouteId;
private String startPlaceCode;
private String endPlaceCode;
private String startPlaceName;
private String endPlaceName;
private String routeCode;
private String routeName;
private String active;
private Auditor auditor;
private boolean revervseRoute;
private String linkedRoute = AppConstants.N;
private Map<Double, RouteHalts> haltsMap;
private RouteHalts routeHalts;
public RouteHalts getRouteHalts() {
return routeHalts;
}
public void setRouteHalts(RouteHalts routeHalts) {
this.routeHalts = routeHalts;
}
public Long getStartPlaceId() {
return startPlaceId;
}
public void setStartPlaceId(Long startPlaceId) {
this.startPlaceId = startPlaceId;
}
public Long getEndPlaceId() {
return endPlaceId;
}
public void setEndPlaceId(Long endPlaceId) {
this.endPlaceId = endPlaceId;
}
public String getStartPlaceCode() {
return startPlaceCode;
}
public void setStartPlaceCode(String startPlaceCode) {
this.startPlaceCode = startPlaceCode;
}
public String getEndPlaceCode() {
return endPlaceCode;
}
public void setEndPlaceCode(String endPlaceCode) {
this.endPlaceCode = endPlaceCode;
}
public Long getReturnRouteId() {
return returnRouteId;
}
public void setReturnRouteId(Long returnRouteId) {
this.returnRouteId = returnRouteId;
}
public String getRouteCode() {
return routeCode;
}
public void setRouteCode(String routeCode) {
this.routeCode = routeCode;
}
public Auditor getAuditor() {
return auditor;
}
public void setAuditor(Auditor auditor) {
this.auditor = auditor;
}
public String getStartPlaceName() {
return startPlaceName;
}
public void setStartPlaceName(String startPlaceName) {
this.startPlaceName = startPlaceName;
}
public String getEndPlaceName() {
return endPlaceName;
}
public void setEndPlaceName(String endPlaceName) {
this.endPlaceName = endPlaceName;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public Map<Double, RouteHalts> getHaltsMap() {
return haltsMap;
}
public void setHaltsMap(Map<Double, RouteHalts> haltsMap) {
this.haltsMap = haltsMap;
}
public boolean isRevervseRoute() {
return revervseRoute;
}
public void setRevervseRoute(boolean revervseRoute) {
this.revervseRoute = revervseRoute;
}
public String getLinkedRoute() {
return linkedRoute;
}
public void setLinkedRoute(String linkedRoute) {
this.linkedRoute = linkedRoute;
}
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
}
POJO of RouteHalts
public class RouteHalts extends Persistent {
private static final long serialVersionUID = -1491637903595290895L;
private Long placeId;
private Long routeId;
private String placeCode;
private Double seqNo;
private Double distanceKM;
private boolean border;
private Auditor auditor;
private String placeName;
private String stateCode;
private String stopType;
private String departureTime;
private Integer tolls;
private String platformNo;
private Long stopTypeId;
private Integer linkSequenceNo;
private String actualTime;
private int arrivalDay;
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public Long getRouteId() {
return routeId;
}
public void setRouteId(Long routeId) {
this.routeId = routeId;
}
public Long getPlaceId() {
return placeId;
}
public void setPlaceId(Long placeId) {
this.placeId = placeId;
}
public String getPlaceCode() {
return placeCode;
}
public void setPlaceCode(String placeCode) {
this.placeCode = placeCode;
}
public Double getDistanceKM() {
return distanceKM;
}
public void setDistanceKM(Double distanceKM) {
this.distanceKM = distanceKM;
}
public boolean isBorder() {
return border;
}
public void setBorder(boolean border) {
this.border = border;
}
public Auditor getAuditor() {
return auditor;
}
public void setAuditor(Auditor auditor) {
this.auditor = auditor;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public Double getSeqNo() {
return seqNo;
}
public void setSeqNo(Double seqNo) {
this.seqNo = seqNo;
}
public String getStopType() {
return stopType;
}
public void setStopType(String stopType) {
this.stopType = stopType;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Integer getTolls() {
return tolls;
}
public void setTolls(Integer tolls) {
this.tolls = tolls;
}
public String getPlatformNo() {
return platformNo;
}
public void setPlatformNo(String platformNo) {
this.platformNo = platformNo;
}
public Long getStopTypeId() {
return stopTypeId;
}
public void setStopTypeId(Long stopTypeId) {
this.stopTypeId = stopTypeId;
}
public Integer getLinkSequenceNo() {
return linkSequenceNo;
}
public void setLinkSequenceNo(Integer linkSequenceNo) {
this.linkSequenceNo = linkSequenceNo;
}
public int getArrivalDay() {
return arrivalDay;
}
public void setArrivalDay(int arrivalDay) {
this.arrivalDay = arrivalDay;
}
public String getActualTime() {
return actualTime;
}
public void setActualTime(String actualTime) {
this.actualTime = actualTime;
}
}
You should not use explicit "JOIN ON" in HQL. Instead you can use implicit joining in HQL:
SELECT rm.id , rm.routeCode , rm.startPlaceId , rm.endPlaceId , rm.active , rm.linkedRoute
FROM com.abhibus.oprs.pojo.routes.RouteMaster rm
INNER JOIN rm.routeHalts rh WHERE rh.placeId = :PlaceId ORDER BY rm.id ASC
or you can use Theta style for writing join:
SELECT rm.id , rm.routeCode , rm.startPlaceId , rm.endPlaceId , rm.active , rm.linkedRoute
FROM com.abhibus.oprs.pojo.routes.RouteMaster rm, RouteHalts rh
WHERE rm.id = rh.routeId AND rh.placeId = :PlaceId ORDER BY rm.id ASC
Also you can execute your query as native SQL query, not HQL query. For this you should use
session.createSQLQuery(queryText);
instead of
session.createQuery(queryText);
And by the way, may be in your case in is better to fetch whole entity, not separated fields (columns)? For this you can use:
select rm from ...
This will return the List<RouteMaster> insted of List<Object[]>.
Change your query likes this;
SELECT rm.id, rm.routeCode, rm.startPlaceId, rm.endPlaceId, rm.active, rm.linkedRoute
FROM RouteMaster rm
INNER JOIN rm.routeHalts AS rh ON rm.id = rh.routeId
WHERE rh.placeId = :PlaceId
ORDER BY rm.id ASC

Categories

Resources