I've two entities and I'm using JPAContainer but I don't know how can use to do a relationship with these 2 entities.
here my code
#Entity
#Table(name="curriculum")
public class Curriculum implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long idCurriculum;
#Temporal(TemporalType.DATE)
private Date dataCad;
#Size(min=5, max=50)
#NotNull
#NotEmpty
private String nome;
#NotEmpty
private String sexo;
#Email
#NotEmpty
#NotNull
#Size(max=250)
#Column(unique=true)
private String email;
#NotNull
#NotEmpty
#Size(min=14, max=14)
#Column(unique=true)
private String cpf;
}
#Entity
#Table(name="curriculum2")
public class Curriculum2 implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long idC2; //NOT NULL AUTO_INCREMENT,
#NotNull #OneToOne #JoinColumn(name="cpf")
private Curriculum curriculum; //NOT NULL,
#NotNull #Temporal(TemporalType.DATE)
private Date dataNasceu; //NOT NULL,
#NotNull #NotEmpty #Size(min=5, max=50)
private String cidade; //` varchar(50) NOT NULL,
#NotNull #NotEmpty #Size(min=5, max=50)
private String endereco; //` varchar(50) NOT NULL,
#NotNull
private int numero; //` int(11) NOT NULL,
#NotNull #NotEmpty #Size(min=5, max=50)
private String bairro; //` varchar(50) NOT NULL,
}
/** here app UI */
/** datasource */
private final CustomJPAContainer<Curriculum2> datasource = new CustomJPAContainer<Curriculum2>(Curriculum2.class);
private final CustomJPAContainer<Curriculum> dsCurriculum = new CustomJPAContainer<Curriculum>(Curriculum.class);
/** beans */
private final Curriculum2 bean = new Curriculum2();
private final Curriculum curriculum = dsCurriculum.getItem(22L).getEntity();
/** beanfieldgroup validation */
private final BeanFieldGroup<Curriculum2> binder = new BeanFieldGroup<Curriculum2>(Curriculum2.class);
public VerticalLayout buildLayout() {
//mainlayout
mainLayout = new VerticalLayout();
mainLayout.setSpacing(true);
mainLayout.setMargin(true);
//tab
tab = new TabSheet();
tab.setSizeUndefined();
mainLayout.addComponent(tab);
//tab1
vLayout_tab1 = new VerticalLayout();
vLayout_tab1.setMargin(true);
vLayout_tab1.setSpacing(true);
binder.setItemDataSource(bean);
Field<?> field = null;
//data nascimento
field = binder.buildAndBind("Data nascimento", "dataNasceu", PopupDateField.class);
dataNasceu = (PopupDateField) field;
dataNasceu.setDateFormat("dd/MM/yyyy");
vLayout_tab1.addComponent(dataNasceu);
//cidade
field = binder.buildAndBind("Cidade", "cidade", TextUpper.class);
cidade = (TextUpper) field;
cidade.setMaxLength(50);
cidade.setWidth("10cm");
vLayout_tab1.addComponent(cidade);
//endereco
field = binder.buildAndBind("Endereço", "endereco", TextUpper.class);
endereco = (TextUpper) field;
endereco.setMaxLength(50);
endereco.setWidth("10cm");
vLayout_tab1.addComponent(endereco);
//numero
field = binder.buildAndBind("Número", "numero");
numero = (TextField) field;
numero.setWidth("2cm");
numero.selectAll();
numero.addStyleName("numeros");
vLayout_tab1.addComponent(numero);
//bairro
field = binder.buildAndBind("Bairro", "bairro", TextUpper.class);
bairro = (TextUpper) field;
bairro.setWidth("10cm");
vLayout_tab1.addComponent(bairro);
}
/** exception */
15:53:19,600 DEBUG [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE) [n/a]
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2834)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2366)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2350)
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.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy30.executeUpdate(Unknown Source)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2870)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3381)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:320)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
at org.hibernate.ejb.event.EJB3MergeEventListener.saveWithGeneratedId(EJB3MergeEventListener.java:71)
at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:236)
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:216)
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:154)
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:76)
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:904)
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:888)
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:892)
at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:879)
at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider$1.run(MutableLocalEntityProvider.java:141)
at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider.runInTransaction(MutableLocalEntityProvider.java:120)
at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider.addEntity(MutableLocalEntityProvider.java:137)
at com.vaadin.addon.jpacontainer.provider.CachingMutableLocalEntityProvider.addEntity(CachingMutableLocalEntityProvider.java:164)
at com.vaadin.addon.jpacontainer.JPAContainer.addEntity(JPAContainer.java:1113)
at br.ind.ibg.views.InformacoesView.buttonClick(InformacoesView.java:328)
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 com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:969)
at com.vaadin.ui.Button.fireClick(Button.java:368)
at com.vaadin.ui.Button$1.click(Button.java:57)
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 com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:168)
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:118)
at com.vaadin.server.communication.ServerRpcHandler.handleBurst(ServerRpcHandler.java:207)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:111)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:91)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
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(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
15:53:19,602 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - SQL Error: 1452, SQLState: 23000
15:53:19,602 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE)
15:53:19,603 DEBUG [org.hibernate.ejb.AbstractEntityManagerImpl] - Mark transaction for rollback
15:53:19,603 DEBUG [org.hibernate.engine.transaction.spi.AbstractTransactionImpl] - rolling back
15:53:19,678 DEBUG [org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction] - rolled JDBC Connection
15:53:19,679 DEBUG [org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction] - re-enabling autocommit
How I can persist with JPAContainer these 2 entities ?
This is Hibernate 101.
For proof-of-concept this is easy. You're best bet is to use Spring transaction + hibernate + dao model
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'm using Glassfish 4 and JPA 2.1 ans Netbeans 7.
In order to generate the table I have these beans :
#Entity
public class Myuser implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long myuserId;
#Column(name = "firstname")
private String firstName;
#Column(name = "lastname")
private String lastName;
#Column(name = "mail")
private String mail;
#Column(name = "password")
private String password;
#OneToMany #JoinColumn(name = "user", insertable=false, updatable=false)
private Collection<Course> courses;
//...
}
#Entity
public class Course implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long courseId;
#Column(name = "coursename")
private String courseName;
#Column(name = "duration")
private int duration;
#Column(name = "description")
private String description;
#ManyToOne #JoinColumn(name="myuserId", insertable=false, updatable = false)
private Myuser user;
#OneToMany #JoinColumn(name ="course", insertable=false, updatable = false)
private Collection<Mymodule> modules;
//...
}
And I got this server Database log message :
Avertissement: Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Erreur de syntaxe : Encountered "user" at line 1, column 134.
Error Code: -1
Call: CREATE TABLE COURSE (COURSEID BIGINT NOT NULL, coursename VARCHAR(255), description VARCHAR(255), duration INTEGER, myuserId BIGINT, user BIGINT, PRIMARY KEY (COURSEID))
Query: DataModifyQuery(sql="CREATE TABLE COURSE (COURSEID BIGINT NOT NULL, coursename VARCHAR(255), description VARCHAR(255), duration INTEGER, myuserId BIGINT, user BIGINT, PRIMARY KEY (COURSEID))")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:679)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1995)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeNoSelectCall(DatasourceCallQueryMechanism.java:271)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeNoSelect(DatasourceCallQueryMechanism.java:251)
at org.eclipse.persistence.queries.DataModifyQuery.executeDatabaseQuery(DataModifyQuery.java:85)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:3207)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1797)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1779)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1730)
at org.eclipse.persistence.internal.sessions.AbstractSession.priviledgedExecuteNonSelectingCall(AbstractSession.java:5000)
at org.eclipse.persistence.tools.schemaframework.DatabaseObjectDefinition.createOnDatabase(DatabaseObjectDefinition.java:141)
at org.eclipse.persistence.tools.schemaframework.SchemaManager.createObject(SchemaManager.java:223)
at org.eclipse.persistence.tools.schemaframework.TableCreator.createTables(TableCreator.java:165)
at org.eclipse.persistence.tools.schemaframework.TableCreator.createTables(TableCreator.java:142)
at org.eclipse.persistence.tools.schemaframework.TableCreator.createTables(TableCreator.java:134)
at org.eclipse.persistence.tools.schemaframework.SchemaManager.createDefaultTables(SchemaManager.java:1032)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.generateDefaultTables(EntityManagerFactoryProvider.java:102)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.writeDDLToDatabase(EntityManagerSetupImpl.java:3937)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.writeMetadataDDLToDatabase(EntityManagerSetupImpl.java:3992)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.writeDDL(EntityManagerSetupImpl.java:3903)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.writeDDL(EntityManagerSetupImpl.java:3783)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:724)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:204)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:182)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getDatabaseSession(EntityManagerFactoryImpl.java:527)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:358)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:199)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:107)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:431)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.sql.SQLSyntaxErrorException: Erreur de syntaxe : Encountered "user" at line 1, column 134.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.Connection.prepareStatement(Unknown Source)
at com.sun.gjc.spi.base.ConnectionHolder.prepareStatement(ConnectionHolder.java:586)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareCachedStatement(ConnectionWrapper40.java:255)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareCachedStatement(ConnectionWrapper40.java:52)
at com.sun.gjc.spi.ManagedConnectionImpl.prepareCachedStatement(ManagedConnectionImpl.java:992)
at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.prepareStatement(ConnectionWrapper40.java:173)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.prepareStatement(DatabaseAccessor.java:1551)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.prepareStatement(DatabaseAccessor.java:1500)
at org.eclipse.persistence.internal.databaseaccess.DatabaseCall.prepareStatement(DatabaseCall.java:778)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:619)
... 71 more
Caused by: org.apache.derby.client.am.SqlException: Erreur de syntaxe : Encountered "user" at line 1, column 134.
at org.apache.derby.client.am.Statement.completeSqlca(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.parsePrepareError(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.parsePRPSQLSTTreply(Unknown Source)
at org.apache.derby.client.net.NetStatementReply.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.net.StatementReply.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.net.NetStatement.readPrepareDescribeOutput_(Unknown Source)
at org.apache.derby.client.am.Statement.readPrepareDescribeOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.readPrepareDescribeInputOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.flowPrepareDescribeInputOutput(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.prepare(Unknown Source)
at org.apache.derby.client.am.Connection.prepareStatementX(Unknown Source)
... 81 more
It looks like the the column "user" is the problem. "USER" is a reserved word in Derby and as such should probably not be used as a column name. If you MUST use it as a column name make sure to enclose it in quotes as shown in this question.
I guess 'user' is a database keyword and cannot be used! You must change your mapping to use a different column name.
i have this error in my code when i m trying to call save method this method is woking fine while i m on JBoss server , now i move on tomcat server 7
ERROR: HHH000123: IllegalArgumentException in class: com.sb.core.beans.CompanyStudies,setter method of property: studyId
Aug 5, 2013 9:24:52 AM org.hibernate.property.BasicPropertyAccessor$BasicSetter set
ERROR: HHH000091: Expected type: java.lang.Integer, actual value: org.hibernate.id.IdentifierGeneratorHelper$2
org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.sb.core.beans.CompanyStudies.studyId
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:119)
at org.hibernate.mapping.Component$ValueGenerationPlan.execute(Component.java:436)
at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:121)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:120)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:642)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:635)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:631)
at com.sb.core.dao.impl.CompanyStudiesDAOImpl.addCompanyStudy(CompanyStudiesDAOImpl.java:31)
at com.sb.core.businesslogic.impl.CompanyStudiesServiceImpl.addCompanyStudy(CompanyStudiesServiceImpl.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
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.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy42.addCompanyStudy(Unknown Source)
at com.sb.web.managed.beans.CompanyManagedBean.saveCompanyDetail(CompanyManagedBean.java:3612)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:737)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:467)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246)
at com.sun.el.parser.AstValue.invoke(AstValue.java:228)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
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:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
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:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:65)
my Bean class is
#Entity
#Table(name = "company_studies", catalog = "studybuddyDB")
public class CompanyStudies implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
// Fields
private Integer studyId = 0;
private CompanyDetail companyDetail;
private int isActive;
/** default constructor */
public CompanyStudies() {
}
/** full constructor */
public CompanyStudies(CompanyDetail companyDetail,int isActive) {
this.setCompanyDetail(companyDetail);
this.setIsActive(isActive);*/
this.companyDetail = companyDetail;
this.isActive = isActive;
}
// Property accessors
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "study_id", unique = true, nullable = false )
public Integer getStudyId() {
return studyId;
}
public void setStudyId(Integer studyId) {
this.studyId = studyId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "company_detail_id")
public CompanyDetail getCompanyDetail() {
return companyDetail;
}
public void setCompanyDetail(CompanyDetail companyDetail) {
this.companyDetail = companyDetail;
}
#Id
#Column(name = "isActive", nullable = false)
public int getIsActive() {
return isActive;
}
public void setIsActive(int isActive) {
this.isActive = isActive;
}
}
please help me out to fix this issue
I have came across the same error,
After some research I came to conclusion that it is depends on two things.
What DB you are using plus
What #GenericGenerator - what strategy you are using.
I was able to resolved issue with following configuration.
DB - MySQL
Changed strategy to increment from native
My code looks like:
#ElementCollection
#JoinTable(name="USERS_ADDRESSES",
joinColumns=#JoinColumn(name="USER_ID"))
#GenericGenerator(name="hilogen", strategy="increment")
#CollectionId(columns= {#Column(name="ADDR_ID")},
generator="hilogen", type=#Type(type="long"))
private List addressList = new ArrayList();
Hope this help.
Thank, Sagar Vyas
Some generators can't generate the identifier before the actual insert, therefore they return a special marker object from the generate() method. This object indicates that Hibernate should obtain identifier in different way, using PostInsertIdentifierGenerator.getInsertGeneratedIdentifierDelegate().
Try using a #SequenceGenerator or a #GenericGenerator
This is clearly a format issue.Change Wrapper class object StudyId to primitive int.
I tries a lot of solutions, but this worked for me:
#CollectionId(columns = { #Column(name="HASTYPE_ID") }, generator= "sequence", type=#Type(type="long"))
This event work with INTEGER:
#CollectionId(columns = { #Column(name="HASTYPE_ID") }, generator= "sequence", type=#Type(type="int"))
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.