Which way is better when insert a record to the database using id generator? - spring-boot

Because my project may be adapted to mysql or oracle,so I have a method that to produce id .When insert a new student record, the student record should call the method to produce the id. But what I'm curious about is when to call the method.Now my project is build by spring cloud. I should call the method in service module and pass the student object with id to the dao module. Or I pass the student object and the in the dao module,I call the id generator?
Which way is better?

Ok, i've decided to extend my comment.
In my opinion a better way would be to generate id inside dao, because you need id to save object in database, so you have to be sure that id is generated. For example if you have multiple clients and each client can save to database object student it would be difficult to make sure that each client uses id generator method in proper way. If you would use this method you don't need to take care about validation of id.
Moreover generating id inside dao follow low coupling principle.

Related

Sprind Boot Controller When Using Hibernate #Inheritance (Single Table)

I've seen a lot of information on the different inheritance strategies but can't seem to find anything on how you setup a REST controller when using a single table strategy. In my scenario, I have 2 Barcode types: product and case.
I created a Barcode superclass that ProductBarcode and CaseBarcode inherit from. However, I have the following questions regarding how to implement this:
Do I need separate repositories for ProductBarcode and CaseBarcode?
Can I use a single endpoint to create/update/delete both kinds of Barcodes?
I have another entity (Product) that relates to Barcode and needs to be able to get the details for a barcode based on an ID. Product won't know what type of Barcode the ID belongs to. Is this something that will cause an issue?
To summarize what I'm trying to do:
Create a barcode entry of either ProductBarcode or CaseBarcode by sending a JSON POST request to a single endpoint such as localhost:8080/barcodes.
Retrieve or update a barcode of either type from a single endpoint.
Be able to perform CRUD operations without needing to know which type of Barcode is being operated on.
Is this something that is doable using Spring Data JPA and Hibernate? Thanks for any advice.

Combine DAO and Entity in Spring and Hibernate

I was wondering if it is possible to combine DAO and Entity in a single class. e.g.
In rails
If I have table named user then there will be one ActiveRecord User and by using that class I can access access Methods related to DB and user i.e. it has both methods user.name (accessing object properties) and user.save / User.get_all methods (managing DB interactions) in the same class
In Spring/Hibernate Configuration
I have two things: DAO and Entity
Entity: I have User class that is an entity and is mapping Table as POJO, so that I can access methods related to a single user e.g. user.getName()
DAO: I have a DAO in which there are DB interactions e.g. userDAO.save(user) and userDAO.get(id).
Question:
I was wondering if I can create single User class and define User properties and getter/setter inside along with DB interactions so that I can single class as both, i.e. user.getName() (as POJO) and User.get(id)/user.save() (as DAO).
Is this method possible, and why are the complications I might run into, if I start with this approach?
it's called Active Record Pattern . Here is article about topic for JPA . Active Record Pattern . and example https://github.com/ActiveJpa/activejpa
Is this method possible, and why are the complications I might run into, if I start with this approach?
it's :
Cohesion & Coupling
if it's real project , it might become problem to support it
when you have 20 entities it's difficult to decide where to put method into what entity , and also find method that you need as it might be in many places
when you don't use active record pattern you can share entity with web layer , with active record entity can't be Serializable.
code become bigger and bigger

Save multiple row data and some other data into two tables simultaneously in spring hibernate

I want to save data of a form into two tables simultaneously. The form contains multiple identical rows with some fields like
item, unit, unit_price, total.
1.) In the table1 I would like to save some data like id(auto generated, primary key), date, creator.
2.) In table2 I would like to save the id(auto generated, primary key), fid(id of the table1, foreign key), item, unit, unit price, total. Remember, in table2 multiple rows will be save from the form data.
I can't figure it out. Please help me with a valid step by step example, and please don't use static or pre-defined data, take the data from form only.
Is your form an HTML form on a web page, and are you writing a Spring MVC application? Have you setup Spring Security, or some other authentication mechanism such that you know who the user is? If so, here is one approach:
Define a plain old Java object (POJO) with fields id, unit, unit-price, total, creator, currentDate; perhaps you would name it Item.
Define another plain old Java object perhaps named "ItemHistory", with its own ID and a reference to an Item.
In the first POJO ("Item") include a reference to a list of ItemHistorys.
Annotate both classes with Hibernate/JPA annotations, such that the Item has a OneToMany relationship to ItemHistory.
Define a Spring MVC controller with a method annotated as a POST method, with an Item as one parameter, and an Authentication as another parameter (supposing you have configured Spring Security, the Authentication will automatically be populated with the identity of the currently-logged-in user. In this method, set the currentDate and author of the Item to the current date and the principal from the Authentication parameter. If it is a new Item (no id yet), add the first ItemHistory as a copy of the Item itself. If it is an existing item, add another ItemHistory if needed.
Define a Spring bean, perhaps named ItemService, with a method annotated as transactional, that takes an Item and saves it. Call this bean from the REST controller. Such a Spring bean is known as a DAO (data access object).
There are other strategies, but if you already have Spring MVC, Spring Security, and Hibernate/JPA configured to your needs, this one is pretty straight-forward.

is this a good idea to implement validation in entity framework POCO entities in dabtase first?

It`s seems that the best place to implement validation is as close as possible to the database, so when I use entity framework the nearest objects are the entities, in my case the POCO entities.
The reason for that is that if I want to reuse this POCO entities, the validation is implemented in the POCO objects and then there are less posibilities to insert worng data in the database.
this also avoid that someone try to insert incorrect data in the databse creating another application, or because he does not implement the validation. So it is more secure.
One way to do that is using partial classes that extends the POCO entities and that implements the IValidatableObject interface and return a list of validationresult.
But other way is the following. I have a common assembly that has the following:
One interface that declare the methods that need to implement the repositories.
The POCO entities that will be used by the repositories.
One class with utilities, such as copy entities and methods to validate the data of the entities.
Then I can create many repositories that use different versions of EF or another technology and all of them use the common assembly. This repositories implements the validation using the methods in the common library.
In this case I implement the validation only once. The only problem is that the repositories need to call the methods to validate the data.
But there are advantages in this way, from my point of view. For example, I can validate the data of the entities depending on the type of the operation. For example, if I am adding a new record and the primary key as an autonumeric, if the ID is not 0, then I can throw an exception, or if I try to delete a register when the ID is 0, then I don't need to send the command to the database.
So this second solution solves the problem to implement the validation as close as possible to the database, bacause is used in the repository, that is the element that access to the database, but has the problem that if some developer creates a new repository and not use the validation methods, I can have incorrect data in the database.
So my question is if the best option is to use validation with partial classes or to use a common library and the validation is implemented in the repositories, that is really what the users will use.
Thanks.
OK - phew, big question. My opinion is that the APPLICATION DOMAIN of the application is the boss of everything. The database is just an add-on service. So, the application domain should ultimately validate ALL objects that are being SENT somewhere. No need to validate object coming out of the DB because they were validated going in.
As an example, what if you were creating some object that needed to be sent off to a web service and it needed validation. Lets say it was never going near the database or the repositories. Once the DOMAIN business objects have been validated, they can then be sent for persistence or anywhere else.
Another thing to consider is what you mean by validation. Does it mean the datatypes are correct? Does it mean the business object is valid? Does it mean the business object is valid in the given context? It could mean all or only some of these things.
As an example, what if your system allows users to partially update records (common with very long input forms). The business object may only become valid when ALL the required data is captured, but the database allows persistence of "partial" data. In other words, you can save the business object to the database although it is not valid for further processing yet. etc etc....

Entity Framework: Implement interface when generating from database

I'm having a few tables on SQL Server, which have similar structure - int Id and string Value.
This tables linked to main table via foreign key, so I'm wrote a bit of logic for mapping a string values to id's in models in MVC Razor. This feature requires that models used as dictionary implement simple IKeyValue interface with Id and Value, but after updating model from database I can loose interface implementation from models and must write it again.
Any way to automate this?
Are you modifying the auto-generated file? If so, you should not do this, for the exact reason you describe in your question -- it will get overwritten.
All of the classes in the generated file should be partial. You can take advantage of this by creating another class (in a different file, but in the same project), make sure it has the same declaration (and namespace), and have it implement the interface. This way the class will implement the interface, but will not be overwritten the next time you refresh the schema from the database.

Resources