2

I am getting into ActiveJDBC at the moment, a very nice and useful framework, as far as I can tell. But I am having some problems with the JDBC-Connection management of it, as it attaches an opened connection to the current thread. That means, if I open the connection at the initialisation of my program, everything works fine; but if I instantiate a JFrame afterwards and try reading/wrtiting data from/to the database in an ActionListener for example, it will generate an error, since there is no connection attached to the dispatch thread.

How to solve this problem? I'd rather have just one connection, to which I can get access (via Base.connection()) all the time, instead of having one connection attached to each thread..

Thanks in advance

JonasB
  • 131
  • 1
  • 9

1 Answers1

3

I would suggest that you implement action listener this way:

public class AJListenerAdapter implements ActionListener{
  public void actionPerformed(ActionEvent e){
     Base.open(...);
     doPerform(ActionEvent e);
     Base.close(...);
  }

  protected abstract doPerform(ActionEvent e);
}

then just subclass this adapter and implement the doPerform() method.

Additionally you might want to use connections from a pool. Here is an example https://github.com/javalite/activejdbc/blob/master/activejdbc/src/test/java/org/javalite/activejdbc/C3P0PoolTest.java

ipolevoy
  • 5,432
  • 2
  • 31
  • 46
  • Thank you for your reply! But won't it be a performance issue to open and close a connection every time a DB access takes place (f. e. AbstractTableModel.getValueAt(...))? – JonasB Jan 08 '15 at 23:44
  • Not if you use a connection pool as I mentioned above. Alternatively you can implement your own DataSource as singleton with one and only one connection as pass that to the `Base.open(datasource)`. – ipolevoy Jan 09 '15 at 14:40
  • Okay, I'm trying to get it to work; but I can't figure it out. I'm trying to get data into a TableModel. Opening and releasing a connection for every single getValueAt doesn't work (not surprisingly). So I tried to initiate the TableModel with a List (the query being "executed" in my main thread), which works, even if the List is accessed from another Thread! I was able to fill a 100000 row table very nicely. But I can't use any methods which will actually do new queries/updates/etc. (f. e. querying parents/children) because there is no connection attached to that thread.. – JonasB Jan 09 '15 at 20:30
  • Got it; just had to do all the work in the dispatch thread. Dumb mistake. Thank you for your help! – JonasB Jan 09 '15 at 21:10