Search code examples
javaactivejdbcjavalite

How to return records from database using javalite?


I am using the following line to query the DB:

List<PostsCategories> postsCategories = PostsCategories.findBySQL("select category from posts_categories");

Instead of returning only [{category=Miscellaneous},....] it is returning extra info such as Model, table, attributes inside array.

I don't know why it works this way with activejdbc?

[Model: com.ngo.org10s.models.PostsCategories, table: 'posts_categories', attributes: {category=Miscellaneous}]

How do I simply return the required values?


Solution

  • It is because ActiveJDBC is an ORM == Object Relational Mapping. This means that a model instance contains all attributes to represent a single row in the table.

    The method findBySQL has JavaDoc that states:

    Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate themselves properly

    In other words, if an instance of a PostsCategories has just one attribute set, than this is not an ORM anymore.

    If you insist on getting just one attribute, use org.javalite.activejdbc.Base:

    List<Map> categories = Base.findAll("select category from posts_categories");