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.
Related
I'm trying to create an multithreaded app (Java) in which some threads insert further rows to database. I use Embedded Derby from JDK.
This is code that concerns establishing connection to database and inserting.
public class DatabaseConnection
{
private static String dbURL = "jdbc:derby:./Database/DB;create=true;user=fafejs;password=fafejs";
private Connection conn;
private DatabaseUpdateContent duc;
private DatabaseUpdateView duv;
public synchronized void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); // load the driver
conn = DriverManager.getConnection(dbURL); // make Derby JDBC connection
duc = new DatabaseUpdateContent(conn);
duv = new DatabaseUpdateView(conn);
System.out.println(conn);
}
catch (Exception except) // TODO - obsluga
{
except.printStackTrace();
}
}
public synchronized void recreateConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
conn = DriverManager.getConnection(dbURL);
duc = new DatabaseUpdateContent(conn);
duv = new DatabaseUpdateView(conn);
System.out.println("Reconnect:" + conn);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean updatePlayer(PlayerService player)
{
try
{
int ID = player.getID();
String firstName = player.getFirstName();
String lastName = player.getLastName();
Date birthdate;
if(!(player.getDate() == null))
birthdate = new java.sql.Date(player.getDate().getTime());
else
birthdate = null;
String league = newLeagueName(player.getLeagueName()).toUpperCase();
String team = player.getTeamName();
int apps = player.getApps();
int firstSquad = player.getFirstSquad();
int minutes = player.getMinutes();
int goals = player.getGoals();
int yellowCards = player.getYellowCards();
int redCards = player.getRedCards();
duc.updatePlayersTable(ID, firstName, lastName, birthdate);
duc.updateLeagueTable(league, ID, team, apps, firstSquad, minutes, goals, yellowCards, redCards);
return true;
}
catch (SQLException sqlExcept)
{
//shutdown();
sqlExcept.printStackTrace();
return false;
}
}
public synchronized void shutdown()
{
try
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
//System.gc();
}
catch (SQLException sqlExcept)
{
//sqlExcept.printStackTrace();
}
}
}
public void updatePlayersTable(int ID, String firstName, String lastName, Date birthdate) throws SQLException // z klasy DatabaseUpdateContent
{
PreparedStatement pstmt = conn.prepareStatement("UPDATE APP.PLAYERS SET FIRST_NAME = ?, LAST_NAME = ?, BIRTHDATE = ? WHERE ID = ?");
pstmt.setString(1,firstName);
pstmt.setString(2,lastName);
pstmt.setDate(3,birthdate);
pstmt.setInt(4,ID);
if(pstmt.executeUpdate() == 0)
{
pstmt = conn.prepareStatement("INSERT INTO APP.PLAYERS VALUES (?,?,?,?)");
pstmt.setInt(1, ID);
pstmt.setString(2, firstName);
pstmt.setString(3, lastName);
pstmt.setDate(4, birthdate);
pstmt.execute();
}
pstmt.close();
}
public void updateDB() // procedura, która zajmuje się aktualizacją zawartości bazy danych
{
DatabaseConnection database = new DatabaseConnection();
database.createConnection();
for(PlayerService player: players)
{
while(!database.updatePlayer(player))
{
database.recreateConnection();
}
}
database.shutdown();
}
On the whole, strongly most rows are inserted to appropriate table properly, but sometimes i get SQLNonTransientConnectionException:
java.sql.SQLNonTransientConnectionException: No current connection.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.noCurrentConnection(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkIfClosed(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.setupContextStack(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at DatabaseService.DatabaseUpdateContent.updateLeagueTable(DatabaseUpdateContent.java:39)
at DatabaseService.DatabaseConnection.updatePlayer(DatabaseConnection.java:68)
at DataService.TeamService.updateDB(TeamService.java:66)
at DataService.TeamService.getPlayers(TeamService.java:56)
at DataService.TeamService.getPlayersUrls(TeamService.java:44)
at DataService.LeagueService.getTeams(LeagueService.java:52)
at DataService.LeagueService.run(LeagueService.java:35)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR 08003: No current connection.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 17 more
java.sql.SQLException: Database './Database/DB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at DatabaseService.DatabaseConnection.recreateConnection(DatabaseConnection.java:35)
at DataService.TeamService.updateDB(TeamService.java:69)
at DataService.TeamService.getPlayers(TeamService.java:56)
at DataService.TeamService.getPlayersUrls(TeamService.java:44)
at DataService.LeagueService.getTeams(LeagueService.java:52)
at DataService.LeagueService.run(LeagueService.java:35)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR XJ004: Database './Database/DB' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
This exception occurs many times in a row, because if updating player fails, function updatePlayer will return false and we repeat loop in function updateDB. But after a while (about 50 attempts of inserting row), it's possible to establish connection and insert a row.
Certainly i've looked for solution of this problem. I tried way associated with System.gc(), what is suggested in some documentation but it doesn't help in my case.
I was considering also fact that my problem could be connected with multithreading of my app but in Embedded Derby's documentation they say in short that Embedded Derby should deal with it.
Thanks for your support in advance.
EDIT
This is error information that I get after adding code from http://wiki.apache.org/db-derby/UnwindExceptionChain:
----- SQLException -----
SQLState: 08003
Error Code: 40000
Message: No current connection.
java.sql.SQLNonTransientConnectionException: No current connection.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.noCurrentConnection(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkIfClosed(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.setupContextStack(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at DatabaseService.DatabaseUpdateContent.updatePlayersTable(DatabaseUpdateContent.java:17)
at DatabaseService.DatabaseConnection.updatePlayer(DatabaseConnection.java:73)
at DataService.TeamService.updateDB(TeamService.java:64)
at DataService.TeamService.getPlayers(TeamService.java:53)
at DataService.TeamService.getPlayersUrls(TeamService.java:39)
at DataService.LeagueService.getTeams(LeagueService.java:50)
at DataService.LeagueService.run(LeagueService.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR 08003: No current connection.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 17 more
java.sql.SQLException: Database './Database/DB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at DatabaseService.DatabaseConnection.recreateConnection(DatabaseConnection.java:39)
at DataService.TeamService.updateDB(TeamService.java:67)
at DataService.TeamService.getPlayers(TeamService.java:53)
at DataService.TeamService.getPlayersUrls(TeamService.java:39)
at DataService.LeagueService.getTeams(LeagueService.java:50)
at DataService.LeagueService.run(LeagueService.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR XJ004: Database './Database/DB' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
It seems to me that error associated with not finding database (to be more precise, I mean problem connected with loading the driver of Embedded Derby) is caused by SQLNonTransientConnectionException and there is the rub.
I have a record in database which being get must be in the tree table view. Here is the filling method:
private void updateGoods(){
goodsPane.setCenter(goodTreeTableView);
List<Good> goodAndFoldersList;
try {
goodAndFoldersList = goodsService.getGoods();//database query
}catch (SQLException e){
goodAndFoldersList = new ArrayList<>();
log.log(Level.ERROR, e.getMessage());
}
List<Good> goods = new ArrayList<Good>();//list for roots
List<Good> roots = new ArrayList<Good>();//list for goods themselves
for (Good good : goodAndFoldersList) {
if (good.isIs_folder()) {
roots.add(good);
} else {
goods.add(good);
}
}
TreeItem<Good> rootItem = new TreeItem<>();//the main root
for (Good root : roots) {
Long folderId = root.getId();
TreeItem<Good> rootTreeItem = new TreeItem<>(root);
for (Good good : goods) {//looking for goods for each folder
if (good.getFolderId() == folderId) {
TreeItem<Good> goodTreeItem = new TreeItem<>(good);
rootTreeItem.getChildren().add(goodTreeItem);
}
}
rootItem.getChildren().add(rootTreeItem);//adding every folder to the main root
}
goodTreeTableView = new TreeTableView<>(rootItem);
}
after this method user doesn't see anything in the treeTableView. Maybe there nessessary to define cell content, but this code being put before goodTreeTableView = new TreeTableView<>(rootItem); drops NullPointerException:
goodName.setCellValueFactory((TreeTableColumn.CellDataFeatures<Good, String> param) ->
new ReadOnlyStringWrapper(param.getValue().getValue().getName()));
folderId.setCellValueFactory((TreeTableColumn.CellDataFeatures<Good, Number> param) ->
new ReadOnlyLongWrapper(param.getValue().getValue().getFolderId()));
is_folder.setCellValueFactory((TreeTableColumn.CellDataFeatures<Good, Boolean> param) ->
new ReadOnlyBooleanWrapper(param.getValue().getValue().isIs_folder()));
I guess this is the reason of my problem but why this drops NPE I can't figure out.
UPD: if I add setting cell value factory I get the following stacktrace:
javafx.fxml.LoadException:
/D:/javaEdi/linkserver/ediagent/target/classes/com/ediagent/edi/gui/Main.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2595)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2565)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2435)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2403)
at com.ediagent.edi.gui.Main.initRootLayout(Main.java:44)
at com.ediagent.edi.gui.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(LauncherImpl.java:821)
at com.sun.javafx.application.LauncherImpl$$Lambda$51/1546859350.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(PlatformImpl.java:323)
at com.sun.javafx.application.PlatformImpl$$Lambda$44/1712669532.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/157858792.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/1225373914.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/152005629.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2560)
... 18 more
Caused by: java.lang.NullPointerException
at com.ediagent.edi.gui.MainController.updateGoods(MainController.java:309)
at com.ediagent.edi.gui.MainController.initialize(MainController.java:328)
... 28 more
**UPD:**rootItem:
You are adding the data to an GUI element on FXML, by re-initializing it. Avoid re-initialization of FXML elements.
You can change the signature of updateGoods() to :
public TreeItem<Good> updateGoods() {
...
}
and use it in the MainController to set items
goodTreeTableView.setRoot(updateGoods());
Preferably, you can also return only data(List) from updateGoods() instead of returning a TreeItem. Create it in the Controller and set it as the root of goodTreeTableView.
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
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.
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.