Java CRUD DAO Persistence design - java

Recently I have really focused on writing clean code and implementing designs and I have stumbled accross a situation where I have several options but cannot decide which one is the appropriate one. I am working on a software that requires persistence on a collection of objects. I decided to implement a DAO Pattern. The thing is that persistency could both be Json OR Xml so I implemented it this way:
I created a Generic DAO:
public interface GenericDao<T> {
public boolean add(T type);
public boolean change(T type);
public void delete(T type);
}
Then I created a CarDAO:
public interface CarDao extends GenericDao<Car> {
public Car getByIdentificationNumber(int id);
public void process();
}
For JSON persistence:
JsonGenericDao:
public class JsonGenericDao<T> implements GenericDao<T> {
public boolean add(T type) {
// implement ADD for json
}
public boolean change(T type) {
// implement Change for json
}
public void delete(T type) {
// implement Delete for json
}
}
JsonCarDao:
public class JsonCarDao extends JsonGenericDao<Task> implements CarDao {
public Car getByIdentificationNumber(int id) {
// Implement logic
}
public void process() {
// Logic
}
}
JsonCarDao extends JsonGenericDao to include the Add, Change, Delete and it also provides additional methods.
The same way is implemented XmlGenericDao and XmlCarDao.
So I end up with the possibility of using XmlCarDao OR JsonCarDao depending on the persistence I want to use.
When implementing the persistence, I used JAXB for XML and Gson for JSON.
I made an EntityCollection<T> class to store the objects inside and I would convert this collection to either XML OR JSON depending on the persistence used and I would retrieve the information from the file to this collection, change what needs to be changed and then rewrite the file.
There are two ways I can implement it:
Option 1:
I could implement the persistence using Gson inside JsonGenericDao and do the same for JAXB inside XmlGenericDao.
Option 2:
I can create an interface Persister<T> and write two classes that implement this interface, therefore JsonPersister<T> and XmlPersister<T> with methods such as update(T type) and acquireAllFromFile(), one of which is going to rewrite the whole file with the new data, and the other one is going to retrieve the information from the file. (Same thing could be done in Option 1 but without making the additional classes)
Then inside JsonGenericDao<T> I can use: JsonPersister<EntityCollection<T>>
and inside XmlGenericDao<T> I can use: XmlPersister<EntityCollection<T>>
therefore packing everything.
The problem here though is thinking about this, it would mean that I can get rid of JsonGenericDao and XmlGenericDao and implement a single PersistenceGenericDao which is going to use a Persister interface inside its CONSTRUCTOR to specify if JsonPersister should be used or XmlPersister should be used. It would basically be a combination of DAO and Strategy Pattern. Now this seems like something I can do.. but it also appears to me that it messes up my initial DAO design. Is it an appropriate thing to do or is it bad practice?

I think your option 2 actually looks like the GoF Bridge Pattern. XmlPersister/JsonPersister are ConcreteImplementors. PersistenceGenericDao is Abstraction, JsonCarDao is RefinedAbstraction.
So the idea actually makes sense. See What problems can the Bridge design pattern solve? to check if you really need the pattern or not.
If you only plan to use XML or JSON persistence, I personally would go with option 2. If you compare JsonCarDao with XmlCarDao, the only difference between them will probably be the mechanics of saving/loading data from some resource (JSON vs. XML). The rest of the logic will probably be pretty much the same. From this point of view, it is reasonable to extract the "saving/loading" into specific implementors and have one generic class for the rest of the DAO logic.
However if you consider relational or NoSQL database persistence, this might not fit that well. Because the DAO logic will probably be different. A method like findById will be pretty different in a relational DAO (query in the DB) compared to a JSON DAO (load data from a JSON file and search the collection of objects for an object with the given ID). In this situation, RelationalPersistence will probably not be very efficient.

Related

Spring cache applying caching on a generic method by dynamically getting the cachname based on the return type

The method getById is located in an Abstract class named AbstractCachedResult.
public abstract class AbstractCachedResult<T extends BaseResource> {
#Cacheable(value = "dynamicName")
public T getById(String id){
//program logic
}
}
Many other service classes will be inheriting from this class. For ex :
public class UserService extends AbstractCachedResult<User> {
//program logic
}
Since I am setting the #Cacheable(value = "dynamicName") in the abstract class I wouldn't be able to know the type of the class that was returned by the method. I need to be able to get the name of the class dynamically so that for each method invocation from its inherited class the correct cache is used.
I have came across another post. Here they are passing the entity class name as a parameter which I cannot do. I need to get the type of the returned data dynamically so that I could us the #Caching annotation which is the #2 soluton. Is there a way to do this?
Arguably, the simplest and most obvious solution, especially for maintainers, would be to override the getById(:String) method in the subclass, like so:
public class UserService extends AbstractCachedResult<User> {
#Cacheable("UserCache")
public User getById(String id) {
super.id(id);
}
// additional logic
}
Alternatively, you might be able to implement a "custom" CacheResolver (see doc and Javadoc) that is able to inspect the class generic signature of the (target) subclass.
Finally, under-the-hood, Spring's Cache Abstraction is implemented with Spring AOP. For real, low-level control, it should be possible to write custom AOP Interceptor not unlike Spring's default CacheInterceptor (Javadoc). Your own AOP Advice could even be ordered relative to the Cacheable Advice, if needed.
Honestly, I think the first option I presented above is the best approach. Not every service class may need to cache the result of the getById(:String) operation. Caching really depends on the transactional nature of the data and how frequently the data changes.
Use your best judgement.

Interface conflicts java

I am currently working on a big project that includes three different types of CRUD. My ICrud interface includes the <t> to put in the desired datatype when I implement it.
My problem is that when I implement it in my third class, I wish to make one of the methods (readAll) use another datatype than the 4 other methods (CRUD). Is this possible in any way?
Right now I have the readAll method return the matching data type but returning null because it isn't used, and instead created another method readall2() that does return the correct datatype but isn't part of my interface.
The ICrud interface:
public interface ICrud<T> {
List<T> readAll();
List<T> read(int cvr);
void create(T t);
void delete(int cvr);
void update(T t, int id);
}
how i implement it:
#Service
public class AdminRepository implements Ilogin<Admin>, ICrud<Driver>,
IAdmin<Company>
how i wish to use the readAll:
public List<Company> readAll()
(not Driver, but driver for all other methods in the interface)
And I wanna add; at first, i had the readAll in iAdmin because it takes Company, but I have this readall method in 6 other classes that implements ICrud aswell.
Thanks for any help. :)
You have a design problem, i recommend you read about SOLID principles in the following link:
https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design
In a correct design, you should not at all implement an interface if you will not implement one of its methods (the readAll i your case). this means you are mixing concerns, and your interface must be split into smaller interfaces. perhaps splitting the readall into a separate interface will solve your problem. for example, instead of ICrud, create an interface for write operations alone, and one for read operations, and one for readAll.
there is many ways to solve your problem preserving the interface ICrud as is, such as using object as a retrun type, or generics or dynamics. but what solves your problem from its roots is following a good design as i mentioned above.

Where should the CRUD operations go in an Android app with many model objects?

In my app, I have many Java model objects (I believe you'd normally refer to them as POJOs?), and I have a central Database singleton class (DatabaseHelper) that extends SQLiteOpenHelper.
My problem: I am unsure where to actually put stuff. Right now I've been putting everything into the DatabaseHelper class and it's getting huge.
This leads me to rethink my approach and that maybe I need to be separating things out.
Should I be putting the database CRUD operations in a dedicated class that acts as a bridge between the model objects and the DatabaseHelper? Or should I be coupling the CRUD methods in the model objects themselves? What about where to store things like the table and column names?
What's considered accepted practice here?
If you have plenty of tables in your database, which I presume you do since you're asking the question, I'd suggest you put all of the CRUD logic into separate classes called Repositories (e.g. ModelRepository).
These classes should have all the things necessary and they'd best be implemented via the interface that has the C R U and D methods, so that if the implementation needs to undergo some changes, everything keeps on working because of the usage of interface. So for every model you need 2 classes, ModelRepositoryInterface which can even extend a common interface with these 4 operations and each can have some additional methods specific to the class itself; and the class that implements the interface, say ModelRepositoryImplementation.
Some basic example, let's assume your Model is called Course:
public class Course {
//your class logic, constructor, getters, setters, etc.
}
This would be it's repository interface:
public interface CourseRepositoryInterface {
void addCourse(Course course);
void deleteCourse(Course course);
void updateCourse(Course course);
List<Course> getAllCourses();
}
Something like that, of course it can have more/less methods varying from your needs.
Finally you need a class that implements that interface like:
public class CourseRepoWithMySqlDatabase implements CourseRepositoryInterface {
void addCourse(Course course) { //TODO: Implement it }
void deleteCourse(Course course) { //TODO: Implement it }
void updateCourse(Course course) { //TODO: Implement it }
List<Course> getAllCourses() { //TODO: Implement it }
}
In this class you would implement the methods to do what they need to do with, for example, MySql database. In case you ever needed to switch from MySql to, let's say, another type of database or a no database implementation, you'd just use another class to implement the interface, and pass that where the interface parameter is required.
Pay attention: this is very important. You always need to require the interface in the place where you plan to use its methods.

What's this java pattern called?

I'm wondering what the following pattern is called, if it has a name at all.
Purpose
Store data that is associated with an object (MyObject), but that is private to an implementation of an interface that deals with that object. Clients of the object have no business looking at this data.
Alternatives
Some alternatives are
a WeakHashMap<MyObject, FooApiMyObjectAttachment> maintained in the implementation of the interface,
using subclassing and factories everywhere the value is created, so that the extra data can be stored in the subclass or
using subclassing and accepting both MyObject and subclasses in the API.
Code example
public interface MyApi {
void doSomething(MyObject x);
}
public class MyObject {
public interface Attachment {} // empty interface, type bound only
private Attachment attachment;
public void setAttachment(Attachment attachment) {
this.attachment = attachment;
}
public <T extends Attachment> T getAttachment(Class<T> type) {
return type.cast(attachment);
}
}
class FooApiMyObjectAttachment implements MyObject.Attachment {
Foo foo; // some data that one MyApi implementer `foo' wants to persist between calls, but that is neither needed nor desired on MyObject
}
class BarApiMyObjectAttachment implements MyObject.Attachment {
Bar bar; // some data that another MyApi implementer `bar' wants to persist between calls, but that is neither needed nor desired on MyObject
}
class FooApi implements MyApi {
// associates FooApiMyObjectAttachment with any MyObjects passed to it or created by it
}
class BarApi implements MyApi {
// associates BarApiMyObjectAttachment with any MyObjects passed to it or created by it
}
Compared to subclassing, the advantage is that no factories are needed for MyObject, just so that implementers of MyApi can associate extra data with the objects.
Compared to a WeakHashMap in the implementers, a disadvantage is two methods on MyObject that aren't useful to clients, but an advantage is the simplicity.
A nice property of this pattern is that you can generalize it to store any number of attachments of different types with each node by changing the field to Map<Class<?>, Attachment> attachments, which cannot be done with subclassing at all.
I've seen the generalized form used successfully to annotate tree nodes in a tree rewriting system with various data used by various modules that processed the nodes. (c.f. pointers to parent nodes, origin information)
Question
Does this pattern have a name? If so, what is it? Any references?
It looks like a structural pattern, very close derivation from Whole-part, or composite.
Looking for a reference online, an overview of Whole-Part:
Sometimes called Composite
Helps with the aggregation of components (parts) that together form a semantic unit (whole).
Direct access to the Parts is not possible
Compose objects into tree structures to represent part-whole hierarchies.
Whole-Part lets clients treat individual objects and compositions of object uniformly
Composite Pattern
Really the difference between what you are doing and the composite is that you are storing non-composites, so you don't get the tree structure that composites would allow, but a UML would look similar just without the pigs ear.
Found it!
The form where multiple attachments are possible (Map<Class<?>, Attachment> attachments) is described by Erich Gamma as the Extension Objects Pattern.
The Gang of Four calls this a Memento.
The Role Object Pattern is really really similar, maybe even up to the point where I conclude that the answer to my own question is: It's the Role Object Pattern.

How to avoid potentially long if statements for the same thing multiple places

I am creating an application and at the front I check if the user is an admin, user, moderator or superadmin. Based on this I create a different XML.
So what I currently do is to pass a string in the method argument that converts the object to XML to specify which mapping it should use. However passing those strings around isn't good. Are there any patterns to do this better?
I could bring the role check to the mapping class, and then change the mapping id to the same as the role of the current user. But I don't think security checks fits those classes.
Would you just create an enum to keep the roles and pass that instead of a string?
Or create different classes and use a factory to return the right object?
A Common Interface Approach
By implementing a common interface between all return objects, you can develop some loose coupling in your code. For example:
public interface XmlReturn
{
public void displayXML(); // Just an example method.
}
And a class that implements this interface:
public class AdminXmlReturn implements XmlReturn
{
public void displayXML() { // Some code here for the admin XML }
}
With this, you can generate some sort of factory that takes a discriminator:
public abstract class XmlFactory
{
public static XmlReturn getInstance(String type)
{
// Using string as an example type. Doesn't need to be.
if(type.equals("Admin")) {
return new AdminXmlReturn();
}
}
}
and by referring to the object by it's interface type, you can generate as many different XML files you want, without having to change any code. IE:
public void loadPage(String permission)
{
// permission can be any type. This is just an example.
XmlReturn xml = XmlFactory.getInstance(permission);
xml.displayXML();
// This method exists in all objects that implement XmlReturn
}
Advantages
This approach has the main advantage that you can add as many new XML files and permissions as you want, and you won't need to change the code that loads the XML. This "separation of concerns" will help you to make your program very manageable and extendable.
By porting your decision logic to a factory, you help make your code more readable, and allows other people to abstract away from the details of the inner workings of your program, if you intend on sharing your code.
You question is not very clear. Anyway, I try to give some option:
if you want to serialize to XML different kind of users, then I would suggest to model the different kind of users as a hierarchy of classes, and have a specialized toXML() serialization method in each class. By the way, JAXB can help you a lot, if this is what you want to do.
if you have a class XMLBuilder that writes some XML, and the way the XML is built depends on the kind of user, then I would suggest to model your different kind of users with a hierarchy of classes, and then use method overloading in XMLBuilder, i.e. have several build() methods each one taking as input a different subclass of your user-kind hierarchy.
I hope this helps.

Categories