Getting java.sql.SQLException: Invalid column name even though column with same name are in table. what can be a reason?
I am trying to call sp with below code:
Session session = HibernateUtil.getSessionFactory().openSession();
Query query = session.getNamedQuery("EMPLOYEE.PRC_HB_EMP_SP1");
query.setParameter("IN_EMPID", empId);
List<Employee> empList = query.list();
System.out.println(empList);
Entity class Employee:
#Entity
#Table(name = "EMPLOYEE")
//#org.hibernate.annotations.NamedNativeQuery(name = "EMPLOYEE.PRC_HB_EMP_SP1", query = "call PRC_HB_EMP_SP1(?,:IN_EMPID)", callable = true, resultClass = Employee.class)
#org.hibernate.annotations.NamedNativeQuery(name = "EMPLOYEE.PRC_HB_EMP_SP1", query = "call PRC_HB_EMP_SP1(?,:IN_EMPID)", callable = true, resultClass = Employee.class)
public class Employee implements Serializable {
private static final long serialVersionUID = -723583058586873479L;
#Id
#Column(name = "EMPID")
private Integer empId;
#Column(name = "EMPNAME")
private String empName;
#Column(name = "ADDRESS")
private String empAddress;
#Column(name = "SALARY")
private Long salary;
#Column(name = "EMPAGE")
private Integer empAge;
............
}
here is sp:
create or replace PROCEDURE PRC_HB_EMP_SP1
(
Out_value OUT SYS_REFCURSOR,
IN_EMPID NUMBER
)
AS
BEGIN
open Out_value for
SELECT EMPID,EMPNAME
FROM EMPLOYEE
WHERE EMPID = IN_EMPID;
END PRC_HB_EMP_SP1;
Stacktrace:
SEVERE: Servlet.service() for servlet [sdnext] in context with path [/sdnext] threw exception [Request processing failed; nested exception is org.hibernate.exception.GenericJDBCException: could not execute query] with root cause
java.sql.SQLException: Invalid column name
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:269)
at oracle.jdbc.driver.OracleStatement.get_column_index(OracleStatement.java:5971)
at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:1527)
at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:1482)
at org.hibernate.type.StringType.get(StringType.java:18)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:154)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:81)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2101)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1380)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1308)
at org.hibernate.loader.Loader.getRow(Loader.java:1206)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:580)
at org.hibernate.loader.Loader.doQuery(Loader.java:701)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2213)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1695)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:152)
at com.dineshonjava.controller.EmployeeController.getEmployeeDetail(EmployeeController.java:160)
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.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Your mappings contain columns ADDRESS,SALARY and EMPAGE but those are missing from your SP.You need to include those in your statement.
Related
I have three tables, tables in sql servers , which Solved had been created by many-many relationship.
Solved table has a composite key, so i wrote a SolvedKey for its composite key SolvedKey
#Embeddable
public class SolvedKey implements Serializable {
#Column(name="userMailer")
private String usermail;
#Column(name="challengeID")
private int challengeid;
My Entity:
Solved: solved entity
#Entity
#Table(name = "Solved")
public class Solved {
#EmbeddedId
private SolvedKey solvedKey;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("usermail")
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("challengeid")
private Challenge chall;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern="yyyy/mm/dd")
#Column(name = "dateSolved")
private Date dateSolved;
User: user entity
#Entity
#Table(name="Users")
public class User implements Serializable{
// declare field
#Id
#Column(name="Mail")
private String mail;
#Column(name="Username")
private String userName;
#Column(name="Password")
private String passWord;
#Column(name ="Validation")
private boolean valid;
#Column(name="Isadmin")
#Nullable
private boolean isAdmin;
#OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<Solved> challs = new ArrayList<Solved>();
Challenge: Challenge entity
#Entity
#Table(name="Challenges")
public class Challenge implements Serializable {
#Id
#GeneratedValue
#Column(name = "ID")
private int id;
#Column(name="challengName")
private String challengeName;
#Column(name = "score")
private int score;
#Column(name="fileAttach")
private String fileAttach;
#Column(name="description")
private String description;
#Column(name="hint")
private String hint;
#Column(name="major")
private String major;
#Column(name = "flag")
private String flag;
#OneToMany(mappedBy = "chall",cascade = CascadeType.ALL)
private List<Solved> users = new ArrayList<Solved>();
But i don't sure that it's correct. And when i try to request list of challenges of a user:
public void getListSolved(String mail){
User user = getUserByMail(mail);
System.out.println("User: " + user.getUserName());
System.out.println("Challs: " + user.getChalls());
user.getChalls().forEach(
(chall) -> System.out.println("Chall: "+ chall.getChall().getChallengeName()+ " | Date: " + chall.getDateSolved())
);
}
It failed because of the invalid column "user_Mail" , but i can't find where is that column in my code.
HTTP Status 500 - Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
type Exception report
message Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
root cause
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1893)
org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:555)
org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:260)
org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:551)
org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:140)
org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:526)
java.lang.String.valueOf(Unknown Source)
java.lang.StringBuilder.append(Unknown Source)
wargame.dao.UserDAO.getListSolved(UserDAO.java:154)
wargame.mainController.UserController.userInfo(UserController.java:285)
wargame.mainController.UserController$$FastClassByCGLIB$$b3d9caac.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:710)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:643)
wargame.mainController.UserController$$EnhancerByCGLIB$$9bfbb734.userInfo(<generated>)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
root cause
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'user_Mail'.
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1458)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:388)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:338)
com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4016)
com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1414)
com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:176)
com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:151)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:281)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1893)
org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:555)
org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:260)
org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:551)
org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:140)
org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:526)
java.lang.String.valueOf(Unknown Source)
java.lang.StringBuilder.append(Unknown Source)
wargame.dao.UserDAO.getListSolved(UserDAO.java:154)
wargame.mainController.UserController.userInfo(UserController.java:285)
wargame.mainController.UserController$$FastClassByCGLIB$$b3d9caac.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:710)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:643)
wargame.mainController.UserController$$EnhancerByCGLIB$$9bfbb734.userInfo(<generated>)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
If you want reference column of User in Solved entity to be usermail, I suggest to design your entity as following. Main difference is that instead of having User and Challenge in Solved use it in SolvedKey as reference entity and don't forget to override equal and hashCode in SolvedKey.
SolvedKey Entity
#Embeddable
public class SolvedKey implements Serializable {
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "usermail" , referencedColumnName = "Mail")
private User user;
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Challenge chall;
Soved Entity
#Entity
public class Solved {
#EmbeddedId
private SolvedKey solvedKey;
User -> to Solved relationship
#Entity
public class User {
#OneToMany(mappedBy = "solvedKey.user",cascade = CascadeType.ALL)
private List<Solved> challs = new ArrayList<Solved>();
Challenge -> to Solved relationship
#Entity
public class Challenge {
#OneToMany(mappedBy = "solvedKey.chall",cascade = CascadeType.ALL)
private List<Solved> users = new ArrayList<Solved>();
When I execute spring boot app , hibernate ddl is as following.
create table Solved (
dateSolved date,
chall_ID integer not null,
usermail varchar(255) not null,
primary key (chall_ID, usermail)
)
alter table Solved
add constraint FKx2kp7aliijq7g7xq0j4huqb4
foreign key (chall_ID)
references Challenge
alter table Solved
add constraint FKhycu95r961terhbackiixqwns
foreign key (usermail)
references User
guys i am making a grid library that uses hibernate and spring mvc to read data from db .. i have 2 table employee which has EPMID, EMPNAME, EMPAGE, SALARY, ADDRESS, department_id (refrences to department_id in department table ) and department which has department_id and name ... here is the Department.java
public class Department {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "department_id")
private int depId;
#Column(name = "name")
private String depName;
#OneToMany(mappedBy="department",cascade = { CascadeType.ALL }, orphanRemoval=true)
private List<Employee> employees;}
Employee.java
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "EMPID")
private int empId;
#Column(name = "EMPNAME")
private String empName;
#Column(name = "ADDRESS")
private String empAddress;
#Column(name = "SALARY")
private String salary;
#Column(name = "EMPAGE")
private int empAge;
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name="department_id")
private Department department;}
and the function that adds teh employee in service
public void addEmployee(String[] list, Employee employee) {
employee.getDepartment().setDepId(Integer.parseInt(list[3]));
employee.setEmpName(list[2]);
employee.setEmpAge(Integer.parseInt(list[4]));
employee.setEmpAddress(list[6]);
employee.setSalary(list[1]);
this.employeeDao.addOrEditEmployee(employee);
everything goes fine without that line employee.getDepartment().setDepId(Integer.parseInt(list[3])); but i want to add foreign key to reference on the primary one ..
here is the exception
SEVERE: Servlet.service() for servlet [sdnext] in context with path [/Spring3HibernateApp1] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.dineshonjava.service.EmployeeServiceImpl.addEmployee(EmployeeServiceImpl.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy30.addEmployee(Unknown Source)
at com.dineshonjava.controller.EmployeeController.doPostSave(EmployeeController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Do NOT maintain foreign keys using something like this
employee.getDepartment().setDepId(Integer.parseInt(list[3]));
Instead do
Department dept = departmentDao.findById(Integer.parseInt(list[3]));
employee.setDepartment(dept);
Hibernate will now create the database relationship between department and employee by inserting the department_id in the employee table.
P.S. I am assuming some class and method names as I do not have all of your code.
Regarding the NPE
I believe you received a null pointer exception because employee doesn't have a department at that point.
employee.getDepartment().setDepId(...
I have a simple (I guess) problem but I have no idea what's wrong.
I'm trying to execute following HQL query:
String hql = "delete CinemaProgramme program where program.id in (select q.id from CinemaProgramme q left join q.timetable a " +
"where a > :today)";
and I get an error:
java.lang.UnsupportedOperationException: References to collections must be define a SQL alias
java.lang.UnsupportedOperationException: References to collections must be define a SQL alias
at org.hibernate.persister.collection.ElementPropertyMapping.toColumns(ElementPropertyMapping.java:69)
at org.hibernate.persister.collection.AbstractCollectionPersister.toColumns(AbstractCollectionPersister.java:1541)
at org.hibernate.hql.ast.tree.FromElement.getIdentityColumn(FromElement.java:348)
at org.hibernate.hql.ast.tree.IdentNode.resolveAsAlias(IdentNode.java:154)
at org.hibernate.hql.ast.tree.IdentNode.resolve(IdentNode.java:100)
at org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:117)
at org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:113)
at org.hibernate.hql.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:880)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.addrExpr(HqlSqlBaseWalker.java:4834)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1326)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4471)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3992)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2047)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:831)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:617)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.collectionFunctionOrSubselect(HqlSqlBaseWalker.java:4696)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.inRhs(HqlSqlBaseWalker.java:4596)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4261)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2047)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:831)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.deleteStatement(HqlSqlBaseWalker.java:455)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:260)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
at movies.database.CinemaListDao.deleteOldData(CinemaListDao.java:97)
at movies.controller.MovieController.viewRegistration(MovieController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at movies.encoding.UTF8Filter.doFilter(UTF8Filter.java:14)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
However, when I just try to execute the query without the delete:
String hql = "from CinemaProgramme program where program.id in (select q.id from CinemaProgramme q left join q.timetable a " +
"where a > :today)";
Then it works fine....
Subquery itself also works correctly:
String hql = "select q.id from CinemaProgramme q left join q.timetable a " +
"where a > :today)"
........
#Entity
#Table(name = "cinema_programme")
public class CinemaProgramme implements Serializable {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#ElementCollection
#LazyCollection(LazyCollectionOption.FALSE)
#JoinColumn(name = "programme_id")
private List<Date> timetable;
#ManyToOne(cascade= CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "movie_id")
private Movie movie;
}
Any ideas?
PS.
delete from CinemaProgramme AS program - also doesn't work
There are not enough details about the entities. Does this work:
delete CinemaProgramme where id in (select q.id from CinemaProgramme q left join q.timetable a where a > :today)
OR
delete CinemaProgramme where timetable > :today
I am writing an application where i am trying to make an example on hibernate search with Lucene.
In my database, i got an array named A_ROLE witch contains an ID field and a NAME field. Into this array i have store the data bellow:
1 - Agalloh
2 - Rorry Galaher
3 - Isis Isis
My entity class looks like this:
#Entity
#Table(name="A_ROLE")
#NamedQuery(name="ARole.findAll", query="SELECT a FROM ARole a")
#Indexed
public class ARole implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#DocumentId
#SequenceGenerator(name="A_ROLE_ID_GENERATOR", sequenceName="A_ROLE_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="A_ROLE_ID_GENERATOR")
#Column(unique=true, nullable=false, precision=38)
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
//#NumericField
private long id;
#Column(length=50)
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String name;
//bi-directional many-to-many association to APermission
#ManyToMany
#JoinTable(
name="A_ROLE_PERMISSION"
, joinColumns={
#JoinColumn(name="ROLE_ID", nullable=false)
}
, inverseJoinColumns={
#JoinColumn(name="PERMISSION_ID", nullable=false)
}
)
private List<APermission> APermissions;
//bi-directional many-to-many association to AUser
#ManyToMany(mappedBy="ARoles")
private List<AUser> AUsers;
constructor, getters and setters
and i have create an interface named DataBaseExchanges which contains a method lucinExample(). This method is responsible for the hibernate search and its implementation is being from the class bellow
import ec.ep.europarl.appdif.db.entity.ARole;
import ec.ep.europarl.appdif.service.DataBaseExchanges;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service("dataSearch")
public class DataBaseExchangesImpl implements DataBaseExchanges {
#PersistenceContext
public EntityManager em;
#Override
#Transactional
public void lucinExample() {
FullTextEntityManager fullTextEntityManager =
org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
//em.getTransaction().begin();
QueryBuilder qb =
fullTextEntityManager.getSearchFactory().buildQueryBuilder()
.forEntity(ARole.class).get();
org.apache.lucene.search.Query query = qb
.keyword()
.onFields("name")
.matching("agalloh")
.createQuery();
// wrap Lucene query in a javax.persistence.Query
org.hibernate.search.jpa.FullTextQuery persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, ARole.class);
// execute search
List result = persistenceQuery.getResultList();
em.close();
}
}
i call this method from a controller, where i have #Autowird the above mentioned interface.
When i debug the above functionality it stops at this line of the implementation code:
org.hibernate.search.jpa.FullTextQuery persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, ARole.class);
with error report:
SEVERE: Servlet.service() for servlet [appdif] in context with path [] threw exception
[Handler processing failed; nested exception is java.lang.NoClassDefFoundError:
org/hibernate/BasicQueryContract] with root cause
java.lang.ClassNotFoundException: org.hibernate.BasicQueryContract
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at
org.hibernate.search.impl.FullTextSessionImpl.createFullTextQuery
(FullTextSessionImpl.java:81)
at
org.hibernate.search.jpa.impl.FullTextEntityManagerImpl.
createFullTextQuery(FullTextEntityManagerImpl.java:112)
at
ec.ep.europarl.appdif.service.impl.DataBaseExchangesImpl.
lucinExample(DataBaseExchangesImpl.java:43)
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.springframework.aop.support.AopUtils.
invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy102.lucinExample(Unknown Source)
at ec.ep.europarl.appdif.web.controllers.HomeController.home(HomeController.java:27)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
I can't figure out what the problem is, at my maven dependencies i have include hibernate search 4.5.0.Final.
Please can anyone help on this?
Finally i got answer to my question, i realize that i haven't include this in pom file:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.4.Final</version>
</dependency>
I am trying to save details of users through registration form.i am using 3 model classes one is user,roles,person.The primary key in user table is foreign key in both roles and person tables.
I used OneToOne mapping in both roles and person.
Here is my User Model Class
#Entity
#Table(name="Login")
public class User{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String username;
private String password;
//Rest are getters and Setters
My Person model class is
#Entity
public class Person{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int pid;
private String email;
private String Gender;
#OneToOne
private User uid;
My Roles table is
#Entity
#Table(name = "Auth")
public class Roles implements Serializable{
#Id
private int id;
#Column(name = "Authority")
private String role;
#OneToOne
private User u_id;
In my dao i am trying to insert these..
public static boolean register(Person p,User u,Roles r)
{
Session s=sf.openSession();
s.beginTransaction();
s.save(u);
s.save(p);
s.save(r);
s.getTransaction().commit();
s.flush();
s.close();
return true;
The Exception I am Getting is
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/spring7]
threw exception [Request processing failed;
nested exception is org.hibernate.exception.ConstraintViolationException:
Could not execute JDBC batch update]
with root cause java.sql.BatchUpdateException: ORA-00001:
unique constraint (OVERFLOW.SYS_C004914) violated
at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:343)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10657)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.rahul.dao.Dao.register(Dao.java:40)
at com.rahul.controller.LoginController.reg(LoginController.java:55)
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:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
from the inormation given i can find out below
#GeneratedValue(strategy = GenerationType.AUTO) is missing for id field in Role entity. Though i think auto is default value.But still its worth to cross check.
As error clearly says its unique key constraint voilation. My guess is there is some check constraint defined in defined in your DB. Duplicate values are allowed for foreign keys.