What is the best pattern to persist objects? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I need to persist objects and I want to keep my data classes as clean as possible. The persisted classes do not feature any business-logic code, but only data with getters/setters.
I'm currently implementing a solution with the Observer pattern. Each time an Observable persisted object is modified, it fires a message to an Observer object that takes care of persistence. This way, the only constraint for the persisted object is to be "Observable". It keeps things clean.
Another solution (maybe better?) would be to implement some DAO pattern, and I'm not very aware of the way it works. Maybe it would look like persistedObject.save(); or persistedObject.readById(id);. But it means I would have to define some DAO interface and then to implement the read/create/update/delete method in each and every persisted class

There are many, many, many answers to this question, data serialization or persistence is a core problem in software engineering. Options include using databases, memory mapped files, binary and textual formats, and more.
My personal favorite for quickly persisting objects is GSON, however your use case will dictate what works best for you.
You mention wanting design patterns for persisting Java objects, and while such patterns are approximately as numerous as there are libraries, here are a couple general suggestions:
Use immutable objects
Use the transient keyword for any fields that are not necessary to reconstruct an object
Avoid defining sanity checks or otherwise limiting the range of acceptable values in your objects - an instance constructed from a deserialize call may not correctly trigger your checks, allowing possibly invalid objects to be constructed
Use your serializable objects to construct more complex objects if you need more sanity checking, e.g. serialize a StubPerson POJO, and have a Person object that can be constructed from a StubPerson only as long as the stub's values are valid

I don't know if it fits for you but since you have only bean classes you could use the Java persistence api.

The DAO pattern is the best one to manage data access and persistence as it has been designed specifically for that.
Considering your needs you will probably have to couple it with some factory pattern in order to manage the different implementations (persistence adapters).
I don't know your requirements but if your application can be used by many persons at the same time you will have to care about concurrent accesses and define a policy (transaction, locking, etc... otherwise people will overwrite data each others).
Regarding your question i'd suggest JDO (with data nucleus as implementation) but the learning curve may be too expensive for your effective needs.

Related

Microservice design : one single call or two separate APIs? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a monolithic app that does the following logics:
Get a list A (Customer) from database
Validate data in A using some criteria, if it's not validated, throw an error
Do some operations on A to get a list B (e.g. Regional customers)
Do sth with B
Now I am transforming my app using microservices, but I have trouble in designing the calls.
As B can be deduced from A entirely, I want to just make a single micro service getCustomerA that returns all the dataset A. That means a single database access is needed. That will be a performance plus.
But the problem is, the operations on A to retrieve list B is also part of the business code. So it's more logical to put these codes in Customer microservice side, if we follow domain driven design, in microservice Customer, maybe getRegionalCustomer.
So I want to know, what is the best practice in this case ? Should we priotize the single database call (first case) or it's better to do two calls (but in this case, 2 database calls) ?
Since this is mainly opinion based I can only give you that :-)
From my experience splitting the app into microservices just for the sake of doing it puts technical dogma over technical simplicity and often introduces a lot of unnecessary overhead.
With regard to the database calls I can also tell you from experience that quite often you win performance when doing two simple calls over doing one overly complex one. Especially if you start introducing big joins over many tables or - ouch - subselects in the on clause.
See if the most simple solution works and keeps the code tidy. Constantly improve quality and optimize when the need for it arises. If you have a piece of logic that warrants to be split of into a microservice (e.g. because you want to use a different language, framework or want to offload some calculations) then go for it.
Domain driven design does not tell that each boundle context only can contains one entity, in fact, a bounded context (or microservice) can contains more than one entity when these entites are clearly related, in other words, when they need to be persisted transactionally.
In your case, due to the tight relation between the two entites, the best way is to build only one microservice that do both operations

what is difference between persistence and serialization? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have gone through this link but i'm looking for convincing answer.
Visit http://www.coderanch.com/t/270170/java-programmer-SCJP/certification/Difference-serialization-persistence
Serialization is the process of converting an object to another representation (often binary, though you can serialize to other forms like xml, but the default java serialization mechanism is to a binary form). You can persist that serialized form of the object for reading in (deserialization) to restore that object. Serialization is also used as a mechanism for sending java objects across processes/machines (e.g. with RMI). Serialization is not persistence but persistence is one way it can be used.
Simple answer: Serialization is the process of changing the represenation of an object to another (mainly for the purpose of transfering it over a communication mechanism), whilst persistence targets the purpose of persisting (yes, it is the same word) object states ( for later retrievment) to a physical storage.
Both topics are strongly related, though. Most persistence layers rely on object serialization and deserialization and not too many provide binary dump and restoring of objects.
Interestingly most developers see implementing processes of de/serialization as a rather boring task whilst developing a persistence layer is more part of interest.
Well, obviously, the second one is more complex and the former one is often just a subtask of it.
Persistence - a mechanism to allow you to keep status between executions of your application.
Perhaps a database, maybe files, sometimes cache, in some cases very weird like in the cloud.
Serialization - a way of representing an object in a serial form that allows it to be stored for later recovery.
Often used to persist objects.

Java Persistent Entities best practices [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am writing my persistent classes for a Java EE 6 project.
I am seeking best practices in writing these classes.
For example, i know that adding version field is recommended.
I am waiting for your help. Merci
UPDATE 1:
I am writing classes for an ecommerce: persons, products, reviews ....
That really depends on what are the requests.
Adding fields just because it is "recommended" may hurt performance, as they are mapped to columns at DB.
Maybe your flow does not require "versioning" at all?
What I would like to suggest for you is (if you insist on using JPA/Hibernate) is:
A. Think of your business logic entities - for example, if this is an application for a library, entities may be - Book, Author, Shelf, Room, Librarian, Reader, and so on...
B. Model the relationships between these entities - For example - a Book may be written by several author. Each other may write several books
Once you're done with this Java/OOP modelling, move on and intorduce relationships, based on JPA annotations:
For example, for the above book author relationship you will need the #ManyToMany annotation.
At this point you will also need to define what are your primary key columns.
You should also consider whether an entity which is used once per each other entity instance - for example - an Address will be used once per Reader, should be kept in a separate table, having OneToOne annotation, or will you prefer to keep it at the Reader table, using an Embeddable class.
However, the best practice can really change when it comes to the domain of the application, the required performance and the use cases.
I would suggest you to start building/designing your application and ask more specific questions.
If you are using JPA in your application, you should need to understand EntityManager and Relationships at least. See this link to learn the usages of JPA. It may be helpful for you.

MVC where model has no intrinsic visual representation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm developing an application in Java with MVC architecture. Doing so has greatly decoupled and simplified my code, but the problem is that the model has no intrinsic visual representation. That is, there are no characters, no specific enemies, no buttons, no text boxes - the model is made up of hundreds of instances of one type of object. Each instance is controlled by an instance of a strategy pattern (technically, it's a hierarchy of strategy patterns); it is the only differing point between each instance in the application. The type of strategy each instance uses should therefore ideally make it look slightly different than others around it.
I'd like to avoid a giant if statement chain with dozens of "instance of" calls checking for the type of strategy used when developing a view for this application. I'd also like to avoid a similar chain using an enumeration. Any suggestions as to how I can make my view without succumbing to a massive if chain? Any suggestions as to how I could design my view properly so that it wouldn't be so tightly coupled to the strategy instances?
Thanks in advance for your time!
#DJClayworth asks the critical question:
Are you interested in presenting to the user the strategy [to be] selected, or the results of that strategy?
Assuming you'll need both, let the model contain an enumeration relating strategy names, implementations and descriptive text. The implementation can use a class literal as a runtime-type token.
In this example, enum Rule serves all three purposes as an implicit model. It supplies a legible name and description, as well as a constant representing a particular composite strategy. No case statements are required.

What problems do you find with this view on domain-driven design? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I just wrote a long (and messy) blogpost about my view on domain-driven design at present day, with frameworks like spring and hibernate massively in use.
I'd ask you to spot any problems with my views on the matter - why this won't work, why it isn't giving the benefits of DDD, why it is not a good idea in general.
The blogpost is here (I don't think I need to copy-paste it on SO - if you think I should, tell me).
I know the question is subjective, but it is aimed at gathering the most predominant opinions.
(I'm tagging Java, since the frameworks discussed are Java frameworks)
I've just spent a year of my life ripping apart an application to eliminate an anaemic domain anti-pattern and its mis-use of Hibernate.
I can say without a doubt that the code that comes as a result of DDD is much easier to understand and refactor. In our case, the removal of a myriad unnecessary getters & setters, the increase in encapsulation, the concentrating of business logic, and resulting (dramatic) simplification of the services layers that come along with DDD have made the system so much more easy to maintain that now I believe we will be able to finish it, whereas before it was dragging on into forever. We've reduced the line count of this application by 50% without removing any functionality.
I also believe that the entire point of an ORM tool is so that my business logic is uncluttered with persistence code. When we had an anaemic domain model, we had a DAO for every domain class, now we have a small handful of DAOs as an entry point for CRUD on the "major" domain classes, but the other "minor" domain classes are handled by their parents...not because persistence logic is in the parent but because Hibernate transparently reacts to the business logic and makes everything Just Work.
In short, I can't answer this SO question because I emphatically agree with your post 100%...and am living it every day.
We go with the "anemic model" approach so that we can reuse the same models with different business logic. However, we do include calculations and helper methods within our models if they're applicable for all cases. But we do not inject anything into our models and do not inject our models into IoC.
Personally I'm not convinced that the part about injecting repository objects into the domain objects (meaning the persistent entities) is necessary with Spring and Hibernate. Hibernate is already providing persistent collections that can do lazy loading, so you already have the ability to traverse the domain model in a way that separates data-access infrastructure from business logic. I don't see what value tacking repositories onto the domain model is adding.
EDIT: Oops, posted this before reading the whole article. Now that I've read the entire blog post I think I'm in agreement with it. I like the part recommending doing without DTOs wherever possible.

Categories

Resources