I am attempting my first Java project (just started learning it/OOP). I have built a thermostat circuit that I can get the temperature from using a driver, and am now in the process of designing a Java program that interfaces with the thermostat and inserts the data into a mysql DB.
I'm attempting to do this properly, and so have come up with a basic UML diagram of my classes/objects and how they interact.
I plan on using a database interface class which will extend a database connection class. This database interface will insert into the DB, and the database connection constructor will create the database connection.
I will also have a thermostat class which interfaces with the thermostat itself, it will have 2 private variables, temperature and humidity. It will have the method update temp, which will update the private variables. The get temp method will be provide the interface to these private variables.
Finally the control class is composed of the thermostat and database interface classes, and will call the methods of both classes to get the temp/humidity data into the database.
UML diagram:
Do you have any thoughts? I don't know how good this design is. Is the controller interacting with the other classes in the correct way?
Thank you for your time.
X.
First, for someone that just "just started learning it/OOP" it look pretty good!
One thing that jumps out as me: It works, but seems idiomatically wrong (we don't usually do it that way) is having your DAO (data access object, "Database Interface") extend the class that creates the connection. Instead is should use this class-- or better, the result of this class, a connection.
Why? As you write more DAO classes (in this project, or others) you'll probably find that these are two separate concerns:
(1) code that deals with the temp/humidity table and related SQL and, temperature specific logic and exceptions.
(2) code that is responsible for connecting to a database and creating connection objects.
If you have a databaseInterface.setConnection(Connection c) method, you'll find that your databaseInterface class is more reusable. You can set connections from various sources, create multiple instances with different connections, inject mock connections in your test cases, etc.
These are ideas that I have learned over years and usually apply to projects with tens to hundreds of data access classes. Its not a terribly significant in a small project, but is a possible improvement nonetheless.
EDIT: Possible Controller constructor:
// My hardware interface
private Thermostat thermostat;
// My temperature DB tables interface
private TemperatureDAO temperatureDAO;
public Controller() {
thermostat = new Thermostat();
temperatureDAO = new TemperatureDAO();
// As the controller, I get to decide what connection the application uses.
temperatureDAO.setConnection(new ConnectionProvider().getConnection());
}
In this code the controller is dictating which DB connection is used, not each individual DAO.
Related
I'm relatively new to Android programming and I have little to no experience with SQL and its interaction with Java altogether, but I couldn't find the answer I was looking for either in tutorials or Google's developer pages.
I'm wondering how I can create a database in Android to store a variety of String and int variables without creating duplicate databases. I understand the schema and contract class concept presented by the development page, but I don't understand how I am supposed to call a class method so that only a single database is created (preferably at first app launch) without several instances being created.
My main question: What sort of setup is recommended to create a database that can be referenced from other classes, exists from the very first launch of the app, and remains private (although to be honest it's not a huge priority)?
but I don't understand how I am supposed to call a class method so
that only a single database is created (preferably at first app
launch)
In Android, database is created only once and then whenever you will try to perform CRUD operations and selects statements, always you will have only one database created. It's same for table(s) in database. Once table(s) are created, they won't be created again (so be careful if you'll add new columns to table during implementation if table was created before without new columns1). Moreover if user explicitly will delete application data - only in this case, database and table(s) will be created again because they were deleted.
What sort of setup is recommended to create a database that can be
referenced from other classes, exists from the very first launch of
the app
In the moment when you'll call for example getWriteableDatabase() or getReadableDatabase() database and table(s) will be created - only at this time! Only once. No more (except1. After that, whenever you'll try to attempt to read or write from / to database your database will be opened with specific permissions (read-write or read-only - it depends how which method you called) and you can perform actions.
without several instances being created.
Database is only one - it's not duplicated (physically), absolutely but when application logic is not designated correctly, there may appear multiple instances of database and this fact is not very good and usually a nightmare of many beginners with Android and SQLite.
But solution exists and it's not hard to implement -> Singleton. Design pattern Singleton is "pretty cool tool" for our goal - ensure that only one instance of database will be ever created.
Here is implementation of Singleton itself:
public class DataSource extends SQLiteOpenHelper {
private static DataSource instance;
public static final DataSource getInstance(Context c) {
if (instance == null) {
instance = new DataSource(c);
}
return instance;
}
}
1 If you added new columns to table at the time when database and table were created before (how i mentioned above the're created only once) it may cause application exception so exactly here you have to clear application data or implement onUpgrade() method.
Try using an ORM like ActiveAndroid. While not recommended for extremely complex apps, using an ORM will make using and managing a database much easier for someone without much database experience (and can make your code more readable as well).
When I did my first SQLite DB in Android, I used this site to get me trough the basics.
To answer your question, take a look at the DatabaseHelper Class. You will see that you have to specify a DB name (filename).
private static final String DATABASE_NAME = "commments.db";
Android will automatically create the DB if it's not existent (newly installed app) and will reuse it if it's there. As long as you use always the same file (and don't mess up the tables), your DB will remain intact.
Also, for security, the DB is stored in the app's data. Not accessible with a file browser (unless you are rooted). You can download the DB via adb if you really need to. There is tons of documentation on how to gets apps private data.
Hope this helps!
Ok guys,
Here's a question more of principle than of fact.
I have a data-structure that is used on both a client and a server.
However, on the server end, I want functionality to create the client from some sort of datastore (at the moment SQL, it used to be serialized data, but it doesn't matter).
Originally I had a giant class called something like 'Datastore' which had static methods for retrieving any stored object.
While not terrible, that's not exactly OO, and it's not exactly scalable.
So I considered moving these static methods to the datastructures themselves. However, that would mean that the shared client libraries then knew how to retrieve objects from my datastore - which is kind of silly.
So I'm now creating new classes for each object in a new datastore package, each of which holds the static methods for retrieving one object from the datastore.
My question is, how do I signify the relationship between these data manager classes and the objects that they retrieve?
Functionally, it doesn't matter. The static methods work fine. But I want to indicate to future me and other future developers that the data retriever class and the object class are tightly linked.
My first thought was to make the data retriever extend the data structure. However, that would then require declaring default constructors and implying that the class could be instantiated - which it can, but why would you?
My second thought was to then make the data retriever extend the data structure, but be abstract. That would flag the tight relationship to other developers, and also make it clear that only new methods were being added, no new fields.
However, extending a concrete class with an abstract class seems really strange, and Java still make me create default constructors.
My question is, how do I signify the relationship between these data manager classes and the objects that they retrieve?
This is a standard industry problem: how to get data from a database into an application. The common solution is to use the DAO pattern, which is to have a Data Access Object (DAO) responsible for retrieving an object from the database.
If you are retrieving an employee's personal information, salary, etc., you could have an EmployeeDAO class which would retrieve it from the appropriate table. If you are retrieving a company's profits, locations, number of employees, you could have a CompanyDAO class to retrieve this object from the database.
On top of this could be a service layer, for performing business logic; also, a DAO manager, for instantiating the DAOs and returning references to whatever classes need them.
You can still merge concepts of Repository Design Pattern and DAO Pattern, taking the application in a more concise abstraction level. The Repository acts as domain-level abstraction. Example:
public class EmployeeBO implements EmployeeRepository { // implementation of a Business Object Domain-model
#Inject
private EmployeeDAO employeeDAO; // really implementation of data access
#Override
public boolean createEmployee(String name){ // domain-oriented method
// ... some validation
employeeDAO.save(new Employee(name)); // really data access/persistence implementation
}
}
I'm writing a database manager layer of a web service.
I have to decide ho to implement my library: this is the situation.
I have a class, PersistenceUnit:
private static RazoooCore rc;
private static DBInstance db;
protected ODatabaseDocumentTx getDb(){return db;}
protected RazoooCooore getRc(){return rc;}
public static void startPersistence (){
//here I get an instance of rc and db
}
that start my db service and allow me to connect to it. What I want is to write class that implement persistence method, like addUser(...), or deleteFile(...) and so on.
My doubt is how to realize these method. Because I have two big classes of operations (one on users and the other on files) I thought to create to class (User and File) and to implement public static method on them, or, and is the same, create two singleton.then the application layer will have to call method without having to create and destroy object each time.
Is this a good way to realize my layer? Is, in this way, well handled concurrency, or is there a better way (perhaps a pattern) to maximize performance and multithreading?
Certainly this is not a memory-bound layer, because upper layer doesn't have to continuously
create object.
Thank you
There were lots of discussions about if an object should (or not) be responsible of persist itself, this is, should an User class have a Save method? Well, it depends. However, currently we hardly ever see that pattern.
I think the persistence logic has to be in a data access layer, probably in repositories (UserRepository and FileRepository). And this has nothing to do with neither performance nor multithreading because both issues (performance and concurrency) are in the database.
That´s my opinion.
Coming from a perl background and having done some simple OO in that, I am struggling to grasp the android/Java way of interacting with databases.
In my experience I would create a file or class for each object, and an object would match/represent a table in the database.
Within that object would be a constructor, variables for the data, methods/functions to return individual variables but also the DB queries to read and write from the DB, doing all the necessary CRUD functions.
From what I read on the web, in Android I would create the objects similarly but without the DB interaction. This would happen in either a single class with all my DB functionality in it, or multiple DB classes, one per table.
My questions are all to do with best practices really.
Can I do my app how I would in Perl. If not why not, and if so,what are the pros and cons and limitations?
What do the terms DAO, Adapter and POJO mean?
Should I make an application class and globally declare the DB there?
Should I create one handler in each activity or in the application class only?
I have read so many tutorials now my head is spinning, all with a diff way of doing things and mostly only with a single table and few showing actual objects directly representing tables.
I'm happy to hear opinion, be linked to tutorials or just have the odd term explained.
Thanks in advance
If I am reading you correctly, ORMLite may be your best bet. It uses reflection for database creation and maintenance which seems to be how Perl does it.
POJO is Plain old java object which means it is just a normal class.
An adapter would be the class that contains the CRUD stuff and manages the database itself. There are quite some patterns around in the Android world and talking about can fill a book.
I prefer the pattern, that I open the database once in my Application class and I never close it (Android does that when it kills the app). A sample from a very old project I had might show you the basic idea.
DAO is Data Access Object and can fill dozens of books. If would just start programming and see where you're heading...
The other poster is correct in putting out ORMLite as a great way to manage code relationships that mirror your database. If you're looking to do it on your own, however, there are a ton of ways to do things, and I wouldn't say the community has really gravitated toward one over the other. Personally, I tend to have my entities represented by Plain Old Java Objects (POJO - implies no special connectivity to other things, like databases), where the various attributes of the table correspond to field values. I then persist and retrieve those objects through a Data Access Object (DAO). The DAO's all have access to a shared, open, Database object - against which they execute queries according to need.
For example: if I had a table foo, I would have a corresponding entity class Foo, with attributes corresponding to columns. class FooDAO would have mechanisms to get a Foo:
public Foo getFooById(Integer id) {
String[] selection = {id.toString()};
String limit = "1"
Cursor c = mDatabase.query(FOO_TABLE, null, "id=?", selection, null, null, null, 1);
// Create a new Foo from returned cursor and close it
}
A second entity bar might have many foo. For that, we would, in Bar, reference the FooDAO to get all of bar's member foo:
public class Bar {
public List<Foo> getFoo() {
return mFooDAO.getFooByBar(this);
}
}
etc... the scope of what one can do in rolling your own ORM like this is pretty vast, so do as much or as little as you need. Or just use ORMLite and skip the whole thing :)
Also, the android engineers frown on subclassing Application for globally accessible objects in favor of Singletons (see hackbod's answer), but opinions vary
In my java program, I had a book class and a library class.
The library stores the book object in an array list and then I display it on the screen.
I can add the book and remove the books using functions.
I also use AbstractJtableModel for adding and removing the books.
But now I want to use a database, MySQL, instead of an array list.
How should I change my program?
well, you need to write the whole application :)
you need to create a db, with at least one table, you need to add mysql jdbc library to classpath and using jdbc you can insert/select/update/delete data from DB.
Alternatively, you need to add jdbc and use ORM framework like Hibernate, but depending on your Java knowledge this way can be harder (but easier to maintain in future, if you create big application). Here you can download simple hibernate application, which does CRUD operations with Honey :), you can extract interface similar to suggested by Javid Jamae from TestExample class, and exchange Honey class with Book according to your needs
You might consider using the Data Access Object (DAO) pattern. Just do a Google search and you'll find tons of articles on the topic. Essentially, you'll create a LibraryDao interface with methods like:
public interface LibraryDao {
public void storeLibrary(Library library)
public Library loadLibrary(long id)
public List<Library> searchByTitle(String title)
//...
}
You can implement this interface with straight SQL, or you can use an Object Relational Mapping (ORM) tool to implement it. I highly recommend reading up on Hibernate and the JPA specification.
Abstract the retrieval and storage of the books into a class by itself - you don't want that persistence logic intermingled with your business logic. I'd suggest creating an interface called something like "BookStorageDAO" and then you can have various implementations of that interface. One implementation may be to store the books in an ArrayList while another may be to store the books in a Database.
In this way, you can utilize the interface in your business logic and swap out the implementation at any time.
You would still use the ArrayList in your GUI to persist and display the data. The difference would be you need logic to save and load that ArrayList from a database so that the data is stored even after the program ends.
Side note, extends DefaultTableModel as opposed to AbstractJtabelModel. It completes some of the methods for you.
You don't need a DAO per se, but those answers aren't wrong.
Separation of Concern
What you need to do is separate your application based on concern, which is a pattern called separation of concern. It's a leak to have concerns overlap, so to combat this, you would separate your application into layers, or a stack, based on concern. A typical stack might be include:
Data Access Layer (read/write data)
Service Layer (isolated business logic)
Controller (Link between view and model)
Presentation (UI)
etc., but this will only partly solve your problem.
Program To The Interface
You also (as the others have mentioned) need to abstract your code, which will allow you to make use of dependency injection. This is extremely easy to implement. All you have to do is program to the interface:
public interface PersonService {
public List<Person> getAllPersons();
public Person getById(String uuid);
}
So your application would look like this:
public class PersonApp {
private final PersonService personService;
public PersonApp(PersonService personService) {
this.personService = personService;
}
}
Why is this better?
You have defined the contract for interacting with the Person model in the interface, and your application adheres to this contract without having any exposure to the implementation details. This means that you can implement the PersonService using Hibernate, then later decide you want to use JPA, or maybe you use straight JDBC, or Spring, etc. etc., and even though you have to refactor the implementation code, your application code stays the same. All you have to do is put the new implementation on the classpath and locate it (tip: the Service Locator pattern would work well for that).