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

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

Related

How to add a NameId value to a AttributeValue using OpenSAML2

Using OpenSAML2 how does one create the following XML:
<saml:Attribute Name="urn:mace:dir:attribute-def:eduPersonTargetedID"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
<saml:AttributeValue>
<saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent">c693b1c47a0da7de6518bc30a1bb8d2e44b56980</saml:NameID>
</saml:AttributeValue>
</saml:Attribute>
Extending OpenSAML fixes the issue as it doesn't seem to support NameID values within Attribute Value elements.
The following files are required to implement the AttributeValue.
Builder
package com.blah;
import org.opensaml.common.impl.AbstractSAMLObjectBuilder;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.core.AttributeValue;
public class AttributeValueBuilder extends AbstractSAMLObjectBuilder<AttributeValue>{
public AttributeValueBuilder() {
}
#Override
public AttributeValue buildObject() {
return buildObject(SAMLConstants.SAML20_NS, AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX);
}
#Override
public AttributeValue buildObject(String namespaceURI, String localName, String namespacePrefix) {
return new AttributeValueImpl(namespaceURI, localName, namespacePrefix);
}
}
Implementation
package com.blah;
import java.util.ArrayList;
import java.util.List;
import org.opensaml.common.impl.AbstractSAMLObject;
import org.opensaml.xml.XMLObject;
public class AttributeValueImpl extends AbstractSAMLObject implements org.opensaml.saml2.core.AttributeValue{
protected AttributeValueImpl(String namespaceURI, String elementLocalName,
String namespacePrefix) {
super(namespaceURI, elementLocalName, namespacePrefix);
}
private List<XMLObject> children = new ArrayList<XMLObject>();
#Override
public List<XMLObject> getOrderedChildren() {
return children;
}
}
Marshaller
package com.blah;
import org.opensaml.common.impl.AbstractSAMLObjectMarshaller;
public class AttributeValueMarshaller extends AbstractSAMLObjectMarshaller {
}
Unmarshaller
package com.blah;
import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.UnmarshallingException;
public class AttributeValueUnmarshaller extends AbstractSAMLObjectUnmarshaller {
#Override
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
throws UnmarshallingException {
AttributeValueImpl attributeValue = (AttributeValueImpl) parentSAMLObject;
attributeValue.getOrderedChildren().add(childSAMLObject);
}
}
Once these files are included they need to be added to the OpenSAML bootstrapping configuration file saml2-assertion-config.xml (I copied it from the OpenSAML jar and placed it into the root of the Java src):
<!-- AttributeValue -->
<ObjectProvider qualifiedName="saml2:AttributeValue">
<BuilderClass className="com.blah.AttributeValueBuilder" />
<MarshallingClass className="com.blah.AttributeValueMarshaller" />
<UnmarshallingClass className="com.blah.AttributeValueUnmarshaller" />
</ObjectProvider>
<ObjectProvider qualifiedName="saml2:AttributeValueType">
<BuilderClass className="com.blah.AttributeValueBuilder" />
<MarshallingClass className="com.blah.AttributeValueMarshaller" />
<UnmarshallingClass className="com.blah.AttributeValueUnmarshaller" />
</ObjectProvider>
It is now possible to add any element to the Attribute Value body.
private static XMLObject createAttributeValueNameId(String value) throws ConfigurationException {
XMLObjectBuilder<AttributeValueImpl> attrBuilder = getSamlBuilder().getBuilder(AttributeValue.DEFAULT_ELEMENT_NAME);
AttributeValueImpl attributeValue = attrBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME);
XMLObjectBuilder<AttributeValue> builder = getSamlBuilder().getBuilder(NameID.DEFAULT_ELEMENT_NAME);
NameID nameId = (NameID) builder.buildObject(NameID.DEFAULT_ELEMENT_NAME);
nameId.setFormat(NameID.UNSPECIFIED);
nameId.setValue(value);
attributeValue.getOrderedChildren().add(nameId);
return attributeValue;
}

Spring JDBC update without commit

I have a simple table "employee" defined as:
create table employee (id int, name varchar2(40));
I want to write an application to insert values in it and commit only after all values are inserted. Here is my code:
Employee.java:
package com.empl;
public class Employee {
private int id;
private String name;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
EmployeeDAO.java:
package com.empl;
import javax.sql.DataSource;
public interface EmployeeDAO {
public void setDataSource(DataSource dataSource);
public void create(int id, String name);
}
EmployeeJDBCTemplate.java:
package com.empl;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeJDBCTemplate {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public DataSource getDataSource() {
return dataSource;
}
public void create(int id, String name) {
String SQL = "insert into employee (id, name) values (?, ?)";
jdbcTemplateObject.update(SQL, id, name);
}
}
MainApp.java:
package com.empl;
import java.sql.SQLException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String args[]) throws SQLException {
ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");
EmployeeJDBCTemplate employeeJDBCTemplate =
(EmployeeJDBCTemplate) context.getBean("employeeJDBCTemplate");
employeeJDBCTemplate.getDataSource().getConnection().
setAutoCommit(false);
employeeJDBCTemplate.create(1, "E1");
employeeJDBCTemplate.create(2, "E2");
}
}
Beans.xml:
<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-3.0.xsd ">
<bean id = "dataSource" class =
"org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value =
"oracle.jdbc.driver.OracleDriver"></property>
<property name = "url" value =
"jdbc:oracle:thin:#localhost:1521/xe"></property>
<property name = "username" value = "sys as sysdba"></property>
<property name = "password" value = "pass"></property>
</bean>
<bean id = "employeeJDBCTemplate" class =
"com.empl.EmployeeJDBCTemplate">
<property name = "dataSource" ref = "dataSource"></property>
</bean>
</beans>
I executed the code but when I enter SQLPlus and type the rollback; command, the records are still in the table.
I saw related questions but nothing seems to work.

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

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.

What are the depencencies to be added to get the XML output in spring-mvc?

What are the maven dependencies need to be added to get the XML output without configuring content negotiation view resolver and managers. By using the default Message Converters based on jars on classpath (output based on accept headers). I am able to get the JSON output by having jackson-databind dependency on the classpath. For XML I am using
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
dependencies - I am unable to get the XML output. DO I need configure any Marshallers like Jaxb2Marsahllar as a bean in the configuration file. Can Any post the maven dependencies for JAXB2.
My Entity class:
package com.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name = "Employee")
#XmlRootElement
public class Employee {
public Employee() {
}
public Employee(Integer empno, String name, String dept, Double salary) {
this.empno = empno;
this.name = name;
this.dept = dept;
this.salary = salary;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer empno;
#Size(min = 1, max = 30)
#NotEmpty
private String name;
#NotEmpty
#Size(min = 1, max = 30)
private String dept;
/*
* #NotEmpty - cannot be set to double - supports String Collection Map
* arrays
*/
private Double salary;
#XmlAttribute
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
#XmlElement
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee [empno=" + empno + ", name=" + name + ", dept=" + dept
+ ", salary=" + salary + "]";
}
}
My Controller Class:
#Controller
public class EmployeeController {
#Autowired
EmployeeRepository employeeRepository;
#RequestMapping(value = "/employees", method=RequestMethod.GET,
produces= {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public #ResponseBody List<Employee> findAllXml(){
return employeeRepository.findAll();
}
}
Please Can any one say Whether the dependencies are enough ? What needs to be added..
put #XMLElement on set methods.
public Integer getEmpno() {
return empno;
}
#XmlAttribute
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
or you can use Spring Marshalling View of spring-oxm.jar
<bean id="xmlViewer"
class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.model.Employee</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
Update:1
Also findAll is returning list that list needs to be accomodated in a parent tag like
<Employees>
<Employee />
<Employee />
</Employees>
so you need to define a class that has an #XMLElement entity as List<Employees> create object of it put the data in it and return that object.
I found the answer to 406 exception
Problem was needed an extra configuration for Message Converters for XML output.
For XML Output, we need to Added a Message Converter to the list of Message converters of RequestMappingHandlerAdapter
But for JSON we dont need to do this explictly, based on the jackson-databind dependencies on the classpath, we can able get the JSON output. But for xml , we need to add a message converter (MarshallingHttpMessageConverter) .
Example: Using Java Based Config: configuring RequestMappingHandlerAdapter as a bean and adding required Message Converters...
#Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
List<HttpMessageConverter<?>> converters = new ArrayList();
converters.add(new MarshallingHttpMessageConverter(
new XStreamMarshaller()));
converters.add(new MappingJackson2HttpMessageConverter());
adapter.setMessageConverters(converters);
return adapter;
}
I am using XStream Marshaller, so need to add its dependencies as well
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.8</version>
</dependency>
Example Tests:
#Test
public void testXml() throws Exception {
this.mvc.perform(get("/employees/xml").accept(APPLICATION_XML))
.andDo(print())
.andExpect(content().contentType("application/xml"));
}
#Test
public void testJson() throws Exception {
this.mvc.perform(get("/employees/json").accept(APPLICATION_JSON))
.andDo(print())
.andExpect(content().contentType("application/json"));
}
Please post if you know any other way of doing this.
useful link: Spring XML 406 error

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