Java and mySQL, why create class objects with data from the database? - java

So I have a homework assignment to build a console application in Java while utilizing mySQL databases.
Our teacher wants us to use objects and ArrayLists, as Java is an "object oriented language".
I am not sure why I must parse the mySQL ResultSets into objects, and not print them directly in my methods in a nice printf format.
Similarly, why should I make class objects when inserting new data and not altering the database directly through my connection.
Can someone please explain and point me in the right direction.
I don't need any code. Just trying to understand.

One printf method for a ResultSet is not the correct way to implement! A resultset can have a different amount of different types of data.
The correct way would be to parse them to an object. For each table you might have an own class with constructor. For example:
You have a table 'Person' with attributes Name, age, address. Then you create a constructor
public Person(String name, int age, String address){}
or you could create a static method to parse like this:
public static Person parseFromResultSet(ResultSet r) throws ParseException {}
and then you can even write your own 'PersonParseExcpetion'.

"I am not sure why I must parse the mySQL ResultSets into objects, and
not print them directly in a nice printf format. Similarly, why should I make class objects when inserting new data and not altering the database directly through my connection."
...mostly because in a real-world application you're likely to do a lot more with the records than just print them directly to the console, and at that point it's useful to put them into a solid data structure you can move around and manipulate easily.
It can also make the code easier to maintain - real-world apps get updated and altered lots of times usually, and may contain a lot of different data types and structures, some of which may be complex representations consisting of several other structures put together - and it's easier to build a complex object if you already have a lot of smaller objects to make it from (imagine building furniture from ready-made sections rather than starting by sawing all the planks and making all the screws yourself).
You can think of it as an intermediate layer between what's on screen and what's in storage - which, in more complicated applications, will not always be structured or displayed in the exact same way as each other, hence the need for an intermediary. Sometimes the display and the storage will not even be on the same computer (like in websites such as this one).
So I imagine the purpose of this assignment might be to get you used to using those structures, but without making the overall goal too complicated. The true purpose of the exercise is not always the obvious one.

Related

How to store the arguments for a large amount of objects?

What I plan to do is create a large set of objects (~500). Currently I have a large Java file in which I create all objects in the following form:
MyCollection.add(String name, int strength, int size, int price);
But with this it takes a lot of space and I don't think it is the best way.
I don't really know my way around in this area. How is such a problem normally handled? Would it make sense to create a CSV file or another database?
Depends on where this data comes from. Do you generate it on runtime? If so - consider abstraction, so that you define a proper structure of objects and encapsulate this data and the process of creating it properly. If the data is static then yes, a database of any sort makes more sense. Specifically this means making your data persistent and simplifying the process of reading it as much as possible, e.g. reading the data via loop, encapsulating it in an objcect MyFancyEntry, then adding it to your collection.
You are in my opinion also right about 500 manual add calls on a Collection being bad design. The reason is simple - maintainability.
It is hard to change the structure quickly, if upon a structural change you suddenly need to edit 500 lines by hand.
There is also more room for mistakes, when you have so many identical repeating lines.

Extend PostgreSQL by index structure, data types, retrieval types, etc. with Java?

I learned that PostgreSQL is written in C. I would like to extend it by
a customized index structure
a customized nearest neighbor retrieval (with various distance functions)
custom data types
I feared so far to use PostgreSQL because it is written in C. However, I've seen on the PostgreSQL about page (http://www.postgresql.org/about/) that they support "library interfaces" e.g. for Java. Can I, thus, use Java to implement (at least) a nearest neighbor retrieval and custom data types (I guess not the index structure since it is quite low-level)?
The answer here is "it's complicated." You can actually go quite far with a procedural language (including pl/java) but you are never going to get quite the flexibility you can get with C. What is fundamentally missing is being able to do proper indexing support in PL/Java because one cannot create new primitives. For quite a bit more, you may want to look at my blog although most of the examples are in pl/pgsql.
Types
Now you can actually get very far with PL/Java (or PL/Perl, or PL/Python, or whatever you like) but there are some things that are going to be out of reach. This is also a very high overview of what is possible with a procedural language in the db and what is not.
There are two effective ways you can work with types in procedural languages. You can work with domains (subtypes of primitives), or you can work with complex types (objects with properties each of which is another type, either a primitive, a domain or a complex type itself). In general you cannot really do much in terms of indexing complex types themselves but you can index their members. Another thing that is not safe to do is output formatting, but you can supply other functions to replace this.
For example, suppose we want to have a type for storing PNG files and processing them for certain properties in the database. We might do this in the following way:
CREATE DOMAIN png_image as bytea check value like [magic number goes here];
We could then create a bunch of stored procedures to process the png in various ways. For example we might look for orange near the top in a function is_sunset. We might be able to do something like:
SELECT name FROM landmark l
JOIN landmark s ON (s.name = 'San Diego City hall'
and ST_DISTANCE(l.coords, s.coords) < '20')
WHERE is_sunset(photo)
ORDER BY name;
There is no reason that is_sunset could not be handled in Java, Perl, or whatever language you like. Since is_sunset returns a bool, we could even:
CREATE INDEX l_name_sunset_idx ON landmark (name) where is_sunset(photo);
This would speed up the query by allowing us to cache the index of names of photographs of sunsets.
What you can't do in Java is create new primitive types. Keep in mind that things like index support is at the primitive level, and therefore you can't, for example, create a new ip address type supporting GiST indexing (not that you'd need to, since ip4r is available).
So to the extent you can re-used and work with what primitives are already existing, you can do your development in Java or whatever you like. You are really limited only by what primitives are available, and enough people have written new ones in C you may not need to touch these at all.
Indexes
Index code is pretty much C only as are the primitives. You cannot customize index behavior in a procedural language. What you can do is work with the primitives of other developers and so forth. This is the area where you are most likely to have to drop to C.
(Update: As I think about it, it may be possible to hook into existing index types to add support for various indexes based on other PL functions, using the CREATE OPERATOR CLASS and CREATE OPERATOR commands. I have no experience doing this though.)
Performance
keep in mind that PL/Java means you are running a JVM in each backend process. In many cases if you can do a what you want to do in pl/pgsql you will get better performance. The same goes with other languages of course too, because you need an interpretor or other environment in the backend process.

LinkedList vs ArrayList - asking point of view for implementation ideas

i want to use a list which will store objects of some type (lets say for simplicity - books) so i can show them in a listview object.
im kinda new to this, so i ask for the help of more advanced and experienced users about the following debates -
which one to use? linkedlist is something im familiar with. however, how do i make the app maintain the list? should i save the details of each object in a XML? if i do that, isnt it just better to use Arraylist? (please exclude in your answer things related to proccessing time).
if not via xml - how do i 'store' a list for later use even when the app is shut down and later on activated?
Thanks!
ArrayLists are good to use when you want random access via an indexed lookup. They're just as well suited for iterating through as LinkedLists.
OTOH, LinkedList doesn't need to be resized, it only runs out of room when you run out of memory to hold more nodes. If you have lots of data growth, or you're doing lots of sequential add/removes, then LinkedLists will win out in performance.
Sometimes you need both random access and growth, in those cases you need to make a judgment call on which criteria you want to be more performant.
In your current use case, I'd probably choose an ArrayList, you'll likely know how big the list should be, it won't be changing in size that often, and if you want to display this thing in a GUI, you're likely to need to do indexed lookups.
As far as storing the list, XML is as good a means as any, CSV files (or plain line-delimited text files), YAML, JSON and even class serialization are some alternatives, choose what's easiest and most convenient for you.
You must storage your data into SQLite. Android provides a very easy way. Look at this tutorial: http://www.vogella.de/articles/AndroidSQLite/article.html
I would prefer ArrayList over LinkedList because it has methods to manipulate the size of the array that is used internally to store the list
If i am going to use it as a stack, queue, or double-ended queue then I would use a LinkedList

How to store Objects from Database?

I am developing a java application which will be graphically depicting and organizing hundreds of objects. Each of these objects is loaded in from a SQL database, for use in this program.
I plan to keep a local copy of all the data, retrived through a JDBC connection, and then sort it locally (Likely with Merge Sort as that is my favorite)
How would you recommend I store the data locally? Ideally, it would be very easy to traverse, sort and compare to the source Database.
Currently, I have objects called Ideas which are populated from the database. Then, to display them, I create the same number of IdeaGraphics objects and add them to the appropriate JPanels. This can be quite slow at times.
You can implement the Comparator interface and use Collections.sort(), a modified mergesort, as shown here.
Maybe you already did that but it's not so clear in your question:
You can get almost as many instances of your data class (Ideas) but it's not the same at all with graphic classes. Limit the number of widgets and graphics to 1.
Build your own custom JPanel class, give it a list of Ideas and override the paintComponent method to draw all items in the list.
If your visible area is large, double buffer it.
I disagree with that and not good idea to holding lots of data in local Memory, with idea to simulate, excelent optimalized preprocesor from Sql Engine (most of todays engines), then basically faster as best EndUser PC
and if you have some WHATEVER permisions to the Database, then there are still exist option(s) to loading data from DbEngine to the Embedded database (on Memory), maybe to H2 or maybe JavaDB

Best way to store application data when data stored and data format could change in future versions?

I'm making an Android Java app game (although this question applies to all languages really) and hope to release the first version soon. I'm nervous about how I save data in my game. My problem is that, if in a later update, I decide to store more data or store the same data in a different way, I need to be careful I don't lose or corrupt data for users that upgrade (i.e. I want users to be able to use data created by an old version in the new version, like their high scores from before).
For example, say I want to save high scores in version 1 and I use a class like:
class Score { String name; int score; }
I then store the scores in an ArrayList and then, to save/load the scores, I serialize the ArrayList object.
In version 1.1, maybe I decide I want to store the date with each score. I could then update the Score object to include a date field and use default values for date if an old object does not include a date.
In version 1.2, maybe I decide that I want to store scores in an TreeSet instead and in version 1.3 perhaps I want to load/store scores online as well.
Anyway, my point is, are there any general tips for making my life easy here? I'm particularly concerned about situations from the above, where one person upgrades from version 1.1 to 1.2 and one person upgrades from 1.0 to 1.2. Testing all scenarios for data corruption sounds like a headache.
Is it really just a case of thinking really hard to pick something sensible and scalable to start with?
I'm thinking it might be easy to use a HashMap from String->Object as a general purpose storage object e.g. storage.put("HighScoreName1", "Bob"); storage.put("HighScorePoints1", 15);. Getting the information out is a little messier than if I'd have used a custom class, but it seems easy to add extra fields and so on without much work. Iterating over lists stored in this way isn't great though.
If you are using SQLiteOpenHelper, have a look at the onUpgrade method.
Called when the database needs to be
upgraded. The implementation should
use this method to drop tables, add
tables, or do anything else it needs
to upgrade to the new schema version.
Write a version number to your output stream before you write the serialized content. I also suggest writing a magic string sequence to the front of the stream (just something that you can say is yours - maybe 5 or 6 characters). So you'll write MAGIC, then you'll write your version number. Then you'll write your serialized content.
Reading from disk is fairly straightforward - read and confirm magic. Read version. Deserialize, then pass the deserialized content on to a handler based on magic.
A couple of words of caution here, though: If possible, keep the classes you use in the serialized stream simple (String, Integer, etc...). If you use your own classes, you must be insanely careful that you never have to refactor in a way that would change the package or classname.
As tempting as it may be to just write your business objects to storage using serialization, over the long run, this is almost always a mistake. Instead, I strongly recommend developing a Configuration object. Your app initializes itself form the Configuration object. When it's time to save, the app constructs a Configuration object. Then you never, ever, ever change a Configuration class once it ships. Just create a new one (sub-classing is fine).
By separating the reading and writing of configuration objects, you can do the following pretty easily:
Read old configuration
Initialize app with old config
Later...
App creates new configuration
Write new config to file
presto - instant file format update.
Obviously, this sort of thing is tough (a lot of work, anyway) to do with big, complex data graphs - but this is Android you are talking about, so your persistent state is probably not that complex.
Note that saving as XML, or even to a SQL database is just a different form of the above strategy.
There is no definite answer, but the term you are looking for is versioning. Best serialization implementations (and file formats) can have that working both ways (old versions of the application can read files of new versions, and vice-versa).

Categories

Resources