Design Problem: Object reference another object at different states

Hi,
This is a problem I came across today while developing a simple prototype. Imagine I have a class Boy which has a one-to-many relation with a class Dog.
The class Boy has the following methods: getName(), setName(), getAge(), setAge(), getDogs().
The class Dog has the following methods: getName(), getOwner()
When the application starts I load a Boy from the database as follows:
Boy peter = BoyFactory.loadBoyByName("Peter");
peter.setAge(10);
I then add peter to a static list which can be accessed from everywhere within my application.
At a different stage in the application I want to load a dog (just a dog). So I use the following code:
Dog dog = DogFactory.loadDogByOwnerName("Peter");
The dog object (using JDO or Hibernate) would also have a reference to the Boy object. However when calling the getOwner() method, the boy returned will not be the same boy stored in that static list (I expect the age, which was not persisted in the database, to be different).
Is there a way how when loading the Dog object, since its Owner of type Boy is already loaded in my object model, a Framework such as Hibernate or JDO will use this object rather then re-build a new one.
I am planning to use either Hibernate or some JDO framework and that is why I am asking this question.
If I where going to use some custom made way to load Dog then I would just search if the Owner was in that static list and if yes then set the owner of the dog equal to the object found in the static list.
However I was wondering if there is some design I should consider (study) to handle such a problem.
Thanks and Regards,
Sim085

Thanks uj :) I had another thought...
I will give another scenario so things are more clear.
Imagine having a class Teacher which has one-to-many relation with a class Student.
If you where programming the classes for these two entities then would you program the student class as follows:class Student{
Teacher t = null;
void setTeacher(Teacher t){...}
Teacher getTeacher(){...}
}ORclass Student{
int teacherId = -1;
void setTeacherId(int tId){...}
int getTeacherId(){...}
}The difference between these two methods is that in the first method, if I wanted to know the teacher of a student then I would only have to call the getTeacher() method while using the second design I would first need to get the teacher Id and then make a database call to actually get the Teacher object (or else get it from a static list where the teacher could be saved.
Personally I prefer the first method since I like to have an object model where objects are directly linked with other rather then linked through some form of id. However I do not know which design is best to use...
Thanks
Sim085

Similar Messages

  • Database design for objects with multiple states

    Context
    I'm designing a database which, simplified, should be able to handle users sending job requests to each other, and after that a job can be started, finished, and reviewed. The design should be scalable (think millions of users).
    Approaches I've considered:
    Gargantuan table
    One approach, probably not the best one, would be to simply store ALL jobs in one, huge table
    jobs. This table would need a state column to represent which state the job is currently in (e.g.
    ACCEPTED, STARTED, FINISHED, REVIEWED e.t.c.). The biggest problem with this approach that I can see is that jobs in different states have different types of data that are relevant to them. For example, a
    job request has a preliminary agreed upon price, but that could change before the job is started, and change again before the job is finished. This could of course be solved by just adding more columns to the table and naming them properly, but it will probably
    become a huge bottleneck performance-wise very early to have one table containing all the different types of possible data for all the different possible states of a job.
    Different tables for different states
    This approach would be to have multiple tables, for example job_requests,
    jobs_started, jobs_finished, tables who in turn can have substates, e.g.
    job_requests could have the sub-states PENDING, ACCEPTED, while the
    jobs_finished table would have the substates COMPLETED,
    CANCELLED, REVIEWED.
    With this approach each table only contains data which is relevant to the current job state, but on the other hand some data might be duplicated (for example the user ids of the job requester, and job receiver -- on the other hand this information could
    be stored in yet another table?). The problem with this approach is that I can't think of a good solution on how to archive all the information when transitioning between states. For example, once a job request has been accepted, and then started, it should
    be deleted from the job_requests table and moved into the jobs_started table, but it's just a matter of time before a stakeholder wants to know for example how long the average time is between a job request being created, until it's
    been started, at which point I'd need the data from the job_requests table to be able to calculate it.
    It feels like this type of problem should be easy to solve, but I really can't think of any good solution which "feels right", any solution I come up with feels ugly and I can immediately think of a number of things which makes the solution bad.
    Very grateful for any feedback or tips on approaches I could take. Thanks in advance!

    This will be moved to the design fourm, which I don't monitor, by a moderator within a day or so.
    A table in a relational database is supposed to model a unique entity. Job is such an entity. But "Jobs in Washingon state" and "Jobs in Oregon" are two such unique entities.
    I don't see why jobs in different states would have different attributes, but it is not my business domain. And the problem certainly appears in other areas. My area is financial instruments, and they come in many flavours. And still have many attributes
    in common.
    So what we do is that we have a table instruments which holds common data. And then there are tables like funds, futures, bonds, optionandwarrants etc that holds attributes that unique to these classes of instruments. These specific tables are child tables
    to the instruments tables.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Problem when Activating Design-Configuration objects

    Hi Everyone,
    We are facing a strange error in our XI system. When we are trying to activate any design/configuration object, we get an error, which states:
    <b>ERROR com.sap.aii.utilxi.swing.toolkit.ExceptionDialog: Throwable
    Thrown:
    MESSAGE ID: com.sap.aii.utilxi.misc.api.ResourceException
    com.sap.aii.utilxi.swing.framework.PersistenceException: ResourceException in method ConnectionFactoryImpl.getConnection(): com.sap.engine.services.dbpool.exceptions.BaseResourceException: SQLException thrown by the physical connection: com.sap.sql.log.OpenSQLException: Error while accessing secure store: File "
    <hostname>\sapmnt\<SYSID>\SYS\global\security\data\SecStore.properties" does not exist although it should</b>
    We double checked that the properties file does exist in the directory specified. We also went for a instance restart, but since then the SMC is showing a yellow flag with info 'J2EE Status Info Unavailable', and the java Stack is not working. Does anybody have any idea why this error is occuring?
    Regards,
    Amitabha

    Hi Krishna,
    As far as I know, this file is used for containing encrypted password and connection info for J2EE stack. So, I daresay, it will be very risky to remove the file from the source directory. Still, I would like to try your hint.
    Regards,
    Amitabha

  • Moving objects into different tablespaces

    Hi Gurus,
    Here is my query .
    I have 40gb space to have dataset from production database.
    Test enviornment will be refreshed with production database.
    From testing enviornment development will be refreshed to aviod any connections to production.
    As part of data copying to dev env is depending on the conditions given by business.
    So my question comes here
    Initially I will be dumpring all the data to one tablespace in one tablespace of development environment.
    It could take 39 to 40GB.
    Now i want to move objects into different tablespaces accoring to storage clause and no of records .
    New tablespaces will be created in development enviornment and will be created in same 40GB.
    Space is constraint in dev env and cann't be extended.
    How can i create tablespaces into the dev env and move objects into them?
    I hope you understood my queries ...
    In simple
    TESTING ENV - - - -- - - - > DEV ENV(Initially one tablespace for all tables/objects) - - -- -- ---- >DEV ENV(Objects in diiferent tablespaces )

    You say:
    While creating scripts of tables we are removing all tablespace names as we will be having 3 tablespaces at target that is also after loading the data into them.Don't remove the TS clause, but replace the TS so-and-so with TS that-and-that.
    Or replace tablespaces a, b and c with x+, and d* and e with y*+.
    This can be automated, but you will have to write some logic for that.
    Because ... we will be having only 3 tablespaces in DEV. ex NEWYORK tablespace is in production but it won't be created in DEv , istead all the objects into that tablespace will be moved to large table space.
    As I said: You will need a code which greps for TS NEWYORK* and replaces it with +<your_big_TS>+.
    So once again: Where is the problem?
    It's just a question of coding.

  • Sort an object by different fields

    Hello!
    Sorry for the (maybe) bad englisch but I'm a German.
    If I have an object fith different fields for example field1, field2, field3.
    To write a method which sorts an array of this objects by a given field?
    I mean something like this
    sort(String field, object[] o) {
    //sort by field
    instead of this
    sortbyfield1(object o){
    //sort by "field1"
    sortbyfield2(object[] o){
    //sort by "field2"
    hope you understood
    thanks
    Stefan

    When faced with this problem I usually use a Comparator helper class. Depending on whether the Comparator can be re-used I'll create a separate class or if not an inner or anonymous inner class. For example:
    import java.util.Comparator;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Collections;
    public class Main {
      // Compares Fields.f1 ascending
      public Comparator c1 = new Comparator() {
        public int compare(Object o1,
                           Object o2) {
          return ((Main.Fields)o1).f1.compareTo(((Main.Fields)o2).f1);
      public void sortem() {
        // Create our array of objects
        Object[] array = new Object[] {
          new Fields(new Integer(1),3,"3"),
          new Fields(new Integer(2),2,"1"),
          new Fields(new Integer(3),1,"2")
        // Sort on Field.f1 using reusable comparator
        Arrays.sort(array,c1);
        System.out.println(Arrays.asList(array));
        // Sort on Field.f2 using inner class
        Arrays.sort(array,new C2());
        System.out.println(Arrays.asList(array));
        // Sort on f3 using an anonymous inner class
        Arrays.sort(array, new Comparator(){
          public int compare(Object o1,
                           Object o2) {
            return((Main.Fields)o1).f3.compareTo(((Main.Fields)o2).f3);
        System.out.println(Arrays.asList(array));
      public static void main(String[] args) {
        Main m = new Main();
        m.sortem();
      // Class with many fields of different types
      class Fields {
        public Integer f1;
        public int     f2;
        public String  f3;
        public Fields(Integer f1, int f2, String f3) {
          this.f1 = f1;
          this.f2 = f2;
          this.f3 = f3;
        public String toString() {
          return ""+f1+" "+f2+" "+f3;
      // Inner class comparator on Field.f2
      class C2 implements Comparator {
        public int compare(Object o1,
                           Object o2) {
          int result = 0;
          int i1 = ((Main.Fields)o1).f2;
          int i2 = ((Main.Fields)o2).f2;
          if (i1==i1) result = 0;
          if(i1<i2) result = -1;
          else if (i1>i2) result = 1;
          return result;

  • When it's required to share a single object in different classes????

    Hi friends...
    I am new to java programming language....
    when it is required to share a single object in different classes???
    and
    please give me one example with explanation...
    Thank you
    regards Shree

    sun_shree wrote:
    Thanks for all giving reply.....
    please write the constructor which is accepting reference and please,,,,,, explain......
    Thanking youNo.
    This will be covered in any Java textbook or tutorial. Like this one: [http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html]
    After reading it and writing some code of your own to test your understanding, if you still have a specific question, post again.

  • Is it posible to create objects with different names dinamically?

    Hi,
    I'm creating an app that manages different wireless nodes in a network and I was thinking that I could create a class called Node which would have a constructor that every time I created an object Node, I would pass the address and some other data about the Node and the constructor will save all that data and also create a unique ID for every Node object.
    Now the problem is that I need to be able to discover all the nodes in my network every time the user clicks a Ping button. So every time the users clicks Ping I need to do a ping and create as many Node objects as nodes I have in my network. The thing is I don't know how to make it create the node objects with different names so after I've created all the nodes objects I can refer to one of them.
    Something like this.
    int Id=0;
    id++;
    Node node+Id = new Node();
    I think its not possible to do something like that. If it isn't how can I do to refer to one of the objects I've created?
    Thanks.

    Twistx77 wrote:
    Thanks to both of you. I'll check out the Link and if I can't find the solution there I'll make the array , I don't know how I didn't think about doing that. There are two collections you should study specifically:
    First you have the ArrayList which in essense is a growable array. This means you don't have to decide in advance how big it can be.
    Second there's the HashMap. It's sometimes called an associate array. Such an array doesn't have fixed position indexes like an ordinary array. Instead each index (called key) is associated with a value but the keys don't have any particular order. Still, given a certain key, finding the corresponding value in a HashMap is almost as fast as an array access.

  • Creating View Object with different criteria

    Hi,
    I have a requirement to execute the following queries in the application logic. We have YEAR table with mileage rates with different effective dates. If the service date is greater than any of the existing effective dates we need to get the rate with that effective date. if the service date is less than the existing effective dates, then we have to get the rate with least effective date.
    SELECT mileage_rate, ... FROM year
    WHERE eff_date =  (SELECT MAX(eff_date) FROM   year WHERE  eff_date <= :bServiceDate)
    SELECT MILEAGE_RATE, .... FROM YEAR WHERE
    EFF_DATE =  (SELECT MIN(EFF_DATE) FROM YEAR)
    We have to execute the 1st query and if there is no matching records then we have to take the second query with min effective date. At present we are creating two view objects for the above scenario. Is there any possibility to create one view object with different criteria. What is the best solution to handle the above problem in ADF.
    Thanks and Regards,
    S R Prasad

    Well on the ViewObjectImpl you can fire the method getQueryHitCount() passing in the required ViewRowSetImpl. If you get the query hit count as 0, use can attached the other query and execute it.

  • How to get similar color for objects in different pictures

    how do you get similar color for objects in different pictures
    I have a prodject that i'm working on and i need to edit several images at once (preferabley) so that they are the same color. They are wooden cupboards and i need all the wood looking the same colour. In light room you can edit a group of images at the same time hence the colours are the same . Is this possible in Elements ? If so how do i do this ?
    I have tried duplicating layers and it just replaces the whole image, it seems to work using levels layers but not the other layers ... I have 30 more images to do and would ideally not like to adjust all the images manually ? I dont mind doing minor tweaks. Essentially all the images where taken with the same camera and lighting and lens's ...
    Screen shot is where I'm at at the moment...
    I have posted this question else where but was told to repost  - this is a link to my previous post as to where we got to
    http://forums.adobe.com/message/4720576#4720576

    You could try using the raw converter. Open one file and edit it (File>Open, pick the image and choose Camera Raw as the format before you click Open). Then open the next image and click the little four-lined square on the upper right side of the ACR window and choose Previous Conversion from the flyout menu.

  • *How to Delet one same object from different roles*

    I need to delete one auth object from different roles, Couls any one please advise me how can i do this and if there will be any complications involved with tis.
    Best regards:
    Maq

    In PFCG, it may be that you have added some objects manually. To remove them you will have to go to pfcg.
    Even if you first remove the objects from su24, you will have to go to all the roles through pfcg to generate them in expert mode by selecting the third option (edit old status and merge with new data)

  • Sharing objects between different tabs on a JTabbedPane

    Does anyone know how to share objects on different tabs of a JTabbedPane? I.e., I want the same buttons/corporate logo to appear on each tab in the same location, and thus the same functionality, locations, look, etc...
    Currently, if I invoke the add(Component) method for the same component but for different panes, only the pane that had the last add() method called contains the object.
    Thanks,
    adam

    An instance of a GUI component can only be in one place in the GUI (visible or not).
    You could make your own component class (extending JPanel and containing other components you want) and then create an instance of this for each tab.

  • SSDT Schema Compare keeps showing the same objects as different..

    Hi, 
    When comparing a database to my project using Visual Studio 2012 SSDT I get several stored procedures marked as changed. The body of the procedures is identical, but two properties are highlighted as different when expanding the object:
    IsSelf (false on the DB vs true on the project) and User  (dbo on the DB, needs to be added to the project).
    The procedures have the option "with execute as self" both in the database and in the project as part of the body.
    I have not found what needs to be done so these differences are applied to the project and never appear again. Tried changing some options on the schema compare but didn't found one that help. 
    Some forum suggested dropping the objects and re-creating them but I don't want to loose the history of changes on TFS.
    Any suggestions? 

    Hi Daniel,
    Since you have posted this issue to the SSDT forum here:
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/5c9c5c47-64ac-4af4-9104-c9500dc8cf52/ssdt-schema-compare-keeps-showing-the-same-objects-as-different?forum=ssdt#5c9c5c47-64ac-4af4-9104-c9500dc8cf52
    I will move this thread to the Off-topic forum, thanks for your understanding.
    Sincerely,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Issues in the import of Design & Configuration objects

    Hi SDNers,
    I have a small doubt. In one of our scenario we have exported the Design & Configuration objects (all objects) from DEV to ACC.
    But actually we want only selected objects to be imported into ACC.
    Will the import of objects under the same namespace append / overwrite the already imported objects ??
    Kindly advice us.
    Thanks in advance,
    Anguraj

    Hi Roger,
    Thanks for your reply..
    Actually with IR we are not facing any issues.. but with ID when we are importing the objects from Dev to Acc , some objects are getting overwritten and some are getting appended.
    Could you please let me know what is the actual behaviour in PI 7.0
    When  the object will overwrite and will append.
    Appreciate for exact reply.
    Regards,
    Anguraj

  • Is it possible to create 2 Date objects with different hashcode.

    Hi,
    I want to create 2 java.util.Date objects with different hashcodes. Is it possible??
    Regards,
    Farooq

    import java.util.Date;
    import java.util.Calendar;
    public class TwoDates {
        public static void main(String[] args) {
            Calendar oneCal = Calendar.getInstance();
            oneCal.set(Calendar.YEAR, 1903);
            Calendar anotherCal = Calendar.getInstance();
            Date oneDate = oneCal.getTime();
            Date anotherDate = anotherCal.getTime();
            System.out.println(oneDate.hashCode() + " " +
                               anotherDate.hashCode());
    -14330615 -825112150

  • Compare DB objects between different schemas

    Hi,
    I want to compare db objects beween 2 different schemas like QA and PROD.
    Please suggest me a tool that compares table definitions,stored procedures and other db objects between different schemas.

    Did you check the above video link which is shared?
    Yes I'd agree with you and also i faced these situations to check what objects i need to export from Dev to Quality ( to analyze what are already correct or what have to be imported again)
    Generally Quality & Prod are in sync.
    Also will be waiting along with you if anyone comments on any such tool.
    Regards,
    Krishna Tangudu

Maybe you are looking for