I have made an aggregate class named Question. This contains references to Answer, Category, Feedback objects. Should the QuestionRepository be the class that contains all methods quering the database that relates to the Question but also all the methods for quering the Feedback, Answer etc? Or should these be seperate classes such as QuestionRepository, FeedbackRepository and so on.
From the way you have explained , I am assuming that each Question will have 1 or more Answers , 1 or more Feedback and the Question belongs to a particular Category
Since the Answer and Feedback are dependent on Question and cannot exist independently , you can have a single QuestionRepository for these 3 entities .
Coming to Category , category is more of a static entity which IMO is a static list , so all such static entities can be grouped together in a StaticRepository
From the DDD web site :
For each type of object that needs global access, create an object
that can provide the illusion of an in-memory collection of all
objects of that type.
A repository is used when you need direct access to an entity, i.e. when there's no other convenient way to get hold of that entity than fetching it from a persistent store directly. In contrast, if you consider that the entity is most of the time easily obtainable through traversal of another object you've already got at hand, then there's no need for a repository. It seems to be the case with Answer, Category, and Feedback here.
Usually repositories are only for aggregate roots, though there may be exceptions.
I suggest you read the DDD blue book or some tutorial to get a basic comprehension of the DDD building blocks before you start building your domain model.
Related
It is not easy to explain my issue.
JPA creates some complex objects for calculations, which are stored in a database.
We decided to set the results in a working copy of this objects.
This means for each object model we created a seperated working copy model file with the same fields but some other LocalDates values and new result fields.
When the calculation was starting the working copies are instantiated.
This approach is not the best i think.
I think of the prototype pattern to clone the object.
There i come to the problem how to add the new fields. How?
Instantion costs and ist creates lots of additionals model class files.
I only think of put the result field in the calculation data models as transient fields.
Maybe inner class or local class?
I also tried to use an interface as data bucket.
But thats not the realy purpose of interfaces and also it works only with many curious trick.
For Unit Tests and user input i think it is the best to use the builder pattern and then tell JPA to store the parent object, or not?
Sorry but my answer was to long for a comment :(
There is big complex object relationship with Lists and Sets One To Many etc. relationship. When i set the result i a new class i cant determine the right object e.g. in a list. So we bild the same structurefor these result and seperated these classes in a package. Maybe it is possible to dont build the structure a second time with also references to the "basic classes". It should be sufficient to reference to each basic class a result class. It would only a little bit more navigation to get values from deeper classes. For a similiar use case there must be a best practise, or? Interfaces or sth. I very dislike the many classes for the result. Is it not possible to clone and add classmember to it for the result or to logical group easier or something like this?
It could be a solution for somebody:
http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2FIWorkingCopy.html
Here you will work with the Eclipse API and create IWorkingCopies.
For the described task toooo much.
I am designing a class for an employee management system.
Class Employee has following fields:
:Employee
id:int
firstName:String
lastName:String
contract:Contract
Class Contract has following fields:
:Contract
-contractNo:int
-contractDate:Date
-contractType:Type
-rate:Double
-function:Function
-contractCopy:File
When an individual becomes employed within the company, he/she signs a contract with an agreed rate, function etc. From time to time, management revises the contract and changes rate and/or function.
Could somebody advise how to design a class that stores revisions of the contract? The user needs to view the original information and all revisions.
You already have two nice entities to create classes for: Contract and Employee, both of which also make nice tables to store data.
I would create a ContactRevision class, that has fields of the Contract that can be revised.
For example:
:ContactRevision
-contractType
-rate
-modifiedOn
-modifiedBy
You could then add a property to your Contract entity called revisions of type List<ContractRevisions>, with operations like addRevision or getAllRevisions to show the changed values if desired.
You can use Event Sourcing Pattern. It will allow you to track the change history.
In short you create an event for each change and thanks to this you may review it whenever you want.
You can find more information here:
http://martinfowler.com/eaaDev/EventSourcing.html
https://msdn.microsoft.com/en-us/library/dn589792.aspx
I am currently working on a product that works with Hibernate (HQL) and another one that works with JPQL. As much as I like the concept of the mapping from a relational structure (database) to an object (Java class), I am not convinced of the performance.
EXAMPLE:
Java:
public class Person{
private String name;
private int age;
private char sex;
private List<Person> children;
//...
}
I want to get attribute age of a certain Person. A person with 10 children (he has been very busy). With Hibernate or JPQL you would retrieve the person as an object.
HQL:
SELECT p
FROM my.package.Person as p
WHERE p.name = 'Hazaart'
Not only will I be retrieving the other attributes of the person that I don't need, it will also retrieve all the children of that person and their attributes. And they might have children as well and so on... This would mean more tables would be accessed on database level than needed.
Conclusion:
I understand the advantages of Object Relational Mapping. However it would seem that in a lot of cases you will not need every attribute of a certain object. Especially in a complex system. It would seem like the advantages do not nearly justify the performance loss. I've always learned performance should be the main concern.
Can anyone please share their opinion? Maybe I am looking at it the wrong way, maybe I am using it the wrong way...
I'm not familiar with JPQL, but if you set up Hiernate correctly, it will not automatically fetch the children. Instead it will return a proxy list, which will fetch the missing data transparently if it is accessed.
This will also work with simple references to other persistent objects. Hibernate will create a proxy object, containing only the ID, and load the actual data only if it is accessed. ("lazy loading")
This of couse has some limitations (like persistent class hierarchies), but overall works pretty good.
BTW, you should use List<Person> to reference the children. I'm not sure that Hibernate can use a proxy List if you specify a specific implementation.
Update:
In the example above, Hibernate will load the attributes name, age and sex, and will create a List<Person> proxy object that initially contains no data.
Once the application accesses calls any method of the List that requires knowledge of the data, like childen.size() or iterates over the list, the proxy will call Hibernate to read the children objects and populate the List. The cildren objects, being instances of Person, will also contain a proxy List<Person> of their children.
There are some optimizations hibernate might perform in the background, like loading the children for other Person objects at the same time that might be in this session, since it is querying the database anyways. But whether this is done, and to what extend, is configurable per attribute.
You can also tell hibernate to never use lazy-loading for certain references or classes, if you are sure you'll need them later, or if you continue to use the persistent oject once the session is closed.
Be aware that lazy loading will of course fail if the session is no longer active. If for example you load a Person oject, don't access the children List, and close the session, a call to children.size() for example will fail.
IIRC the hibernate session class has method to populate all not-yet-loaded references in a persistent oject, if needed.
Best read the hibernate documentation on how to configure all this.
To end 2014 year I got a simple question I think.
I would like to use "DDD" a bit more, and I'm currently trying to experiment various usecases to learn more about DDD.
My current usecase is the following :
we have a new database schema that is using a classic pattern in our company : modeling our nomenclature table as "id / code / label". I think it's a pretty classic case when using hibernate for example.
But in the OO world things get "complciated" for something this simple when using a API like JDBC or QueryDSL. I need to fetch an object by its code, retrieve its id or load the full object and then set it as a one to one relation in another object.
I wondering :
this kind of nomenclature can be an enum (or a class with String cosnatnts depending on the developer). in DDD terms, it is my ValueObject
the id /code / label in the database is not i18n friendly (it's not a prerequisite) so I don't see its advantages. Except when the table can be updated dynamically and the usecase is "pick something in a combobox loaded from this table and build a relation with another object : but that's all because if you have business rules that must be applied you need to know the new code etc etc).
My questions are :
do you often use the id / ocde / label pattern in your database model.
how do your model your nomenclature data ? (country is perhaps not the best example :) but no matter what how do you model it ? without thinking much I would say database table for country; but for some status : "valid, waiting validation, rejected" ?
do you model your valueObjects using this pattern ?
or do you use lots of enum and only store their toString (or ordinal) in the database ?
In the Java OO objects world, I'm currently thinking that it is easier to manipulate enum that objects loaded from the database. I need to build repositories to load them for example. And it will be so simple to use them as enums. I'm searching some recomfort here or perhaps am I missing something so obvious ?
thanks
see you in 2015 !
Update 1 :
We can create a "Budget" and the first one is mark as Initial and the next ones are marked as "Corrective" (with a increment). For example, we can have a list of Budgets :"Initial Budget", "Corrective budget #1", "Corrective budget #2".
For this we have this database design : a Budget Table, a Version Budge with a foreign key between the two. the Version budget only contains an ID, a CODE and a LABEL.
Personnaly, I would like to remove this table. I don't see the advantages of this structure. And from the OO perspective, when I'm creating a budget I can query the databse to see if I need to create an Inital or Corrective budget (using a count query) then I can set the right enum to my new budget. But with the current design I need to query the database using the CODE that I want, select the ID and set the ID. So yes, it's really database oriented. Where is the DDD part ? a ValueObject is something that describe, quantify something. In my case seems good to me. A Version describe the current status of my Budget. I can comapre two versions just but checking their code, they don't have lifecycle (I don't want this one in particular).
How to you handle this type of usecases ?
It's only a simple example because I found that if you ask a database admin he would surely said that all seems good : using primary key, modeling relations, enforing constraints, using foreign key and avoid data duplication.
Thanks again Mike and Doctor for their comments.
I will hook in in your country example. In most cases, country will be a value object. There is nothing that will reference a country entity and that should know that if the values of the country changes it is still the same country. In fact, the country could be represented as an enum, and some nasty resource lookup functions that translate the Iso3 into a usefull display text. What we do is, we define it as a value object class with iso3, displayname and some other static information. Now out of this value object we define a kind of "power enum" (I still miss a standard term here). The class implementing the country value object gets a private constructor and static properties for each of its values (for each country) and explicit cast operators from and to int. Now you can treat it just like a normal enum of your programing language. The advantage to a normal enum beside having more property fields is, that it also can have methods (of course query methods, that don't change the state of the object). You can even use polymorphism (some countries with different behaviour than others). You could also load the content of the enums from a database table (without the statics then and a static lookupByIso3 method instead).
This you could make with some other "enum like" value objects, too. Imagine Currencies (it could have conversion methods that are implemented polymorphic). The handling of the daily exchange rates is a different topic though.
If the set of values is not fixed (for example another value object candidate like postal adress) then it is not a value object enum, but a standard value object that could be instantiated with the values you want.
To decide if you can live with something as a value object, you can use the following question: Do you want copy semantic, or reference semantic? If you ever change a property of the object, should all places where you used it update, too, or should they stay as they are? If the latter, than the "changed" object is a new and different value object. Another question would be, if you need to track changes to an object realizing that it remains the "same" despite of changing values. And if you have a value object, where you only want specific instances to exist, it is a kind of enum described above.
Does that somehow help you?
I am working on a API to access data stored in a system. The system contains things like people, appointments and procedures associated with those appointments. My application will strictly be read-only.
I am using Spring w/ RowMapper to build objects such a "Person", "Appointment" and "Procedure". I have a DAO for each element. (ie: PersonDAO.getById(), PersonDAO.getByName(), ..).
The issue comes in that Appointment has a reference to a Person object. An it would be nice in the Person object to have a reference to that Person's appointments, but if I begin to load these it becomes a circular reference.
So, I guess my question is the right way to handle this just put the references (Ids) in the POJOs and then have the business layer(?) just make the right calls to get the information? Or is it ok to somehow pass around a reference to the DAO in the actual POJO so that I can lazily load the object objects when referenced? But then how do you handle the circular reference? When I have a Person and I lazily load all their appointments, those appointments will also have a Person associated with them. When I load this Person it could potentially have difference information from the Person I am loading Appointments for.
Person (object x) lazily load -> Appointments could lazily load Person (object x').
Since Person could have changed by the time I went to lazily load their appointments. I really need the Person object in Appointment to refer back to the same Person object.
I'm getting all caught up on this. I know I could just "make it work", but I want to try and find a good solution. I was thinking about using hibernate for this, but thought it was really just overkill. Maybe it isn't.
You're describing a bidirectional association, which Hibernate has specific (and generally very good) support for.
Read up on how to do it in the docs.
Rolling this by hand is going to be quite fiddly and bug-prone. I wouldn't recommend it. Use the the power of ORM tools like Hibernate, that's what they're there for.
Extending the suggestion of using Hibernate, I would recommend checking out the JPA annotation support that Hibernate supports ( I believe it's part of the J2EE spec). You can annotate your classes with a #ManyToMany annotation. Check out these docs:
https://www.hibernate.org/397.html