In Java, entity objects are classes that represent data from your table. From an object-oriented perspective, these objects are built to encapsulate your data in the real-world problem domain.
There are two different ways you can work with entity objects:
The first approach is more flexible, but it doesn’t offer security for the type values. Also, it’s possible to make a mistake setting the data. It also requires you to remember the names of the columns.
The second approach is much more appealing in terms of the readability and understandability of the code. It also offers type safety.
The main drawback here is the necessity to write data binding objects (or entity objects if you prefer) that will represent the particular table. And what if you have a very large number of tables in your application, and every table consists of many columns? The amount of such tedious work could be significant. But don’t fret, Backendless is already doing it for you!
Let’s take a look at an example.
1) First, create a table. Set the schema to match the following screenshot. You may also download it with the prepared data and import it into your Backendless app.
2) Next, go to the “Code Generation” section and download the generated entity classes for your tables.
You also can also download the archive later as it is saved in your Files.
3) Unpack the downloaded archive completely, or extract only the necessary files. In our example, we need only the file called Car.java
4) Add the class file to your project.
5) That’s all! Now you can look through and try simple code examples, as below.
Car car1 = new Car(); car1.setBrand( "Volkswagen" ); car1.setBody( "jeep" ); car1.setModel( "Toareg" ); car1.setColor( "dark red" ); car1.setCondition( "new" ); car1.setFuel_type( "gasoline" ); car1.setEngine_capacity(3000); car1.setTransmission( "auto" ); car1.setIssue_date( Date.from(LocalDate.of( 2017, 1, 1).atStartOfDay( ZoneId.systemDefault() ).toInstant()) ); car1.save();
Car firstCar = Car.findFirst(); firstCar.removeAsync( new AsyncCallback<Long>() { @Override public void handleResponse( Long response ) { System.out.println("Deleted successfully."); } @Override public void handleFault( BackendlessFault fault ) { System.out.println("Cannot delete, because of: " + fault); } } );
Car lastCar = Car.findLast(); lastCar.setCondition( "used" ); lastCar.save();
Car foundById = Car.findById( "20789D18-C480-46A1-FF32-921477BBA300" );
DataQueryBuilder dqb = DataQueryBuilder.create() .addProperty( "condition" ) .setWhereClause( "fuel_type = 'electro'" ); List<Car> listOfCars = Car.find( dqb );
In this article, we showed you how to generate Java classes from your data and then access them with code. Thanks for reading.