Error reading 'nom' on type dao.Etudiant_$$_jvst1a2_0 Hibernate - spring

I want to search on a table by ID , the search work fine , but when hibernate don t find any row it s return this error :
Error reading "nom" on type dao.Etudiant , and sometimes it s return : No row with the given identifier exists:[dao.Etudiant#4]
I want to show nothing when hibernate don t find that ID on the table , need your helps thanks , I m stack my learning, I googled a lot without any solution. this is my code :
Controller :
package controller;import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import dao.DaoEtudiant;
import dao.Etudiant;
import service.EtudiantMetier;
#Controller
public class EtudiantController {
#Autowired
EtudiantMetier service;
#RequestMapping("afficherId")
public String afficheId(Model mod,#RequestParam(value="id") Long id)
{
List <Etudiant> ets1=new ArrayList<Etudiant>();
ets1.add(service.chercheEtudiantID(id));
mod.addAttribute("etudiants",ets1);
return "etudiant1";
}
}
Class : Etudiant :
package dao;
import java.util.Date;
public class Etudiant {
private Long idEtudiant;
private String nom;
private String prenom;
private Date dateNaissance;
private String email;
public Etudiant() {
super();
}
public Long getIdEtudiant() {
return idEtudiant;
}
public void setIdEtudiant(Long idEtudiant) {
this.idEtudiant = idEtudiant;
}
public Etudiant(String nom, String prenom, Date dateNaissance, String email) {
super();
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
this.email = email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDateNaissance() {
return dateNaissance;
}
public void setDateNaissance(Date dateNaissance) {
this.dateNaissance = dateNaissance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Etudiant.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 20, 2016 7:42:26 AM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="dao.Etudiant" table="etudiant">
<id name="idEtudiant">
<column name="ID_ETUDIANT" />
<generator class="native" />
</id>
<property name="nom" column="NOM" />
<property name="prenom" >
<column name="PRENOM" />
</property>
<property name="dateNaissance" >
<column name="DATE_NAISSANCE" />
</property>
<property name="email" >
<column name="EMAIL" />
</property>
</class>
Hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class"> com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/etudes</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">100</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.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 the existing tables and create new one -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.enable_lazy_load_no_trans" >
true
</property>
<!-- Mention here all the model classes along with their package name -->
<mapping resource="dao/Etudiant.hbm.xml"/>
</session-factory>
Etudiantmetierimpl.java:
#Override
public Etudiant chercheEtudiantID(Long idEtudiant) {
Session session=HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
System.out.println("avant load session");
Etudiant et=session.load (Etudiant.class, idEtudiant);
//Etudiant et=session.get (Etudiant.class, idEtudiant); // presque meme chose que load
System.out.println("apres load session et ");
session.close();
return et;
}

find it finally. I change this line :
Etudiant et=session.load (Etudiant.class, idEtudiant)
to :
Etudiant et=session.get (Etudiant.class, idEtudiant)
doc:
session.load()
• It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
• If no row found , it will throws an ObjectNotFoundException.
session.get()
• It always hit the database and return the real object, an object that represent the database row, not proxy.
• If no row found , it return null.

Related

Is it possible to define a Spring Repository for shared classes?

I have a class User which is shared between the server and the android client. So I don't want to annotate the class with an #id annotation.
What is the best way to deal with this in spring-jpa?
I believe the simplest possible way is to fallback to xml mapping so your domain objects will stay pure.
Spring-boot will notice that you're using this type of mapping and configure hibernate for you out of the box.
Here is a simple example:
package com.stackoverflow.so45264894;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;
#SpringBootApplication
#EnableJpaRepositories
public class So45264894Application {
public static void main(String[] args) {
SpringApplication.run(So45264894Application.class, args);
}
public static class User {
private Long id;
private String username;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
}
#Bean
CommandLineRunner run(UserRepository userRepository) {
final User user = new User();
user.setUsername("admin");
return args -> userRepository.save(user);
}
}
interface UserRepository extends CrudRepository<So45264894Application.User, Long> {
}
And mapping from /src/main/resources/com/stackoverflow/so45264894/User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.stackoverflow.so45264894" default-access="field">
<class name="com.stackoverflow.so45264894.So45264894Application$User" table="users" dynamic-update="true">
<id name="id" type="java.lang.Long">
<column name="user_id" sql-type="integer"/>
<generator class="identity"/>
</id>
<property name="username" column="username" unique="true"/>
</class>
</hibernate-mapping>
Output:
Hibernate: drop table users if exists
Hibernate: create table users (user_id integer generated by default as identity, username varchar(255), primary key (user_id))
Hibernate: alter table users add constraint UK_r43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: insert into users (username, user_id) values (?, ?) // <- this is userRepository.save() call

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'std' defined in file

package com.nareshit.beans;
public class Address {
private String city,state;
public String toString()
{
return "\n city:"+city+"\nstate:"+state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
package com.nareshit.clients;
import java.awt.Container;
import java.beans.Beans;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import com.nareshit.beans.Student;
public class Test {
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("MyBeans.xml"));
Student std1=(Student)factory.getBean("std");
std1.getStudentDetails();
}
}
package com.nareshit.beans;
public class Student {
private int sid;
private String name;
private String address;
public void getStudentDetails()
{
System.out.println("student id:"+sid);
System.out.println("student name:"+name);
System.out.println("student address:"+address);
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="std" class="com.nareshit.beans.Student">
<property name="std" value="1001"/>
<property name="name" value="mitu"/>
<property name="address" ref="addressObj"/>
</bean>
<bean id="addressObj" class="com.nareshit.beans.Address">
<property name="city" value="bam"/>
<property name="state" value="odisha"/>
</bean>
</beans>
This is the spring setter injection prog. where i am getting error:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'std' defined in file("")
how to solve it?
Please see com.nareshit.beans.Student class. It is having one property named as address which is a type of String. When you are writing the XML,
you are giving one reference type of com.nareshit.beans.Address.
Solution :
1. You can give a String value in the XML for address property.like
ddress property like
<bean id="std" class="com.nareshit.beans.Student">
<property name="std" value="1001"/>
<property name="name" value="mitu"/>
<property name="address" value="SOME ADDRESS"/>
</bean>
2. You can change the type of address property in Student Class like
public class Student{
Address address;
//declaration of rest property
//Some Boiler Plate Code
}

String to Date Conversion in Spring 4.0

I am educating myself on Spring 4.0.0 M3
Following is the code,
Bean
package org.chebus.springs;
import java.util.Date;
public class Traingle {
private String name;
private int height;
private Date date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void drawShape() {
System.out.println(getName() + " Traingle height " + getHeight()
+ " Date = " + getDate());
}
}
Main
ApplicationContext ctx = new ClassPathXmlApplicationContext("org/chebus/springs/Spring.xml");
Traingle traingle = ctx.getBean("traingle",Traingle.class);
traingle.drawShape();
XML Config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id = "traingle" class="org.chebus.springs.Traingle">
<property name="name" value = "RightAngled"/>
<property name="height" value = "20"/>
<property name="date" value = "2013-09-10"/>
</bean>
<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>
</beans>
Exception:
java.lang.IllegalArgumentException: Cannot convert value of type
[org.springframework.beans.propertyeditors.CustomDateEditor] to
required type [java.lang.Class] for property
'customEditors[java.util.Date]': PropertyEditor
[org.springframework.beans.propertyeditors.ClassEditor] returned
inappropriate value of type
[org.springframework.beans.propertyeditors.CustomDateEditor] at
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:260)
at
org.springframework.beans.TypeConverterDelegate.convertToTypedMap(TypeConverterDelegate.java:620)
at
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:205)
at
org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:459)
... 17 more
Not sure where i am going wrong. Appreciate your help. Thanks!
Good catch, this seems to be a new behavior with Spring 4.0+, your code works cleanly with 3.2.x version of Spring.
The reason appears to be because the type of customEditors in
CustomEditorConfigurer has changed with Spring 4.0+. Whereas it was of type Map<String, ?> with Spring 3.2.x it is Map<Class<?>, Class<? extends PropertyEditor>> with Spring 4.0+.
The fix is to instead create a custom PropertyEditorRegistrar, this way:
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;
public class CustomDateEditorRegistrar implements PropertyEditorRegistrar {
#Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
}
}
and to use this in the configuration:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="dateeditor.CustomDateEditorRegistrar"/>
</list>
</property>
</bean>
There is no builtin of Date values by default in spring.
Here you go :
How to initialize a Java Date object in Spring xml configuration file?

Initialising static list using spring

I have a class as below:
public class SensitivityDescription {
private final String measureId;
private final ColumnType type; private final String sensName;
private final SensType sensType;
private final ServicePhase svcPhase;
private final AggregateFunction agFn;
private final String positionEnum;
private static List <SensitivityDescription> senRecordList = new ArrayList<SensitivityDescription> ();
public SensitivityDescription(String measureId, ColumnType type,
String sensName, SensType sensType, ServicePhase svcPhase,
AggregateFunction agFn, String positionEnum) {
super();
this.measureId = measureId;
this.type = type;
this.sensName = sensName;
this.sensType = sensType;
this.svcPhase = svcPhase;
this.agFn = agFn;
this.positionEnum = positionEnum;
}
I need to populate the static senRecordList with objects of the SensitivityDescription class.How do I do this in spring xml.
Based on this link everything is working:
Class
package com.sopovs.moradanen.test;
import java.util.List;
public class SensitivityDescription {
private String name;
private static List<SensitivityDescription> senRecordList;
public SensitivityDescription(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void setSenRecordList(List<SensitivityDescription> senRecordList) {
SensitivityDescription.senRecordList = senRecordList;
}
public static List<SensitivityDescription> getSenRecordList() {
return senRecordList;
}
}
Xml config:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="first" class="com.sopovs.moradanen.test.SensitivityDescription">
<constructor-arg name="name" value="first" />
</bean>
<bean id="second" class="com.sopovs.moradanen.test.SensitivityDescription">
<constructor-arg name="name" value="second" />
</bean>
<bean id="third" class="com.sopovs.moradanen.test.SensitivityDescription">
<constructor-arg name="name" value="third" />
</bean>
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="com.sopovs.moradanen.test.SensitivityDescription.setSenRecordList" />
<property name="arguments">
<list>
<ref bean="first" />
<ref bean="second" />
<ref bean="third" />
</list>
</property>
</bean>
</beans>
And test:
package com.sopovs.moradanen.test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:test.xml")
public class SpringTest {
#Test
public void test() {
assertEquals(3, SensitivityDescription.getSenRecordList().size());
}
}
Spring way of thinking does not play well with your approach.
But you can work around this.
Add a public setter for senRecordList for SensitivityDescription.
Add default constructor
public class SensitivityDescription {
private final String measureId;
...
private static List <SensitivityDescription> senRecordList = new ArrayList<SensitivityDescription> ();
public SensitivityDescription(String measureId,..) {
...
}
/** new code */
public SensitivityDescription() {super();}
public void setSenRecordList(List<SensitivityDescription> senRecordList) {
SensitivityDescription.senRecordList = senRecordList;
}
}
Instance the bean once, that way the list will be injected to your field.
<bean class="...SensitivityDescription">
<property name="senRecordList">
<util:list value-type="...SensitivityDescription">
<bean class="...SensitivityDescription">
<constructor-arg name="name" “measureId”
<value>id1</value>
</constructor-arg>
<constructor-arg name="name" "sensName"
<value>name1</value>
</constructor-arg>
...
</bean>
<bean class="...SensitivityDescription">
<constructor-arg name="name" "measureId"
<value>id2</value>
</constructor-arg>
<constructor-arg name="name" "sensName"
<value>name2</value>
</constructor-arg>
...
</bean>
</util:list>
</property>
</bean>
If this is not a legacy code and you can change it, I suggest defining a singleton for those values and not a static field. Spring will like it better.

How to fetch data dynamically from two tables using HQL (Annotations)? I'm posting the details

I have two tables called STUDENT(studentId,studentName,courseId),COURSE(courseId,courseName) in mysql.I have two .java files for mentioned tables as:
Student.java
package com.vaannila.course;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.*;
#Entity
#Table(name="STUDENT")
public class Student {
private long courseId;
private String studentName;
private long studentId;
public Student() {
}
#Id
#Column(name="studentId")
public long getStudentId() {
return this.studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
#Column(name="studentName", nullable=false)
public String getStudentName() {
return this.studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
#Column(name="courseId")
public long getCourseIdStu() {
return this.courseId;
}
public void setCourseIdStu(long courseId) {
this.courseId = courseId;
}
}
Course.java
package com.vaannila.course;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="COURSE")
public class Course {
private long courseId;
private String courseName;
public Course() {
}
public Course(String courseName) {
this.courseName = courseName;
}
#Id
#Column(name="courseId")
public long getCourseId() {
return this.courseId;
}
public void setCourseId(long courseId) {
this.courseId = courseId;
}
#Column(name="courseName", nullable=false)
public String getCourseName() {
return this.courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
}
The hibernate.cfg.xml file has
<?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/emp</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">aktpl</property>
<property name="show.sql" >true</property>
<mapping class="com.vaannila.course.Course"/>
<mapping class="com.vaannila.course.Student"/>
</session-factory>
And my HQL is:
String hql = "SELECT s.studentName,c.courseName FROM Student s,Course c where s.courseId=c.courseId and s.studentName=':sname'"; (sname is the input here which i set using setParameter())
But i'm having this error:
org.hibernate.QueryException: could not resolve property: courseId of: com.vaannila.course.Student [SELECT s.studentName,c.courseName FROM com.vaannila.course.Student s,com.vaannila.course.Course c where s.courseId=c.courseId and s.studentName=':sname']
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1809)
at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:313)
at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:485)
at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:598)
at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:266)
at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:213)
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:118)
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:114)
at org.hibernate.hql.internal.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:883)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1246)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4252)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3730)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:1923)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:1848)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:782)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:583)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:287)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:235)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:119)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:214)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:192)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1537)
at com.vaannila.course.Main.searchResult(Main.java:184)
at Action.ShowStu.doPost(ShowStu.java:56)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:619)
I want to show a table having attributes 'studentName' along with corresponding 'courseName'.
Please help me out !!! Thank u in advance
The annotated getter in Student is called getCourseIdStu(). This means that the property is named courseIdStu (which is a terriblename, BTW). You must thus use this property name in your HQL.
Moreover, you don't need the single quotes around your parameter. The query should thus be:
select s.studentName, c.courseName from Student s, Course c
where s.courseIdStu = c.courseId and s.studentName = :sname
Note that you missed one important part of Hibernate, which consists in providing an object graph on to of a database, and not just individual objects containing IDs of other objects. You shouldn't have a courseId in Student. Instead, you should have a (many-to-one) association with a Course:
#ManyToOne
#JoinColumn(name = "courseId")
public Course getCourse() {
return this.course;
}
This allows getting a student from the database, and navigating to its course. And the query you had could then be rewritten as:
select s.studentName, c.courseName from Student s
inner join s.course c
where s.studentName = :sname

Resources