privatecoder

Main.java

Jul 14th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1. import com.j256.ormlite.dao.Dao;
  2. import com.j256.ormlite.dao.DaoManager;
  3. import com.j256.ormlite.field.DatabaseField;
  4. import com.j256.ormlite.jdbc.JdbcConnectionSource;
  5. import com.j256.ormlite.table.DatabaseTable;
  6. import com.j256.ormlite.table.TableUtils;
  7. import javafx.beans.property.SimpleStringProperty;
  8. import javafx.beans.property.StringProperty;
  9.  
  10. import java.io.File;
  11. import java.nio.file.FileSystems;
  12. import java.util.List;
  13.  
  14. /**
  15.  * @since 2016-07-15 04:12
  16.  */
  17. public class Main {
  18.     @DatabaseTable(tableName = "a")
  19.     public static class A {
  20.         @DatabaseField(generatedId = true, columnName = "id")
  21.         private long id;
  22.  
  23.         @DatabaseField(columnName = "value", persisterClass = StringPropertyPersister.class)
  24.         private final StringProperty value;
  25.  
  26.         protected A() {
  27.             value = new SimpleStringProperty();
  28.         }
  29.  
  30.         public A(String token) {
  31.             value = new SimpleStringProperty(token);
  32.         }
  33.  
  34.         public String getValue() { return value.get(); }
  35.         public StringProperty valueProperty() { return value; }
  36.     }
  37.  
  38.     private static void initDB() throws Exception {
  39.         final File path = FileSystems.getDefault().getPath(System.getProperty("user.home"), "Desktop", "test").toFile();
  40.         final String DATABASE_URL = "jdbc:h2:" + path.getAbsolutePath();
  41.  
  42.         Class.forName("org.h2.Driver");
  43.  
  44.         connectionSource = new JdbcConnectionSource(DATABASE_URL);
  45.         connectionSource.initialize();
  46.  
  47.         TableUtils.createTableIfNotExists(connectionSource, A.class);
  48.     }
  49.  
  50.     private static void insertMockData() throws Exception {
  51.         Dao<A, Integer> dao = DaoManager.createDao(connectionSource, A.class);
  52.         dao.executeRaw("INSERT INTO a (id, value) VALUES (NULL, NULL)");
  53.     }
  54.  
  55.     private static List<A> fetchResults() throws Exception {
  56.         Dao<A, Integer> dao = DaoManager.createDao(connectionSource, A.class);
  57.         return dao.queryForAll();
  58.     }
  59.  
  60.     private static JdbcConnectionSource connectionSource;
  61.  
  62.     public static void main(String[] args) throws Exception {
  63.         initDB();
  64.         insertMockData();
  65.  
  66.         List<A> results = fetchResults();
  67.         for (A result : results) {
  68.             System.out.println(result.getValue()); // throws NullPointerException
  69.         }
  70.     }
  71. }
Add Comment
Please, Sign In to add comment