Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use db with a dialog 1

Status
Not open for further replies.

zooxmusic

Programmer
Nov 24, 2004
96
US
Hi, sorry for the very basic question but I feel I have a hole in my abc's. I want to make a plain old dialog that has to change the color of an item, actually many different items that are stored in many different JTables in a dialog.

What is the best way to interact with the db?

Do I create DBHandler class and pass and instance of that directly to the Dialog? Or do I make just a HandlerClass that I pass the DBHandler class into, then pass that regular HandlerClass into the Dialog for other purposes also?
And how do I pass the info, should I pass the TableModel or is that too specific?

So what I kindof see is something like this:

//the constructor would take the handler
Dlg(Handler handler)

//then to populate the dlg I could call a bunch of functions
handler.getSoAndSo();
handler.getAnotherSoAndSo(); //which would delegate this to the DBHandler and get the info from the db?

Dlg.save(tblModel)
or actually I have a few table models to save so I should
Dlg.save(map) //map of table models

and then the Handler class would just delegate it to the DBHandler. This seems like adding a middle man for no reason.


I know this seems so basic but I don't even know how to do this.

Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 

"...but I feel I have a hole in my abc's..".

You do have a hole. Seems like you have your A and C but you're missing your B, where:



A = UI

B = Application

C = Domain

D = Infastructure



Hi Zoo,

the first apps I wrote were very open. In other words, I use to do exactly what you are trying to do with the DBHandler thing controlled by UI. Open architecture is defined as serives accessible to any other subsystem, this allows you to write more effecient and compact code but defeats the principle of information hiding, better known as encapsulation.





Correct me if i am wrong, but your UI (Dialog) needs to display some items, some of which are highlighted.? You were asking if your UI should talked to a DBHelper which gets info from the database. At first, you might not see anything wrong with this, but it'll lead to architectural suicide.



I am not sure how DBHelper is implemented exactly, but I'll play the pessimistic role and assume that it is directly tied to DB access(C.R.U.D work). If so, DBHelper should be part of your Infastructure, hidden away by the layers sitting on top of it.



Let your UI talk to the Application Layer. The app layer provides high-level abstraction, hiding the details of the lower, more detailed subsystems. Application provies services, policies, coordinition and controllers that drive a specific instance of an application. In theory you can write 2 different applications that operate on the same domain model, and recently I have been worink on a content management project that allowed me to do so.



The application I am writing is a content management system, that is architectured in such a way, it provides 2 different applications to the same domain. One application revolved around my Domain model to render objects in the domain onto web pages for presentation. The second application sits right next to the Web Application and i call it the Admin tool. The admin allows me to minipulate and edit objects in the domain so that it can be reflected on the web.



Applications provides application specific services, they allow your UI to render presentations based on Domain objects, not things like datasets and data readers. In other words, Your UI should handle things like:



People, Places, Dogs, Orders, Characters, Bosses, Cars, etc etc.. Notice, I mentioned nothing about, IO Streams, datareaders, datasets, Why? Because those are low-level concepts hidden away by the application and domain layers.



Now that we are on the same page, let your UI deal with a Model. If your UI needs to render a list of People, let it interact with a Model in the application that repsents People, maybe a PeopleModel, or PeopleManager, which provides services to an Interface, the services are delegated to the domain to work out the intricate business requirements.





Your UI can get a list of people from the model and bind it to it's widgets, part of the binding can toggle highlighting based on some property of a Person.

Binding can be as simple as:


BINDING:
--------------------------------------
ComboBox.DataSource = PeopleManager.FindPeopleByName("Tom");
ComboBox.BindData();


OR:

Person aPerson = PeopleManager.FindPersonByID("1002");
Lable1.Text = aPerson.FirstName;



UI MINIPULATION/HIGHLIGHTING:
--------------------------------------
Checkbox1.checked = aPerson.isActive;
 
Thanx Ed,

Everytime I read something like you just told me I say "Oh yeah, of course, that makes total sense" then I find myself trying to code something here at work and I then say "How is this going to work?" and I get lost again. I have SAMS Teach yourself Object Oriented Programming in 21 hours it has helped. I haven't finished it yet but can look at the examples and apply them to my situation. But they are not exactly what I do here. I suppose my biggest problem is finding and example that is simple enough and easy enough to understand while talking to a database. I need and example of the whole DAL and the tiers you are mentioning in a plain and simple fashion so I can grasp the concepts at a basic level. Not some extravagent application that will take me 3 months to decipher because they never help me. I seem to always get lost. But not something too simple either because then I am still lost.

You wouldn't happen to know of any java examples that implement this kind of a structure without using some proprietary server like weblogic or even EJB's? Just some basic classes started from scratch that goes from the db to the client and back?

Brian


Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
Brian,
I don't blame you one bit. While you may read my responses and say it makes sense, implementing it is another story.

I'll tell you why, I think authors have covered every topic under the oo sun, but gave little attention to system partitioning /layered architecture.

Everything i mentioned above is very conceptual, feasible and i agree i have burned the bridge i once walked on by assuming you know how to retrofit all of this.

I have learned the hard way, by trying really hard to decipher bits and pieces from all books and figuring out why/what layers they belong to.

i will get back to you with a small sample on the layers and how it all works..

Edward JS
 
Your awesome, what I really need is to find a job where I can be an apprentice to someone like you so I can learn this stuff from a master;)

Brian


Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
Actually Ed maybe I don't need an entire example. Let me tell you my thought process and ask a few questions;

public class ClassThatActuallyConnectsToDb extends ParentDb
{
//would the connect function be in here?
void Connection getConnection()
{
//maybe an abstract parent?
return(super.getConnection());
}
//what does this return from its functions
// a disconnected CachedResultSet
// a user defined type
void ???? query(String sql)
{
//who will actually build the sql
//statement? This class?
}

//does this seem correct?
void ???? getDataById(long id)
{
return(query("select something from somewhere where
id = " + id);

}

void ???? getDataBy???(????? ?????)
{

}
}

//I kind of get lost already
//what would call the ClassThatActuallyConnectsToDb
//and what would you call this? The Domain?

public void ClassThatCallsClassThatActuallyConnectsToDb
{
private ClassThatActuallyConnectsToDb ctactdb = new ClassThatActuallyConnectsToDb();

//what would this return, the user defined type
//would xml be best?
public ???? getDataById(long id)
{
???? value = ctactdb.getDataById(id)
return(bindToXml(value));
OR
return(bindToUserType(value));
}

}


and would all of this be on the server side? Since we don't have a J2EE compliant server it would have to be a servlet.
Then how to get that data back to the client? Obviously I will have to use and OutputStream.

So the Servlet would have an instance of the ClassThatCallsClassThatActuallyConnectsToDb or is that already jumping too much?

then I would have like an Application module that would read in and write out on Streams

public class AppModule
{
public ???? write()
public ???? read()
}

and if I send back xml then I will have to have some XmlParser class instance in the app, correct?

I know this is getting long but I don't know any other way to get my thoughts clear enough. I will stop now but sum it up by asking if there is a number of main classes you can think of that would be used to query a db and return the result with a quick responsibility list. For example

DbConnector - connect to db
SqlBuilder - build sql and send to DbConnector
DbDataBinder - take result set from DbConnector and build (xml, userdefined type, etc...)
Servlet - write out the (xml, userdefined type, etc...)
ClientReceiver - read in/write out streams and create appropriate objects (xml, userdefined type array, etc...)
UI - take object and bind to user controls

I am almost there, thank you for all of your help I wouldn't know what to do without this forum.

Brian


Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
You're almost there. Everyone preaches their own way of doing this, and I have my own. Ever heard of Repositories? It's a concept that Martin Fowler and Eric Evans once talked about. [Can't remember where that article is].

Any way, Repositories are objects that sit in the Domain layer and exposes a collection like API. Let's say your domain is modeled around a Pet Shop, you'll most likely have entities like Cats, Dogs, Parots, Snakes, etc [maybe inherits Animal?]..Repositories provide a collection like API to make finding, storing, updating and deleting any animal simple.

Usually there is one repository for each composite root object, in our case we are dealing with simple animal objects that form no deep composition hierarchies, so we can have just one Repository class, "PetsRepository".

PetsRepository, will expose a collection like, or finder api such as:

PetsRepository.FindAllAnimals();
PetsRepository.FindAnimalByID();
PetsRepository.FindAnimalsLikeBirds();

Pay close attention to the interface of this class, it reveals an intention. It's telling you that whatever is returned from a repository must be a Domain object and NOT, Data,Datasets,Xml,streams etc...Repositories are Domain layer helpers that encapsulates how animals are Created, Retrieved, Updated and Deleted.

PetsRepository.UpdateAnimal(anAnimal);
PetsRepository.SaveNew(anAnimal);
PetsRepository.DeleteAnimal(anAnimal);

[assuming all pets inherit from a base Animal class, your Repository can return is base type]

We are still on the domain layer, so sticck with me. You may be asking, how does a repository really work? It's job is to find Data from a persistence medium, take the data and hand it to a factory for building of real domain objects. Factory hands back a domain object fully constructed, and Repository then takes this object preforms an post minipulation and then hands it up the chain to the caller.

1]Repository.FindAnimalByID(10001); {
2] SomeDataAccess.ExecuteSQL("select *...");
3] SomeFactory.BuildNew(aDataRow);
4] return anAnimal;
5]}

Thats pseudo code. Line 2 delegates finding of data to a data access layer in the low Infastructure.

At line 3, a single datarow is handed to a factory for producing a domain object.

line 4, returns the domain object to caller.


Now you may be saying, who is the caller? Well the caller can be any object in the upper Application layer or anyother object within the Domain layer even.


Let's show an exampe of a use-case in the application layer. This use case can be as simaple as,
"Show all pets similar to Fishes".

return aRepository.FindAnimalsLikeFishes()

or even

return aRepository.FindAnimalsLikeType(aType)


Notice the application is returning domain objects to the layer above it, the UI.

The UI can then take the objec(s) returned and populate text fields, datagrids or whatever.

In conclusion,
Repositories facilitate CRUD work on domain objects. It sits in the domain layer. It's job is to find data by delegating finding to a data access object. It then hands data to a factory for building real domain objects. Any objects within the domain or upper Application layer can call a Repository. The Application layer usually models use cases which lends nicely to repositories in most cases, not all. UI, needs data (beans in java) to bind to its presentation. This is provided to the UI from app layer.

As you can see, there is delegation from one layer to the next to accomplish sometimes the smallest of tasks. But step back and look at it, it accomodates changes without breaking any upper tier.

For example, the DataAccess tier can be replaced with an XML file db, and the UI or Application layer will never even know. If i wanted, I can throw away my UI be a more rich Swing UI and still nothing affected.

I can throw away my UI and Application and be left with a barebones domain layer that still functions...see the expressive power?>

I know i have rambled on alot here, if I did miss something that left you wondering, please, do ask or comment.


Jay








 
Thanks Jay,
I see more clearer but still some confusion. So I understand the Domain. Is the Domain usually on a server? You wouldn't deploy a Domain layer to a client correct? I believe that is true so I will go upon that assumption.

Ok, so the server side is clear to me but now how to get this object to the client?

Who is responsible for actually implementing writing on a stream? Not the Respository right? I am lost on where to implement my outputStream.write() method and then on the client the inputStream.read() methods. I think I understand the rest pretty good.

Brian

Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
And also how to send back the anAnimal array? As anAnimal[], in a vector, collection, object[]? Is one better than another or is this just personal preference as per the project?

Brian

Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
Zoo, I have to admit, I am weak on Java. Just started learning it. I do not know what you mean by outputStream.write() and outputStream.read()

I mostly have a c#/vb.NET background.

And yes, domain is never deployed to the client, I see the clients as being thin.

"And also how to send back the anAnimal array?" I guess it's how your repositories are designed to take apart the objects for storing.


ok, back to the output stream thing. Now correct me if i am wrong but, JSP is based around struts. A request comes in from the UI, trapped by an HttpServlet and servlet figures out the correct actions to take (selection of views, etc).


Why cant your servlet act as the app layer? Allow your servlet to talk to the Repository, get an object result from the repository store it into the request and forward the request to a jsp page.

the jsp can then pick out what it needs from the object (model).

 
Ahh yes, I see as per JSP. Unfortunately I don't use jsp at all. I am using an application front end and I actually have to open a stream (which is how I interact with a servlet)

I am now thinking just a small layer to break apart the objects and distribute them to the interface. Hmm. You know what I love about OO. It really makes everything simpler. But now it seems so hard.

Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
One more thing. Does the Respository have an instance of the DbAccess class AND the ObjectFactoryClass? For some reason my brain gets all funny at this. I think "single responsibility" and "NOT modular or procedural" would mean no class has an instance of another (kindof) but that is impossible.

Correct me if this is wrong. Most classes have only one or two instances of another class because the responsiblility gets passed allong instead of one class having 5-endnumber of instances?

This would make it very procedural right?

I should think like the main() function, it is only a starting point, usually one instance is created and then you go drilling to the next class to get what it does and that next class has an instance of another class and so on, right?

But is it ok for the the respository to have an instance of the dbAccessor and the objectfactory, get and instance of a resultset (which I keep thinking should be a db class's responsibility, not a repository's), pass it into the object factory and then return the animal object?

Brian

Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
Hey, sorry for the late response. It is perfectly fine for the Repository to have an instance of a DataAccess object. It's is also fine for the reposiroty to have an instnace of a factory.

You said this:
"..get and instance of a resultset (which I keep thinking should be a db class's responsibility, not a repository's..."


You are right, the repository isnt finding the data itself, no no..It's asking/delegating that finding of data to the DataAccess obj,[whatever that is]...Notice you say DB class and I say DataAccess..There is a reason for that, do not limit your self to the DB at all.

Take this example. You're building a stock quote app. Your UI needs to get stock quotes, so it asks the application layer to:
FindQuoteBySymbol(aSymbolString) --> which is then delegated to the Repository's exact method signature.

With that example, does the client know where the quote is coming from? Nope. The Repository may use different kinds of DataAccessors at runtime. One data accessor might just be a webservice, another might be a Text file accessor, or how about RSS/XML or some other? Repositories are not limited to the db, they can use a variety of DataAccessors [strategy or dependency injection]

Moving on with factories. good ol' factories. Yes, fine to let the repository delegate building of an object to the factory. You see, when data is found, the repository hands it to a factory (row at time). An AnimalFactory knows how to take the data and inject it into and create a new instance of that domain object. It's handed back to the repository which can keep a running list of objects created which is then returned to the calling client. Simple, effective.

Eric Evans say that Repositories presents the illusion of a factory itself. It sure looks that way. In very simple cases, a Repository may not even use a facotory, it can simple instantiate new instances of objects and build it itself. Simple, effective.


I employ use of repositories on almost all my projects, they work so well. And remember, since repositories are "finding" and returning objects, they provide a centralized point for query optimization, Identity Maps and other optimizers without a client being affected at all.

If you think Repositories end there, wait till you get a hold of Repositories in conjunction with Query Objects and Specification [Evans] to make finding objects even more generic, good for framework development.

Right now I use methods Like FindByID,FindAnimalsBySpecies,AnimalCount, etc. These methods are recurring queries that i simply encapsulate into an intention revealing interface to make reuse within my app more effecient.
 
YOur the best. I am getting it more and more. I am now looking at my PetStore example of EJB's. It is huge but I just have to bite the bullet and wade through it. I know I am not using EJB's (I wish I could) but I understand how that works. JBuilder builds a facade pattern type of framework based off of J2EE that will help also. DTO's (Data Transfer Objects) and DTOAssemblers. Similar to the repository it seems to me.

Also, the DataAccessor (I see your point perfectly about these) is returning a List in the JBuilder framework, so do you send back something of that sort from your DataAccessor? This is I think one of my last confusions! (YEAH RIGHT!! HA HA HA) I keep just using the db exampe and if i get 1000 rows returned, what do I put each row into? Then what do I put each of those into to send back to the repository?

Brian


Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
OK, sounds like you are asking a question more like: "what object type should be returned from a data accessor."


Data Accessors live in the Infastructure layer, they are closely tied to technology, data. They have no concept of domain entities. You'll have to let your accessors return a common type to the repository. That way, switching between accessors will continue to return a common type and repository will not have to change.

A simple value object/bean is sometimes good choice.

Then repositories always return domain concepts from the data. Repositories never return technology related concepts, only business related objects.

If your repositories are ever finding and returning things like datasets or XmlNodes, it's a good sign that something is definitely wrong. Now guess what, your app layer is then forced to parse that data itself and make objects out of it.

Remember, applications should deal with Domain concepts and not technology concepts like streams,datasets, although there are cases when this is acceptable.

let me know if u have more q's.
 
Thank you very much, I am soooooo much further just in the past two days. I'm sure I will have more questions but I need to gain some experience with what I just realized to articulate specific questions rather than just stating "What do I do" in a very general sense. Thanks

Brian


Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top