ORMLite error no databasefield annotations exists - java

I have this error when I run my Android application:
No fields have a DatabaseField
annotation in class [[Lmodel.Vak;
My class Vak has annotations, so I really don't understand why it still giving me this error.
package model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
#DatabaseTable(tableName = "vak")
public class Vak {
#DatabaseField(generatedId = true, columnName = "vakID", id=true) Long id;
#DatabaseField int rij;
#DatabaseField
int kolom;
...
}
I have a file called Databasehelper.java in which extends OrmLiteSqLiteOpenHelper and the file looks like this:
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application -- change to something
// appropriate for your app
private static final String DATABASE_NAME = "project56.db";
// any time you make changes to your database objects, you may have to
// increase the database version
private static final int DATABASE_VERSION = 1;
private DatabaseType databaseType = new SqliteAndroidDatabaseType();
// the DAO object we use to access the tables
private Dao<Vleugel, Long> vleugelDao = null;
private Dao<Verdieping, Long> verdiepingDao = null;
private Dao<NavigatiePunt, Long> navigatiePuntDao = null;
private Dao<Lokaal, Long> lokaalDao = null;
private Dao<Raster, Long> rasterDao = null;
private Dao<Vak, Long> vakDao = null;
private Dao<Graaf, Long> graafDao = null;
private Dao<Vertex, Long> vertexDao = null;
private Dao<Edge, Long> edgeDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* This is called when the database is first created. Usually you should
* call createTable statements here to create the tables that will store
* your data.
*/
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
TableUtils.createTable(connectionSource, Vleugel.class);
TableUtils.createTable(connectionSource, Verdieping.class);
TableUtils.createTable(connectionSource, NavigatiePunt.class);
TableUtils.createTable(connectionSource, Lokaal.class);
TableUtils.createTable(connectionSource, Raster.class);
TableUtils.createTable(connectionSource, Vak.class);
TableUtils.createTable(connectionSource, Graaf.class);
TableUtils.createTable(connectionSource, Vertex.class);
TableUtils.createTable(connectionSource, Edge.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
/**
* This is called when your application is upgraded and it has a higher
* version number. This allows you to adjust the various data to match the
* new version number.
*/
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, Vleugel.class, true);
TableUtils.dropTable(connectionSource, Verdieping.class, true);
TableUtils.dropTable(connectionSource, NavigatiePunt.class, true);
TableUtils.dropTable(connectionSource, Lokaal.class, true);
TableUtils.dropTable(connectionSource, Raster.class, true);
TableUtils.dropTable(connectionSource, Vak.class, true);
TableUtils.dropTable(connectionSource, Graaf.class, true);
TableUtils.dropTable(connectionSource, Vertex.class, true);
TableUtils.dropTable(connectionSource, Edge.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
/**
* Returns the Database Access Object (DAO) for the classes It will create
* it or just give the cached value.
*/
public Dao<Vleugel, Long> getVleugelDao() throws SQLException {
if (vleugelDao == null) {
vleugelDao = getDao(Vleugel.class);
}
return vleugelDao;
}
public Dao<Verdieping, Long> getVerdiepingDao() throws SQLException {
if (verdiepingDao == null) {
verdiepingDao = getDao(Verdieping.class);
}
return verdiepingDao;
}
public Dao<NavigatiePunt, Long> getNavigatiePuntDao() throws SQLException {
if (navigatiePuntDao == null) {
navigatiePuntDao = getDao(NavigatiePunt.class);
}
return navigatiePuntDao;
}
public Dao<Lokaal, Long> getLokaalDao() throws SQLException {
if (lokaalDao == null) {
lokaalDao = getDao(Lokaal.class);
}
return lokaalDao;
}
public Dao<Raster, Long> getRasterDao() throws SQLException {
if (rasterDao == null) {
rasterDao = getDao(Raster.class);
}
return rasterDao;
}
public Dao<Vak, Long> getVakDao() throws SQLException {
if (vakDao == null) {
vakDao = getDao(Vak.class);
}
return vakDao;
}
public Dao<Graaf, Long> getGraafDao() throws SQLException {
if (graafDao == null) {
graafDao = getDao(Graaf.class);
}
return graafDao;
}
public Dao<Vertex, Long> getVertexDao() throws SQLException {
if (vertexDao == null) {
vertexDao = getDao(Vertex.class);
}
return vertexDao;
}
public Dao<Edge, Long> getEdgeDao() throws SQLException {
if (edgeDao == null) {
edgeDao = getDao(Edge.class);
}
return edgeDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
vleugelDao = null;
verdiepingDao = null;
navigatiePuntDao = null;
lokaalDao = null;
rasterDao = null;
vakDao = null;
graafDao = null;
vertexDao = null;
edgeDao = null;
}
}
I also have a file Controller which extends OrmLiteBaseActivity:
public class Controller extends OrmLiteBaseActivity<DatabaseHelper> {
Dao<Vleugel, Long> vleugelDao;
Dao<Verdieping, Long> verdiepingDao;
Dao<NavigatiePunt, Long> navigatiePuntDao;
Dao<Lokaal, Long> lokaalDao;
Dao<Raster, Long> rasterDao;
Dao<Graaf, Long> graafDao;
Dao<Vertex, Long> vertexDao;
Dao<Edge, Long> edgeDao;
Dao<Vak, Long> vakDao;
// Databasehelper is benodigd voor ORMLite
static {
OpenHelperManager.setOpenHelperFactory(new SqliteOpenHelperFactory() {
public OrmLiteSqliteOpenHelper getHelper(Context context) {
return new DatabaseHelper(context);
}
});
}
public Controller() throws SQLException {
/** initialiseren van dao */
vleugelDao = getHelper().getVleugelDao();
verdiepingDao = getHelper().getVerdiepingDao();
navigatiePuntDao = getHelper().getNavigatiePuntDao();
lokaalDao = getHelper().getLokaalDao();
rasterDao = getHelper().getRasterDao();
graafDao = getHelper().getGraafDao();
vertexDao = getHelper().getVertexDao();
edgeDao = getHelper().getEdgeDao();
vakDao = getHelper().getVakDao();
}
/**
* Haalt vleugel idNaam op uit dao object bijv. K1
*
* #return Vleugel
* #throws java.sql.SQLException
*/
public Vleugel getVleugel(String vleugelIDNaam)
throws java.sql.SQLException {
// select * from vleugel where idNaam='{vleugelIDNaam}'
QueryBuilder<Vleugel, Long> qb = vleugelDao.queryBuilder();
Where where = qb.where();
// the name field must be equal to "foo"
where.eq("idNaam", vleugelIDNaam);
PreparedQuery<Vleugel> preparedQuery = qb.prepare();
List<Vleugel> vleugelList = vleugelDao.query(preparedQuery);
Log.v("Getvleugel", vleugelList.size() + "");
if (vleugelList.size() == 1) {
return vleugelList.get(0);
}
return null;
}
public Verdieping getVerdieping(int nummer) throws java.sql.SQLException {
// TODO: Met querybuilder query naar db om verdieping te pakken
return null;
}
/**
* Haalt navigatiepunt op
*
* #param naam
* #return
* #throws java.sql.SQLException
*/
public NavigatiePunt getNavigatiePunt(String naam)
throws java.sql.SQLException {
// select * from navigatiepunt where naam='{naam}'
QueryBuilder<NavigatiePunt, Long> qb = navigatiePuntDao.queryBuilder();
Where where = qb.where();
where.eq("naam", naam);
PreparedQuery<NavigatiePunt> preparedQuery = qb.prepare();
List<NavigatiePunt> navigatieList = navigatiePuntDao
.query(preparedQuery);
Log.v("GetLokaal", navigatieList.size() + "");
if (navigatieList.size() == 1) {
return navigatieList.get(0);
}
return null;
}
/**
* Get lokaal object op basis van lokaalcode
*
* #param lokaalcode
* #return
* #throws java.sql.SQLException
*/
public Lokaal getLokaal(String lokaalcode) throws java.sql.SQLException {
// select * from lokaal where lokaalcode='{lokaalcode}'
QueryBuilder<Lokaal, Long> qb = lokaalDao.queryBuilder();
Where where = qb.where();
where.eq("lokaalcode", lokaalcode);
PreparedQuery<Lokaal> preparedQuery = qb.prepare();
List<Lokaal> lokaalList = lokaalDao.query(preparedQuery);
Log.v("GetLokaal", lokaalList.size() + "");
if (lokaalList.size() == 1) {
return lokaalList.get(0);
}
return null;
}
}
So do you have any advice on this, what should I check?

Could you check, are created table Vak in your DB? The absence of this table can be reason of this crash.

This turned out to be a bug in ORMLite around foreign object loops that was fixed in version 4.22. ORMLite was not properly handing the case where A has a foreign-field B which has a foreign-field to C which has a foreign-field back to A..
http://ormlite.com/releases/
Please send me some direct mail #Yanny if this does or doesn't work and I will tune this answer accordingly.

It's probably late for giving solution but this is my solution:
you see proguard try to obfuscating the code and if you read proguard in depth or intro
http://proguard.sourceforge.net/FAQ.html
what Shrinking in proguard -> Shrinking programs such as ProGuard can analyze bytecode and remove unused classes, fields, and methods.
so from this we can presume that it is removing your objects since it's not used by anywhere...
so wt you probably need?
you need to stop proguard from shirking that methods or objects from process
so this is the line for that..:
-keep class com.j256.**<br>
-keepclassmembers class com.j256.** { *; }<br>
-keep enum com.j256.**<br>
-keepclassmembers enum com.j256.** { *; }<br>
-keep interface com.j256.**<br>
-keepclassmembers interface com.j256.** { *; }
this line will keep proguard from removing my public methods and variables..
-keepclassmembers class classpath.** {
public *;
}
you need to write column name for atlest id... because it will search for it and will proguard change it's name... so you need to define column name id for primary key..

Related

spring-data-couchbase error while finding all documents with PageRequest

Using Spring Data Couchbase I created a very simple repository
public interface UserDao extends PagingAndSortingRepository<User, String>
This should allow me to execute a paged findAll as follows:
Page<User> userResult = repo.findAll(new PageRequest(1, 20));
However the the following is always thrown:
Exception in thread "main" java.lang.IllegalStateException: Unknown query param: Page request [number: 1, size 20, sort: null]
at org.springframework.data.couchbase.repository.query.ViewBasedCouchbaseQuery.execute(ViewBasedCouchbaseQuery.java:47)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:337)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.couchbase.repository.support.ViewPostProcessor$ViewInterceptor.invoke(ViewPostProcessor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at $Proxy14.findAll(Unknown Source)
at com.polycom.cloudAxis.proxymanagement.model.Main.main(Main.java:41)
This doesn't happen if I create a Query and use the skip/limit/startKeyDocId, but would like to use PagingAndSortingRepository if possible.
Any idea what could be wrong? Thanks for all friendly help :)
i also had this same issue, here was the approach i took. its actually a very small change to the core implementation (which currently only support Query object types), essentially all I did was add another instance of check:
if (param instanceof Query) {
query = (Query) param;
} else if (param instanceof Pageable) {
pageable = (Pageable) param;
}
then added the logic for paging here, its been working so far but i havent fully vetted it so any comments from the community would be appreciated.
if (pageable != null) {
CouchbaseClient client = operations.getCouchbaseClient();
View view = client.getView(designDocName(), viewName());
// Paginator p = new Paginator(client, view, query,
// pageable.getPageSize());
Paginator paginator = client.paginatedQuery(view, query, pageable.getPageSize());
// now we need to goto the start point
ViewResponse viewResponse = null;
// views are 0 base
int i = 0;
while (paginator.hasNext()) {
viewResponse = paginator.next();
if (pageable.getPageNumber() == i++) {
LOGGER.debug("Found the response for this page: {} ", i);
break;
}
}
if (viewResponse == null) {
LOGGER.debug("no view response so leaving now");
return null;
}
Class<?> type = method.getEntityInformation().getJavaType();
final List result = new ArrayList(viewResponse.size());
for (final ViewRow row : viewResponse) {
result.add(operations.findById(row.getId(), type));
}
return result;
}
To get this wired up i had to do some things i didnt want to :D, i wanted to just override one method however to get to it required me to override many other things, so i ended up copying a little bit of code, ideally i would like to get this added as part of https://jira.spring.io/browse/DATACOUCH-93
And the whole impl here:
public class DCORepositoryFactory extends CouchbaseRepositoryFactory {
CouchbaseOperations couchbaseOperations;
MappingContext<? extends CouchbasePersistentEntity<?>, CouchbasePersistentProperty> mappingContext;
public DCORepositoryFactory(CouchbaseOperations couchbaseOperations) {
super(couchbaseOperations);
mappingContext = couchbaseOperations.getConverter().getMappingContext();
this.couchbaseOperations = couchbaseOperations;
}
#Override
protected Object getTargetRepository(RepositoryMetadata metadata) {
// TODO Auto-generated method stub
CouchbaseEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());
final DCORepository simpleCouchbaseRepository = new DCORepository(entityInformation, couchbaseOperations);
simpleCouchbaseRepository.setViewMetadataProvider(ViewPostProcessor.INSTANCE.getViewMetadataProvider());
return simpleCouchbaseRepository;
}
#Override
protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) {
return new CouchbaseQueryLookupStrategy();
}
/**
* Currently, only views are supported. N1QL support to be added.
*/
private class CouchbaseQueryLookupStrategy implements QueryLookupStrategy {
#Override
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) {
CouchbaseQueryMethod queryMethod = new CouchbaseQueryMethod(method, metadata, mappingContext);
return new PagingViewBasedCouchbaseQuery(queryMethod, couchbaseOperations);
}
}
private static class PagingViewBasedCouchbaseQuery extends ViewBasedCouchbaseQuery {
private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory
.getLogger(DCORepositoryFactory.PagingViewBasedCouchbaseQuery.class);
private CouchbaseOperations operations;
private CouchbaseQueryMethod method;
public PagingViewBasedCouchbaseQuery(CouchbaseQueryMethod method, CouchbaseOperations operations) {
super(method, operations);
this.operations = operations;
this.method = method;
}
/*
* (non-Javadoc)
*
* #see org.springframework.data.couchbase.repository.query.
* ViewBasedCouchbaseQuery#execute(java.lang.Object[]) added the ability
* to support paging
*/
#Override
public Object execute(Object[] runtimeParams) {
Query query = null;
Pageable pageable = null;
for (Object param : runtimeParams) {
if (param instanceof Query) {
query = (Query) param;
} else if (param instanceof Pageable) {
pageable = (Pageable) param;
} else {
throw new IllegalStateException(
"Unknown query param: (btw null is also not allowed and pagable cannot be null) " + param);
}
}
if (query == null) {
query = new Query();
}
query.setReduce(false);
if (pageable != null) {
CouchbaseClient client = operations.getCouchbaseClient();
View view = client.getView(designDocName(), viewName());
// Paginator p = new Paginator(client, view, query,
// pageable.getPageSize());
Paginator paginator = client.paginatedQuery(view, query, pageable.getPageSize());
// now we need to goto the start point
ViewResponse viewResponse = null;
// views are 0 base
int i = 0;
while (paginator.hasNext()) {
viewResponse = paginator.next();
if (pageable.getPageNumber() == i++) {
LOGGER.debug("Found the response for this page: {} ", i);
break;
}
}
if (viewResponse == null) {
LOGGER.debug("no view response so leaving now");
return null;
}
Class<?> type = method.getEntityInformation().getJavaType();
final List result = new ArrayList(viewResponse.size());
for (final ViewRow row : viewResponse) {
result.add(operations.findById(row.getId(), type));
}
return result;
} else {
return operations.findByView(designDocName(), viewName(), query, method.getEntityInformation()
.getJavaType());
}
}
/**
* Returns the best-guess design document name.
*
* #return the design document name.
*/
private String designDocName() {
if (method.hasViewAnnotation()) {
return method.getViewAnnotation().designDocument();
} else {
return StringUtils.uncapitalize(method.getEntityInformation().getJavaType().getSimpleName());
}
}
/**
* Returns the best-guess view name.
*
* #return the view name.
*/
private String viewName() {
if (method.hasViewAnnotation()) {
return method.getViewAnnotation().viewName();
} else {
return StringUtils.uncapitalize(method.getName().replaceFirst("find", ""));
}
}
}
#Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata repositoryMetadata) {
return DCORepository.class;
}
}

Table info to an ArrayList

I have created an sql database with a table containing information about Airplanes, I want to be able to take this information and insert it into an ArrayList of type Aircraft(object) although the different info in the sql table are different primitive types........can this be done?`package uk.ac.qub.sqldbflights;
This is the Aircraft object with all the attributes which are the
public class Aircraft {
/**
* private String containing the airline name of the aircraft
* -Can't be blank
*/
private int aircraft_number;
/**
* private String containing the flight number belonging to the aircraft
* -Can't be blank
*/
private String airline_company;
/**
* private String containing the aircrafts city of origin
* -Can't be blank
*/
private String departure_airport;
/**
* private int which holds the aircrafts fuel level
* -Must be over 0 and less than 100
*/
private float passenger_number;
/**
* private int containing the number of passengers aboard the aircraft
* -Must be over 0 and less than 300
*/
private float fuel_percentage;
/**
* private Boolean indicting wether the aircraft is in the landing queue or not
*/
private int flight_time_remaining;
/**
* private Boolean indicating wether the aircraft is landed or not
*/
private boolean in_queue;
private boolean is_landed;
public Aircraft() {
}
/**
* Song creation
* #param name -not null
* #param artist -not null
* #param album -not null
* #param genre- not null and one of Pop, Dance, Rock
* #throws IllegalArgumentException
*/
public Aircraft(int aircraft_number, String airline_company, String departure_airport, int passenger_number, float fuel_percentage, int flight_time_remaining, boolean in_queue, boolean is_landed)
throws IllegalArgumentException {
try {
// set name
this.setAircraft_number(aircraft_number);
this.setAirline_company(airline_company);
this.setDeparture_airport(departure_airport);
this.setPassenger_number(passenger_number);
this.setFuel_percentage(fuel_percentage);
this.setFlight_time_remaining(flight_time_remaining);
this.setIn_queue(in_queue);
this.setIs_landed(is_landed);
} catch (IllegalArgumentException ex) {
System.out.println("Unable to create song due to arguments passed");
throw ex;
}}
public int getAircraft_number() {
return aircraft_number;
}
public void setAircraft_number(int aircraft_number) {
this.aircraft_number = aircraft_number;
}
public String getAirline_company() {
return airline_company;
}
public void setAirline_company(String airline_company) {
this.airline_company = airline_company;
}
public String getDeparture_airport() {
return departure_airport;
}
public void setDeparture_airport(String departure_airport) {
this.departure_airport = departure_airport;
}
public float getPassenger_number() {
return passenger_number;
}
public void setPassenger_number(float passenger_number) {
this.passenger_number = passenger_number;
}
public float getFuel_percentage() {
return fuel_percentage;
}
public void setFuel_percentage(float fuel_percentage) {
this.fuel_percentage = fuel_percentage;
}
public int isFlight_time_remaining() {
return flight_time_remaining;
}
public void setFlight_time_remaining(int flight_time_remaining) {
this.flight_time_remaining = flight_time_remaining;
}
public boolean isIn_queue() {
return in_queue;
}
public void setIn_queue(boolean in_queue) {
this.in_queue = in_queue;
}
public boolean isIs_landed() {
return is_landed;
}
public void setIs_landed(boolean is_landed) {
this.is_landed = is_landed;
}
}
This is the code which makes the connection to the sql DB and trys to add the info to an arraylist...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class FlightsDbtoArrayList {
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
public static void main(String[] args) {
// Entering username to verify connection to SQL Server
String url = "jdbc:mysql://";
Connection con;
Statement statement1;
try {
Class.forName("com.mysql.jdbc.Driver");
//Catching any errors and printing a message to the user
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
// Entering username and password to verify connection to SQL Server
con = DriverManager.getConnection(url);
//Creating platform for a SQL query Statement
statement1 = con.createStatement();
//Creating and executing the designed SQL query statement
ResultSet results1 = statement1.executeQuery("SELECT aircraft_number, airline_company, departure_airport, passenger_number, fuel_Percentage, flight_time_remaining, in_queue, is_landed FROM flights");
//Displaying the results of the query to screen
printResults(results1);
con.close();
statement1.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
/**
* Method to display the results of the three SQL queries
* #param results
* #throws SQLException
*
*
*/
public ArrayList<Aircraft> allFlights() {
return allFlights;
}
/**
* set songs on the system
* #param allSongs
*/
public void setSongs(ArrayList<Aircraft> allSongs) {
allSongs = this.allFlights;
}
private static void printResults(ResultSet results) throws SQLException {
while (results.next()) {
int aircraft_number = results.getInt("aircraft_number");
String airline_company = results.getString("airline_company");
String departure_airport = results.getString("departure_airport");
int passenger_number = results.getInt("passenger_number");
float fuel_percentage = results.getFloat("fuel_percentage");
int flight_time_remaining = results.getInt("flight_time_remaining");
boolean in_queue = results.getBoolean("in_queue");
boolean is_landed = results.getBoolean("is_landed");
Aircraft a1;
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
a1 = new Aircraft(aircraft_number, airline_company, departure_airport, passenger_number, fuel_percentage, flight_time_remaining, in_queue, is_landed);
allFlights.add(a1);
System.out.println(allFlights);
}
}
}
`
Yes it is definitely possible to have list of objects(Aircraft) derived from database. But in this case your while loop inside the PrintResult has some errors.
You are creating list allFights within the while loop which will create new list in each iteration and add a1 to it so in the end you will only have a list with one aircraft details in it.
System.out.println(allFlights) will not give much desired output (or it might), but I would advice you should override toString() method in your AirCraft class.
Try to change your PrintResult method as following.
private static void printResults(ResultSet results) throws SQLException {
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
Aircraft a1;
while (results.next()) {
int aircraft_number = results.getInt("aircraft_number");
String airline_company = results.getString("airline_company");
String departure_airport = results.getString("departure_airport");
int passenger_number = results.getInt("passenger_number");
float fuel_percentage = results.getFloat("fuel_percentage");
int flight_time_remaining = results.getInt("flight_time_remaining");
boolean in_queue = results.getBoolean("in_queue");
boolean is_landed = results.getBoolean("is_landed");
a1 = new Aircraft(aircraft_number, airline_company, departure_airport, passenger_number, fuel_percentage, flight_time_remaining, in_queue, is_landed);
allFlights.add(a1);
//Instead of this line System.out.println(allFlights);
//write following code
For(AirCraft aircraft : allFlights){
System.out.println(aircraft.toString());
}
}
}
Edit 2: Write the following method in your AirCraft class.
#Override
Public String toString(){
String string;
//Write some code here so that you can represent you object using this method
//for example I am adding just the aircraft_number
string = getAircraft_number()+"";
return string;
}
Important: The toString() method I wrote is just an example you need to learn how to correctly write toString() method for any of your class. this and this are good starting point to learn that. And stop worrying about your your list of allFlights because as per this code it is getting created but you can not print it the way you are trying to.

ORMLite: Updating a foreign object field

For my current project I decided to use ORMLite (4.46). Currently, I'm experiencing some issues when saving data of a foreign object. Below, a example of my code. The field called "field" is not saved properly (The old data is displayed). Anybody an idea, what's wrong with this code?
Thank you!
Regards
Andreas
Some class:
DatabaseHelper databaseHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class)
branch.field = 123423;
Log.d("...", "field:" + branch.field); <-- new value of field is displayed
databaseHelper.getBranchDao().update(branch);
Other class:
DatabaseHelper databaseHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
databaseHelper.getFloorDao().refresh(floor);
databaseHelper.getBranchDao().refresh(floor.branch);
Log.d("...", "branch field:" + floor.branch.field); <-- old value of field is displayed
DatabaseHelper:
...
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application -- change to something appropriate for your app
private static final String DATABASE_NAME = "xy.db";
// any time you make changes to your database objects, you may have to increase the database version
private static final int DATABASE_VERSION = 1;
// the DAO objects we use to access the tables
private Dao<Branch, Integer> branchDao = null;
private Dao<Floor, Integer> floorDao = null;
private Context appContext;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
appContext = context;
}
/**
* This is called when the database is first created. Usually you should call createTable statements here to create
* the tables that will store your data.
*/
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
// Create tables for each domain object here!
TableUtils.createTable(connectionSource, Branch.class);
TableUtils.createTable(connectionSource, Floor.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
/**
* This is called when your application is upgraded and it has a higher version number. This allows you to adjust
* the various data to match the new version number.
*/
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
// Drop all tables of domain objects here!
TableUtils.dropTable(connectionSource, Branch.class, true);
TableUtils.dropTable(connectionSource, Floor.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
/**
* Delete and re-create database when user is changed
*/
public void reCreateDB(){
//delete the database (onCreate() will be called if database is needed again)
appContext.deleteDatabase(DATABASE_NAME);
}
/**
* Returns the Database Access Object (DAO) for our domain class. It will create it or just give the cached
* value.
*/
public Dao<Branch, Integer> getBranchDao() throws SQLException {
if (branchDao == null) {
branchDao = getDao(Branch.class);
}
return branchDao;
}
public Dao<Floor, Integer> getFloorDao() throws SQLException {
if (floorDao == null) {
floorDao = getDao(Floor.class);
}
return floorDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
}
}
Floor:
...
public class Floor {
#DatabaseField(generatedId = true)
public int id;
#DatabaseField(foreign = true, canBeNull = true, foreignAutoRefresh = true, maxForeignAutoRefreshLevel=5)
public Branch branch;
public Floor(){}
}
Branch:
....
public class Branch {
#DatabaseField(generatedId = true)
public int id;
#DatabaseField(canBeNull = true)
public int field;
#ForeignCollectionField(eager = true, maxEagerLevel = 99)
private ForeignCollection<Floor> floors;
public Branch(){}
public ForeignCollection<Floor> getEmptyFloorCollection() {
try {
return MainActivity.getDatabaseHelper().getBranchDao().getEmptyForeignCollection("floors");
} catch (SQLException e) {
Log.e("DatabaseHelper", "SQL Exception: " + e.getLocalizedMessage());
return null;
}
}
public ForeignCollection<Floor> getFloors() {
if(floors == null) floors = getEmptyFloorCollection();
return floors;
}
public void setFloors(ForeignCollection<Floor> floors) {
this.floors = floors;
}
}

Loss of types in the abstract factory

I am developing an java application that accepts SOAP message. The body of the SOAP contains various documents. From time to time their number varies (depending on the version of the album).
For their analysis I am trying to apply a pattern Abstract Factory.
But my implementation, I ran into a problem:
IAlbumFactory albumFactory = AlbumFactory.buildDocument (Album.A_5_0_12);
The first parameter has I can point to any type of enum CustomDocument (although CustomDocument.DO1 only valid Du). And this error only shows up in RunTime
IDocumentEntity <Du, org.w3c.dom.Element> documentEntity =
albumFactory.getWorker (CustomDocument.DO1);
how to avoid it?
Some class:
public interface IDocumentEntity<T,E> {
T getReport(E e) throws JAXBException ;
}
public interface IAlbumFactory {
IDocumentEntity getWorker(CustomDocument document);
}
/**
* Class for convert document DO1 (album 5.0.12) from org.w3c.dom.Element to Du
* entity type
*
* #author uas
*/
public class DO1_5_0_12 implements IDocumentEntity<Du, org.w3c.dom.Element> {
protected DO1ReportInType unmarshall(org.w3c.dom.Element e) throws JAXBException {
DO1ReportInType resultType = null;
JAXBContext result = JAXBContextHelper_DO1.getJaxbContextInstance();
Unmarshaller u = result.createUnmarshaller();
Object c = u.unmarshal(e);
if (c instanceof JAXBElement) {
JAXBElement jaxbe = (JAXBElement) c;
resultType = (DO1ReportInType) JAXBIntrospector.getValue(jaxbe);
}
return resultType;
}
#Override
public Du getReport(org.w3c.dom.Element e) throws JAXBException {
DO1ReportInType dO1Report = unmarshall(e);
DO1ReportIn_JAXBtoORCL btoORCL = new DO1ReportIn_JAXBtoORCL(dO1Report);
return btoORCL.getReport();
}
}
Factory for Album 5_0_12.
public class AlbumFactory_5_0_12 implements IAlbumFactory {
/**
* Return documentWorker byn CustomDocument value
* #param customDocument
* #return throws IllegalArgumentException
*/
#Override
public IDocumentEntity getWorker(CustomDocument customDocument) {
IDocumentEntity doc = null;
switch (customDocument) {
case DO1:
doc = new DO1_5_0_12();
break;
case DO2:
doc = new DO2_5_0_12();
break;
default:
throw new IllegalArgumentException("For album 5.0.12 " + customDocument.DocName() + " not support");
}
return doc;
}
}
public class AlbumFactory {
private AlbumFactory() {
}
public static IAlbumFactory buildDocument(Album album) {
IAlbumFactory result = null;
switch (album) {
case A_5_0_12:
result = new AlbumFactory_5_0_12();
break;
default:
throw new IllegalArgumentException("This version " + album.AlbumName() + " is not support");
}
return result;
}
}

How to intercept and change sql query dynamically in mybatis

I use mybatis to perform sql queries in my project. I need to intercept sql query before executing to apply some changed dynamically. I've read about #Interseptors like this:
#Intercepts({#Signature(type= Executor.class, method = "query", args = {...})})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
And it really intercepts executions, but there is no way to change sql query since appropriate field is not writable. Should I build new instance of whole object manually to just replace sql query? Where is the right place to intercept query execution to change it dynamically? Thank.
I hope it will help you:
#Intercepts( { #Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class
})
})
public class SelectCountSqlInterceptor2 implements Interceptor
{
public static String COUNT = "_count";
private static int MAPPED_STATEMENT_INDEX = 0;
private static int PARAMETER_INDEX = 1;
#Override
public Object intercept(Invocation invocation) throws Throwable
{
processCountSql(invocation.getArgs());
return invocation.proceed();
}
#SuppressWarnings("rawtypes")
private void processCountSql(final Object[] queryArgs)
{
if (queryArgs[PARAMETER_INDEX] instanceof Map)
{
Map parameter = (Map) queryArgs[PARAMETER_INDEX];
if (parameter.containsKey(COUNT))
{
MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
BoundSql boundSql = ms.getBoundSql(parameter);
String sql = ms.getBoundSql(parameter).getSql().trim();
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),
getCountSQL(sql), boundSql.getParameterMappings(),
boundSql.getParameterObject());
MappedStatement newMs = copyFromMappedStatement(ms,
new OffsetLimitInterceptor.BoundSqlSqlSource(newBoundSql));
queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
}
}
}
// see: MapperBuilderAssistant
#SuppressWarnings({ "unchecked", "rawtypes" })
private MappedStatement copyFromMappedStatement(MappedStatement ms,
SqlSource newSqlSource)
{
Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms
.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
// setStatementTimeout()
builder.timeout(ms.getTimeout());
// setParameterMap()
builder.parameterMap(ms.getParameterMap());
// setStatementResultMap()
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
String id = "-inline";
if (ms.getResultMaps() != null)
{
id = ms.getResultMaps().get(0).getId() + "-inline";
}
ResultMap resultMap = new ResultMap.Builder(null, id, Long.class,
new ArrayList()).build();
resultMaps.add(resultMap);
builder.resultMaps(resultMaps);
builder.resultSetType(ms.getResultSetType());
// setStatementCache()
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
private String getCountSQL(String sql)
{
String lowerCaseSQL = sql.toLowerCase().replace("\n", " ").replace("\t", " ");
int index = lowerCaseSQL.indexOf(" order ");
if (index != -1)
{
sql = sql.substring(0, index);
}
return "SELECT COUNT(*) from ( select 1 as col_c " + sql.substring(lowerCaseSQL.indexOf(" from ")) + " ) cnt";
}
#Override
public Object plugin(Object target)
{
return Plugin.wrap(target, this);
}
#Override
public void setProperties(Properties properties)
{
}
}
You may consider using a string template library (eg Velocity, Handlebars, Mustache) to help you
As of to date, there is even MyBatis-Velocity (http://mybatis.github.io/velocity-scripting/) to help you to do scripting for the sql.
Depending on the changes you want to make, you may want to use the dynamic sql feature of mybatis 3

Categories