Hibernate Lazy init exception in spring scheduled job - java

I have a spring scheduled job (#Scheduled) that sends emails from my system according to a list of recipients in the DB.
This method is annotated with the #Scheduled annotation and it invokes a method from another interface, the method in the interface is annotated with the #Transactional annotation.
Now, when i invoke the scheduled method manually, it works perfectly. But when the method is invoked by spring scheduler i get the LazyInitFailed exception in the method implementing the said interface.
What am I doing wrong?
code:
The scheduled method:
#Component
public class ScheduledReportsSender {
public static final int MAX_RETIRES = 3;
public static final long HALF_HOUR = 1000 * 60 * 30;
#Autowired
IScheduledReportDAO scheduledReportDAO;
#Autowired
IDataService dataService;
#Autowired
IErrorService errorService;
#Scheduled(cron = "0 0 3 ? * *") // every day at 2:10AM
public void runDailyReports() {
// get all daily reports
List<ScheduledReport> scheduledReports = scheduledReportDAO.getDaily();
sendScheduledReports(scheduledReports);
}
private void sendScheduledReports(List<ScheduledReport> scheduledReports) {
if(scheduledReports.size()<1) {
return;
}
//check if data flow ended its process by checking the report_last_updated table in dwh
int reportTimeId = scheduledReportDAO.getReportTimeId();
String todayTimeId = DateUtils.getTimeid(DateUtils.getTodayDate());
int yesterdayTimeId = Integer.parseInt(DateUtils.addDaysSafe(todayTimeId, -1));
int counter = 0;
//wait for time id to update from the daily flow
while (reportTimeId != yesterdayTimeId && counter < MAX_RETIRES) {
errorService.logException("Daily report sender, data not ready. Will try again in one hour.", null, null, null);
try {
Thread.sleep(HALF_HOUR);
} catch (InterruptedException ignore) {}
reportTimeId = scheduledReportDAO.getReportTimeId();
counter++;
}
if (counter == MAX_RETIRES) {
MarketplaceServiceException mse = new MarketplaceServiceException();
mse.setMessage("Data flow not done for today, reports are not sent.");
throw mse;
}
// get updated timeid
updateTimeId();
for (ScheduledReport scheduledReport : scheduledReports) {
dataService.generateScheduledReport(scheduledReport);
}
}
}
The Invoked interface:
public interface IDataService {
#Transactional
public void generateScheduledReport(ScheduledReport scheduledReport);
}
The implementation (up to the line of the exception):
#Service
public class DataService implements IDataService {
public void generateScheduledReport(ScheduledReport scheduledReport) {
// if no recipients or no export type - return
if(scheduledReport.getRecipients()==null || scheduledReport.getRecipients().size()==0 || scheduledReport.getExportType() == null) {
return;
}
}
}
Stack trace:
ERROR: 2012-09-01 03:30:00,365 [Scheduler-15] LazyInitializationException.<init>(42) | failed to lazily initialize a collection of role: com.x.model.scheduledReports.ScheduledReport.recipients, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.x.model.scheduledReports.ScheduledReport.recipients, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122)
at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248)
at com.x.service.DataService.generateScheduledReport(DataService.java:219)
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:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
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:202)
at $Proxy208.generateScheduledReport(Unknown Source)
at com.x.scheduledJobs.ScheduledReportsSender.sendScheduledReports(ScheduledReportsSender.java:85)
at com.x.scheduledJobs.ScheduledReportsSender.runDailyReports(ScheduledReportsSender.java:38)
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:616)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
at org.springframework.scheduling.support.MethodInvokingRunnable.run(MethodInvokingRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:51)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:165)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:636)
ERROR: 2012-09-01 03:30:00,366 [Scheduler-15] MethodInvokingRunnable.run(68) | Invocation of method 'runDailyReports' on target class [class com.x.scheduledJobs.ScheduledReportsSender] failed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.x.model.scheduledReports.ScheduledReport.recipients, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122)
at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248)
at com.x.service.DataService.generateScheduledReport(DataService.java:219)
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:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
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:202)
at $Proxy208.generateScheduledReport(Unknown Source)
at com.x.scheduledJobs.ScheduledReportsSender.sendScheduledReports(ScheduledReportsSender.java:85)
at com.x.scheduledJobs.ScheduledReportsSender.runDailyReports(ScheduledReportsSender.java:38)
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:616)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
at org.springframework.scheduling.support.MethodInvokingRunnable.run(MethodInvokingRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:51)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:165)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:636)
getReportTimeid implementation:
#Override
public int getReportTimeId() {
Query query = super.entityManager.createNativeQuery("select timeid from lgdwh.report_last_updated order by timeid desc limit 1");
return (Integer) query.getSingleResult();
}

The problem was that I was extracting an object from the DB in the scheduled class and passing it to a class that does work on the object, my solution was to initialize the object in the scheduled class before passing it to the class that does the work.

Related

RMI Application For ArrayList [duplicate]

I'm trying to send objects using Java RMI in a JavaFX 2 project, but when the following code runs it returns a NotSerializableException.
My Admin class is Serializable and so is the super class. However it seems the exception is pointing towards the JavaFX SimpleIntegerProperty fields inside the Admin class.
I don't know what to do from here as the class being sent via RMI is serializable. Any help much appreciated.
ObservableList<Admin> data = null;
try
{
data = FXCollections.observableArrayList(Main.docServer.getAllAdmins());
}
catch (RemoteException e)
{
e.printStackTrace();
}
The error I receive:
java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: javafx.beans.property.SimpleIntegerProperty
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:191)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at $Proxy0.getAllAdmins(Unknown Source)
at com.reece.doc.views.ViewAdmin.getContent(ViewAdmin.java:34)
at com.reece.doc.ApplicationWindow.start(ApplicationWindow.java:32)
at com.reece.doc.Main.start(Main.java:57)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
Caused by: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: javafx.beans.property.SimpleIntegerProperty
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1964)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1888)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at java.util.ArrayList.readObject(ArrayList.java:733)
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 java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1004)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1866)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:324)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:173)
... 10 more
Caused by: java.io.NotSerializableException: javafx.beans.property.SimpleIntegerProperty
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at java.util.ArrayList.writeObject(ArrayList.java:710)
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 java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at sun.rmi.server.UnicastRef.marshalValue(UnicastRef.java:292)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:332)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
the class being sent via RMI is serializable
It's only serializable if it extends Serializable or Externalizable and all of its non-static non-transient member variables do so as well, and so on recursively until closure. In this case you clearly have one of type javafx.beans.property.SimpleIntegerProperty, which as the exception tells you isn't serializable:
java.io.NotSerializableException: javafx.beans.property.SimpleIntegerProperty
So any class that refers to it, directly or indirectly, isn't serializable either.
You may mark a member variable not to be serialized. And add to class new int field.
private int variableInt = 0;
private transient IntegerProperty variable;
public IntegerProperty variableProperty()
{
if(variable == null)
{
variable = new SimpleIntegerProperty();
variable.set(variableInt);
}
return variable;
}
public void setVariable(int variable)
{
if(this.variable != null)
this.variable.set(variable);
variableInt = variable;
}
public int getVariable()
{
if(variable == null)
return variableInt;
else
return variable.get();
}

Spring Hibernate: TypedQuery NullPointerException

I'm trying to do some api in spring mvc. When I run clearKoszyk method:
$scope.clearKoszyk = function(){
var successCallBack = function(response){
$scope.seans = response.data;
};
var errorCallBack = function(response){
$scope.seans = response.status;
};
$http.post('http://localhost:8080/kino/koszyk/delete').then(successCallBack, errorCallBack);
}
});
I get in response status 500 error so it's an internal server error. It's caused by:
SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with
path [/kino] threw exception [Request processing failed; nested exception
is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.hibernate.internal.SessionFactoryImpl.getReturnTypes(SessionFactoryImpl.java:1112)
at org.hibernate.internal.AbstractQueryImpl.getReturnTypes(AbstractQueryImpl.java:192)
at org.hibernate.ejb.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:690)
at sun.reflect.GeneratedMethodAccessor69.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
at com.sun.proxy.$Proxy43.createNamedQuery(Unknown Source)
at kino.repositoryImpl.KoszykRepositoryImpl.deleteKoszyk(KoszykRepositoryImpl.java:60)
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:333)
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:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy50.deleteKoszyk(Unknown Source)
at kino.serviceImpl.KoszykServiceImpl.deleteKoszyk(KoszykServiceImpl.java:50)
at kino.controllers.KoszykController.DeleteKoszyk(KoszykController.java:82)
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)
So I think this NPE is here:
at kino.repositoryImpl.KoszykRepositoryImpl.deleteKoszyk(KoszykRepositoryImpl.java:60)
But I really don't know what cause this exception. I'm checking if EntityManager or User is null.
56 public void deleteKoszyk(User user) throws NullPointerException{
57
58 if(user != null){
59 if(emManager != null){
60 TypedQuery<Koszyk> query = emManager.createNamedQuery("Koszyk.deleteKoszyk", Koszyk.class);
query.setParameter("id", user.getId());
query.executeUpdate();
}else{
throw new NullPointerException("emManager = null");
}
}else{
throw new NullPointerException("Podany użytkownik nie istnieje");
}
}
It's my koszyk class.
#Entity
#NamedQuery(name = "Koszyk.deleteKoszyk", query = "DELETE FROM Koszyk k WHERE k.user.id = :id")
#Table(name="Koszyk")
public class Koszyk implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="Koszyk_id")
private Long id;
#OneToOne
private User user;
#Column(name="Cena")
private int cena;
#Column(name="KoszykItems")
#OneToMany(mappedBy="koszyk", fetch = FetchType.EAGER)
private List<KoszykItem> koszykItems;
This problem shows only when I try to delete or find koszyk by id. I can read from this entity and I can show it in a normal way. It's my KoszykRepository class:
#Repository
#Transactional
public class KoszykRepositoryImpl implements KoszykRepository {
#PersistenceContext
private EntityManager emManager;
public KoszykRepositoryImpl(){
}
#Override
public void update(Koszyk koszyk) {
emManager.merge(koszyk);
}
#Override
public Koszyk deleteKoszykItem(KoszykItem koszykItem, User user) {
Koszyk koszyk = read(user);
List<KoszykItem> listaItemow = koszyk.getKoszykItems();
listaItemow.remove(koszykItem);
koszyk.setKoszykItems(listaItemow);
update(koszyk);
return koszyk;
}
#Override
public void deleteKoszyk(User user) throws NullPointerException{
if(user != null){
if(emManager != null){
TypedQuery<Koszyk> query = emManager.createNamedQuery("Koszyk.deleteKoszyk", Koszyk.class);
query.setParameter("id", user.getId());
query.executeUpdate();
}else{
throw new NullPointerException("emManager = null");
}
}else{
throw new NullPointerException("Podany użytkownik nie istnieje");
}
}
#Override
public void create(User user, Koszyk koszykDoZapisu) {
List<Koszyk> ListaKoszykow = read();
boolean zapisz = true;
if(user == null){
throw new NullPointerException("Zaloguj się!");
}else if(!ListaKoszykow.isEmpty() && ListaKoszykow != null){
for(Koszyk koszyk: ListaKoszykow){
if(koszyk.getUser().getId() == user.getId()){
zapisz = false;
break;
}
}
}
if(zapisz){
koszykDoZapisu.setUser(user);
emManager.persist(koszykDoZapisu);
}
}
#Override
public List<Koszyk> read() {
return emManager.createQuery("SELECT k FROM Koszyk k", Koszyk.class).getResultList();
}
#Override
public Koszyk read(User user) {
List<Koszyk> ListaKoszykow = read();
Koszyk zwracany = new Koszyk();
if(user == null){
throw new NullPointerException("Zaloguj się!");
}
if(ListaKoszykow.isEmpty() || ListaKoszykow == null){
throw new NullPointerException("Dany użytkownik nie ma jeszcze przypisanego koszyka");
}else{
for(Koszyk koszyk: ListaKoszykow){
if(koszyk.getUser().equals(user)){
zwracany = koszyk;
//Hibernate.initialize(zwracany.getKoszykItems());
}
}
}
return zwracany;
}
}
[EDIT]
I've changed delete function to this:
public void deleteKoszyk(User user) throws NullPointerException{
if(user != null){
if(emManager != null){
final Query query = emManager.createNamedQuery("Koszyk.deleteKoszyk");
query.setParameter("id", user.getId());
63 final int executeUpdate = query.executeUpdate();
}else{
throw new NullPointerException("emManager = null");
}
}else{
throw new NullPointerException("Podany użytkownik nie istnieje");
}
}
and the stacktree is completly different:
SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with
path [/kino] threw exception [Request processing failed; nested exception is
javax.persistence.PersistenceException:
org.hibernate.exception.ConstraintViolationException: Cannot delete or
update a parent row: a foreign key constraint fails (`marcin`.`koszykitem`,
CONSTRAINT `FK8F90CFF02AE8E273` FOREIGN KEY (`koszyk_Koszyk_id`) REFERENCES
`koszyk` (`Koszyk_id`))] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot delete or update a parent row: a foreign key constraint fails
(`marcin`.`koszykitem`, CONSTRAINT `FK8F90CFF02AE8E273` FOREIGN KEY
(`koszyk_Koszyk_id`) REFERENCES `koszyk` (`Koszyk_id`))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:932)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2551)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5094)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994)
at sun.reflect.GeneratedMethodAccessor66.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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.$Proxy51.executeUpdate(Unknown Source)
at org.hibernate.hql.internal.ast.exec.BasicExecutor.execute(BasicExecutor.java:95)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:413)
at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:283)
at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1135)
at org.hibernate.internal.QueryImpl.executeUpdate(QueryImpl.java:116)
at org.hibernate.ejb.QueryImpl.internalExecuteUpdate(QueryImpl.java:183)
at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:99)
at kino.repositoryImpl.KoszykRepositoryImpl.deleteKoszyk(KoszykRepositoryImpl.java:63)
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:333)
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:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy48.deleteKoszyk(Unknown Source)
at kino.serviceImpl.KoszykServiceImpl.deleteKoszyk(KoszykServiceImpl.java:50)
at kino.controllers.KoszykController.DeleteKoszyk(KoszykController.java:91)
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)
It's hard to guess where the NPE is coming from without debugging it, maybe there is no User assigned to your Koszyk instance. Your #OneToOne mapping does not prevent running into null here because the default is optional = true. If you would adjust that, the constraint would help you to at least avoid that.
Much more confusing is that you do not get another type of error. I would expect something like:
... Update/delete queries cannot be typed ...
Because update / delete queries, resp. the executeUpdate() method does just return an update count int value, no instances.
You should turn it into:
final Query query = emManager.createNamedQuery("Koszyk.deleteKoszyk");
query.setParameter("id", user.getId());
final int executeUpdate = query.executeUpdate();
Update:
Since we have the real root cause now, the issue seems clear. You can't delete an entity as long as it's id is used as a foreign key on another entity. Delete the entity which references this Koszyk first.

More than one row with the given identifier was found: 1, for class: com.model.Diagnosis

Below is the model, service implementation and the error trace of my code.
Model class:
#Entity
#Table(name = "ph_diagnosis_history")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id",scope=Diagnosis.class)
public class Diagnosis extends AbstractEntity {
#Column(name = "diagnosis_notes", length=255)
#Length(max = 255, message = IprProp.MAX_LEN_255_MSG)
private String diagnosisNote;
#Enumerated(EnumType.STRING)
private DiagnosisTypeEnum type;
#Temporal(TemporalType.DATE)
#Column(name = "diagnosis_date")
#JsonSerialize(using = JsonDateSerializer.class)
private Date diagnosisDate;
#ManyToOne
#JoinColumn(name = "patient_chart_id")
private PatientChart patientChart;
public String getDiagnosisNote() {
return diagnosisNote;
}
public void setDiagnosisNote(String diagnosisNote) {
this.diagnosisNote = diagnosisNote;
}
public DiagnosisTypeEnum getType() {
return type;
}
public void setType(DiagnosisTypeEnum type) {
this.type = type;
}
public Date getDiagnosisDate() {
return diagnosisDate;
}
public void setDiagnosisDate(Date diagnosisDate) {
this.diagnosisDate = diagnosisDate;
}
public PatientChart getPatientChart() {
return patientChart;
}
public void setPatientChart(PatientChart patientChart) {
this.patientChart = patientChart;
}
}
My service:
public Diagnosis updateDiagnosis(IPRDTO clientDto, Long userId,
Long patientChartId, DiagnosisDTO diagnosisDTO, Long diagnosisId) throws Exception {
Diagnosis diagnosis = diagnosisRepository.findOne(diagnosisId);
if (diagnosis!=null){
if(diagnosis.getType().equals(DiagnosisTypeEnum.WORKING)){
BeanCopyUtil.copyProperties(diagnosisDTO, diagnosis, true);
return this.diagnosisRepository.saveAndFlush(diagnosis);
}
else{
throw new BusinessException("updateDiagnosisValidation");
}
}
throw new BusinessException("noDiagnosis");
}
My stack trace:
[2014-09-08 11:34:08,148] INFO com.zurelsoft.ipr.service.IDiagnosisService- Logged In User Id [1]:Started updateDiagnosis
diagnosis id 2
[2014-09-08 11:34:08,969] INFO org.hibernate.event.internal.DefaultLoadEventListener- HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
[2014-09-08 11:34:09,001] ERROR com.zurelsoft.ipr.service.IDiagnosisService- Logged In User Id [1]:Error Occurred updateDiagnosis
org.springframework.orm.jpa.JpaSystemException: org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis; nested exception is javax.persistence.PersistenceException: org.hibernate.HibernateException: More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
[2014-09-08 11:34:09,006] ERROR com.zurelsoft.ipr.client.DiagnosisWebService- org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321)
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy85.findOne(Unknown Source)
com.zurelsoft.ipr.service.impl.DiagnosisServiceImpl.updateDiagnosis(DiagnosisServiceImpl.java:76)
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:51)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy86.updateDiagnosis(Unknown Source)
com.zurelsoft.ipr.client.DiagnosisWebService.updateDiagnosis(DiagnosisWebService.java:98)
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:219)
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:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:849)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
I get this HibernateException in this line alhough my table has now two rows with the same id.
Diagnosis diagnosis = diagnosisRepository.findOne(diagnosisId);
Please anyone help me with my mistake. What can be probable error in my code.
Hy, It woks for me:
Seems I have two choices: either cascade all and delete orphan on the one-to-one relationship, or explicitly call my repository class to look up and save the original Sheet every time I remove its relationship with Plate. I opted for the first choice and added this to the plate class:
#OneToOne(mappedBy = "plate", cascade = CascadeType.ALL, orphanRemoval = true)
https://stackoverflow.com/a/32636186/3255595
From Spring documentation:
T findOne(ID id)
Retrieves an entity by its id.
Seem that diagnosisId is not a primary key.
it sounds like you have more than one row in the database with the same id values!
Are you sure your id is really unique in the DB ?
Hibernate Exception
More than one row with the given identifier was found: 2, for class: com.zurelsoft.ipr.model.Diagnosis
tells that hibernate query executes returns more than one row (i.e 2) of class Diagnosis Please enable SQL logging and execute the select by hand and see what it returns

Why code insert data before validation in Spring

I have code here:
#Controller
#RequestMapping(value="/guestbook")
public class GuestBookController {
#Autowired
GuestBookServiceIF guestBookServiceIF;
#ModelAttribute("messagesModel")
public List<UserMessage> getMessagesModel() {
return guestBookServiceIF.fetchAllService();
}
#RequestMapping(method = RequestMethod.GET)
public String renderGuestBook(Model model) {
GuestBookBackObject guestBookBackObject = new GuestBookBackObject();
model.addAttribute("guestBookBackObject", guestBookBackObject);
return "book";
}
#RequestMapping(method=RequestMethod.POST)
public String saveGuestBookMessage(#ModelAttribute(value="guestBookBackObject") GuestBookBackObject guestBookBackObject,
BindingResult buindingResult) {
guestBookBackObject.setIsNameExist(guestBookServiceIF.isUserInDBService(guestBookBackObject.getUser().getUserName()));
GuestBookValidation validator = new GuestBookValidation();
validator.validate(guestBookBackObject, buindingResult);
if(buindingResult.hasErrors()) {
return "book";
} else {
guestBookBackObject.getUserMessage().setTheUser(guestBookBackObject.getUser());
guestBookServiceIF.saveMessageService(guestBookBackObject.getUserMessage());
return "redirect:/guestbook";
}
}
in saveGuestBookMessage() there is should be some validation before execute the rest of the code. The point of my validation is that it check is there same user name in Database if yes user name is exist in database then on jsp page should render some error messages like: "Choose different name" for example for this purpose is isUserInDBService() method.
Here is my validator code:
#Component
public class GuestBookValidation implements Validator{
#SuppressWarnings("rawtypes")
#Override
public boolean supports(Class clazz) {
return GuestBookBackObject.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object obj, Errors error) {
GuestBookBackObject guestBookBackObject = (GuestBookBackObject)obj;
if(guestBookBackObject.equals(obj)) {
ValidationUtils.rejectIfEmpty(error, "user.userName", "", "\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0432\u0432\u0435\u0441\u0442\u0438 \u0438\u043C\u044F");
ValidationUtils.rejectIfEmptyOrWhitespace(error, "userMessage.theMessage", "", "\u042D\u0442\u043E \u043F\u043E\u043B\u0435 \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C");
if(guestBookBackObject.getIsNameExist()== null) {
ValidationUtils.rejectIfEmpty(error, "user.userName", "", "Please choose different user name");
}
} else {
try {
throw new Exception("Object of referance variable obj not equal referance variable guestBookBackObject");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Basically it should work fine, but it gives error:
Hibernate: insert into USER_DESC (USER_NAME) values (?)
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1062, SQLState: 23000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Duplicate entry 'we' for key 'UK_ok6uvp3eyniad0xua3xdt5icw'
Oct 01, 2013 9:27:04 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'we' for key 'UK_ok6uvp3eyniad0xua3xdt5icw'
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:4190)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2818)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2157)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2460)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2377)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2361)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
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:2975)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3487)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:214)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:194)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:178)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:735)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:727)
at org.hibernate.engine.spi.CascadingAction$5.cascade(CascadingAction.java:258)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:388)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:331)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:209)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:166)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:424)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:263)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
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:764)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:756)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:752)
at demidov.pkg.persistence.GuestBookDAOImpl.saveMessage(GuestBookDAOImpl.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.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.$Proxy8.saveMessage(Unknown Source)
at demidov.pkg.service.GuestBookServiceImpl.saveMessageService(GuestBookServiceImpl.java:27)
at demidov.pkg.web.GuestBookController.saveGuestBookMessage(GuestBookController.java:60)
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.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
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)
Which tells that value exist in database and this value should be unique. Ok! But why the Validator let insert value first with out check them???
My back object (GuestBookBackObject):
#Component
public class GuestBookBackObject {
private UserMessage userMessage;
public UserMessage getUserMessage() {
return userMessage;
}
public void setUserMessage(UserMessage userMessage) {
this.userMessage = userMessage;
}
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
private User isNameExist;
public User getIsNameExist() {
return isNameExist;
}
public void setIsNameExist(User isNameExist) {
this.isNameExist = isNameExist;
}
}
thank you.
Lacking more information like implementation of GuestBookBackObject. But based on what you have given
Simply the Exception you have got is thrown because you never check in database whether the values you going to insert exists or not in a column which is said to be unique.
You should implement this inside your validator or anywhere before you save. For example
boolean exists = guestBookServiceIF.isMessageExists(guestBookBackObject);
The only way to database to find out you are violating the a constraint is while executing that statement.
To store the validation message you are calling the wrong method.
if(guestBookBackObject.getIsNameExist()== null) {
ValidationUtils.rejectIfEmpty(error, "user.userName", "", "Please choose different user name");
}
If the property is set, but the username isn't empty nothing is going to get set. You should simply call the reject method on the Errors object.
if(guestBookBackObject.getIsNameExist()== null) {
errrors.reject("username.not.unique", "Please choose different user name");
}
Next to that you should do the check inside your Validator and not your controller. That way you can let Spring do all the heavy lifting for you.

GWT/JAVA Uncaught exception escaped

I have got a problem with my code and i cant seem to fix it. I want to add some customer data to a array list in java/GWT when submitting a button.
the form from which i add the data.
ok.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (!voornaamTB.getText().equalsIgnoreCase("") && !achternaamTB.getText().equalsIgnoreCase("") && !emailTB.getText().equalsIgnoreCase("") && !geboortedatumTB.getText().equalsIgnoreCase("")) {
boolean addVG;
System.out.println(voornaamTB.getText());
System.out.println(tussenvoegselTB.getText());
System.out.println(achternaamTB.getText());
System.out.println(emailTB.getText());
System.out.println(geboortedatumTB.getText());
--> the error is generated here addVG = VGC.addVakantieganger(voornaamTB.getText(), tussenvoegselTB.getText(), achternaamTB.getText(), emailTB.getText(), geboortedatumTB.getText());
if (addVG) {
Window.alert("Vakantieganger toegevoegd.");
} else {
Window.alert("Vakantieganger niet toegevoegd.");
}
} else {
voornaamTB.addStyleName("invalide-TextBox");
tussenvoegselTB.addStyleName("invalide-TextBox");
achternaamTB.addStyleName("invalide-TextBox");
emailTB.addStyleName("invalide-TextBox");
geboortedatumTB.addStyleName("invalide-TextBox");
}
}
});
the controller class.
import java.util.ArrayList;
import com.vakantievibes.client.domein.Vakantieganger;
public class VakantiegangerController {
private String msg;
private ArrayList<Vakantieganger> vakantiegangers = new ArrayList<Vakantieganger>();
public VakantiegangerController(){
}
#SuppressWarnings("static-access")
public boolean heeftVakantieganger(String email) {
boolean result = false;
for (Vakantieganger v : vakantiegangers) {
if (v.getEmail().equalsIgnoreCase(email)){
result = true;
}
}
return result;
}
public boolean addVakantieganger(String voornaam, String tussenvoegsel, String achternaam, String email, String geboortedatum) {
//boolean result = false;
//if (!heeftVakantieganger(email)) {
Vakantieganger v = new Vakantieganger(voornaam, tussenvoegsel, achternaam, email, geboortedatum);
vakantiegangers.add(v);
boolean result = true;
System.out.println("klant toegevoegd");
//}
return result;
}
}
with the methode addVakantieganger it should add the data to the arraylist. but it doesn't seem to do that it should then report true back to the form. the !heeftVakantieganger(email) should check if the person is already in the array list but is disabled now for testing purpose's
the errors i recieve in eclipse.
14:17:03.207 [ERROR] [vakantie_vibes] Uncaught exception escaped
com.google.gwt.event.shared.UmbrellaException: One or more exceptions caught, see full set in UmbrellaException#getCauses
at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:129)
at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:124)
at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116)
at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:172)
at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1321)
at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1277)
at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:167)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:326)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:207)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:132)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:214)
at sun.reflect.GeneratedMethodAccessor16.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:167)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:281)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:531)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:352)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.lang.NullPointerException: null
at com.vakantievibes.client.GUI.FormToevoegenVakantieganger$8.onClick(FormToevoegenVakantieganger.java:153)
at com.google.gwt.event.dom.client.ClickEvent.dispatch(ClickEvent.java:54)
at com.google.gwt.event.dom.client.ClickEvent.dispatch(ClickEvent.java:1)
at com.google.gwt.event.shared.GwtEvent.dispatch(GwtEvent.java:1)
at com.google.web.bindery.event.shared.SimpleEventBus.doFire(SimpleEventBus.java:193)
at com.google.web.bindery.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:88)
at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:127)
at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:124)
at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116)
at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:172)
at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1321)
at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1277)
at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:167)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:326)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:207)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:132)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:214)
at sun.reflect.GeneratedMethodAccessor16.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:167)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:281)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:531)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:352)
at java.lang.Thread.run(Thread.java:679)
You get a NullPointerException. This happens because you are using a reference which is null. In your case this is one of the fields in the line that you marked.
Use a debugger, put a breakpoint on that line, and inspect which field in null.
Since you use all the variables, only VGC can be null at this time.
But I suspect this is a class name. My first guess is that the type VGC is part of the server API and not of the client API or something along these lines.

Categories

Resources