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 5 years ago.
Improve this question
All of the examples I've read about DAO classes only show DAO classes with very general methods, for example, insertNewCar(), deleteCar(), updateCar(), getCars(), getCarByID(). But can I put more specific methods into a DAO class?
In my case, I need to get all doctors who are having a shift today, and to know that, I have to get all doctors' scedules which have the date equal to today. Right now, I'm getting those doctors by a single method in doctorDAO class called getDoctorsWorkingToday(ArrayList scedulesToday). In this method, I first get all ids of doctors from the arraylist and attact them into a complete sql query. And the rest of the method is just like a normal "get" method: I use the query to get all doctors I want, put them into an arraylist and return it.
It works fine, but is that solution acceptable? Or must I only use general methods in DAO class like getAllSchedules() and getAllDoctors(), and do all the filter stuff in other classes?
As per my understanding , I usually put all db specific code (queries) in DAO's and transaction handling and business logic in service layer. This allows for service methods to invoke methods across multiple dao's and keep it all within same transaction. In my opinion, this is allows for better code reuse across dao's.
In your case,
Use 'get' method business logic in Service layer and Query related stuff in dao.
It's upto you, how you are implementing the service and dao. Just for the flow and easy understanding,we are following the standards.
Related
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 2 years ago.
Improve this question
I know both ways would work, but I'm not sure which way would be more clean and flexible.
There is OrderService and it has the following methods:
searchOrders
setBookableFlag
mappingWithCarrier
Method 1: Invoking all the methods in controller
OrdersController:
public OrderCarrierDTO searchOrders(#PathVariable carrierGuid){
List<Order> orders = ordersService.searchOrders();
ordersService.setBookableFlag(orders, carrierGuid);
return orderService.mappingWithCarrier(orders, carrierGuid);
}
Method 2: Create a new method in Service and put all the callings in the method and invoke that new method from Controller:
OrdersController:
public OrderCarrierDTO searchOrders(#PathVariable carrierGuid){
return orderService.searchOrdersForCarrier(carrierGuid);
}
I prefer method 2
The controller should only be handling input / output. So the job of the controller is receive the carrierGuid and pass that to the service which then does its thing. The result of this (or an exception) comes back to the controller and then the controller returns the proper http code / body for it
I would suggest to use Method 2, Along with that you should ideally make all other three methods private and not accessible to the users of your service class.
That means the controller should not care if you call 3 or 30 methods inside your service, it should just know that if I call this method then it will get the output.
Since it's a good practice to maintain all the business logic in service and minimum code at controller layer, I would recommend the second approach. Assuming getting Orders for any Carrier is a frequent task, so maintaining a separate method (searchOrdersForCarrier()) in service for such tasks comes handy instead of calling multiple methods each time. if searchOrders() setBookableFlag() mappingWithCarrier() are also of reusable nature we can maintain them as separate methods and use them in searchOrdersForCarrier().
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 4 years ago.
Improve this question
Recently I started thinking about #Transactional and how it works and the performance and I have a project where I use spring transactions, so I have such code:
#Transactional
public PageableProductsDTO getUsersProducts(String userName, Pageable page) {
PageRequest pageRequest = PageRequest.of(page.getPageNumber(), page.getPageSize(), Sort.Direction.DESC, "createdAt");
Page<Product> pagebelProductsByUser = productRepository.findProductsByUser(userService.getUser(userName), pageRequest);
Page<ProductDetailsDto> productDtos = pagebelProductsByUser.map(source -> {
ProductDetails productDetails = source.getProductDetails();
return new ProductDetailsDto(productDetails.getBarcode(), productDetails.getName(), productDetails.getPrice());
});
return new PageableProductsDTO(productDtos);
}
As you can see, in the above method I fetch products from db, and then map the products to the PageableProductsDTO, I have doubts whether I do it right, because maybe the dto mapping should be done in controller layer? And also it seems that doing such mapping in the service layer will prolong time spent for transaction itself, I mean maybe it's not good in perspective of performance?
There’s no universal solution, only the one that suits you best. It’s not about DTOs being pattern or anti-pattern, it’s about do you need them or not.... and why
One part of the question is if you should re-pack data in controller or service layer. That depends fully on if you introduced DTOs to separate data and business logic of your application layers OR you introduced DTOs to re-pack data (maybe remove some private properties) that will be returned to the client (if latter is the case, controller should do the business).
Although performance impact looks negligible in this case, you should1 move logic of loading data from DB in separate method and mark that one2 as Transactional.
1 Separation of methods will allow you to re-use code that loads data from DB inside service layer, without need to re-pack data back to entities.
2This will be good pattern as long as you want to commit a transaction after executing db load. If you want to re-use method for loading data from DB please consider other use-cases and if you want to prolong committing.
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
In J2EE design, usually we have view layer, business layer and dao layer. In business layer, if we need some other data, shall we call the DAO directly or call the other data's business service?
I like this question, because I had to find the answer, and later convince the others... So my view, coming from experience on some projects is:
Business Layer should be built from Componenents (I would name them Facades) which are responsible for some tasks. E.g.
Validate Entity/Object before it is persisted (DAO is called) (kind of Persist(entity))
Or represent factory method CreateNew(), returning new objects with some basic business settings (pre-filled country, currency...)
load some data via Find(filter)
And I could continue, but at the end, I would end up with Facades, which are really doing their tasks and are responsible for them. And that means that we have the answer.
If there is already some business object (Facade) representing some specific task... other business componenets should use it. They should not reimplement it again.
To say it clearly explicitly:
Other layers (presentation, scheduled job) should call only one Business API (service/facade)
This Business Service/Facade should do its job, and if needed it should call other Business Service(s)/Facade(s) and ask them to do their job.
That service should NOT call DAO if this is already implemented elsewhere.
So if there si some BL guy, ready to get data from DAO or pass (and validate) some other data into DAO ... we should use it...
At the end, we have DRY and SOLID principles in place... and code becomes easy to maintain and extend. For example, if we know that there is only one EmployeeFacade.Find(filter), it is easy to introduce AOP and be sure that all the results could be intercepted...
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 9 years ago.
Improve this question
The code base that I work with has a common set of data-access methods in an abstract base class which is extended by many different entity-specific DAO classes.
As there are currently no tests covering any of this logic, I've started adding tests for a specific entity DAO which covers the common data-access methods as well as the custom methods in that DAO.
Writing tests to cover the exact same common methods for each other entity DAO seems like a waste of time and a maintenance nightmare, so I only have the one so far. On the other hand, having those tests for all entity DAOs may help us catch differences between our schema and entity mappings.
Is there any real benefit to having integration tests of common methods for every entity DAO?
It is ok to write test for all these methods, however here are somethings you should to take into consideration
Time: It will take time to implement all these test. If for some reason you need to allocate development resources else where you should really take this into consideration.
Maintenance: You need to maintain all these test, if you decide to write them.
Redundancy: These method will behave similar in most cases and can be a waste of time to implement in the first place.
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 9 years ago.
Improve this question
In Java I have the abstract class Place, with two concrete subclasses Area and Level; a Level must have a parent Area. But in trying to make unit tests for Level, I don't want to have create a full-fledged instance of Area. I see two ways of dealing with this:
1) Create an interface IPlace, extended by interface IArea, which Place and Area implement. Then create a MockArea class which implements IArea, and pass that to Level when testing it.
2) Use a mocking framework which will automatically create mock objects for me.
Which way is better? Or is there a third way to do it?
You're not giving us the reason why you don't want to create a full-fledged Area, but lets assume it does something difficult to test, like connect to a DB or read a file or something. Those are dependencies that it has. Dependency Injection is the answer.
For example, let's say Area does this in its constructor:
public Area() {
//get db connection
//do something with db connection
}
Now when you create a Level, it'll connect to a DB. Here's how you'd rewrite the constructor to use Dependency Injection:
public Area(Connection con) {
//do something with db connection
}
Now, when you create a Level, you can give it a fake Connection and are able to test your Level.
Now you can use a mocking framework to make a fake Connection. I recommend Mockito.
As you've written it, I'd suggest using a mocking framework.
Dependency Injection is great. Using it lets your classes state in an obvious way what types of things they need to interact with. If done properly, the need for mocked objects is often unavoidable. Get used to working with a mocking framework. I like Mockito personally.