In my application I use DTOs. My current solution in pseudocode is this - works well:
ResponseEntity<EntityDTO> RestController.get(String uuid){
EntityDTO dto = Service.get(uuid) {
Entity entity = Repository.loadEntity(id);
return EntityDTO.from(entity);
}
return ResponseEntity<EntityDTO>( dto , HttpStatus.OK);
}
Recently I saw an other solution without the transformation step in the service layer.
E.g. your Entity looks like this
:
#Entity
public class Book {
Long id;
String title;
String text;
.....
}
And the text is too 'heavy' to send it with the hole book you usually would create a DTO like this:
public class SlimBookDTO {,
static SlimBookDTO from(Book book) {
return new SlimBookDTO(book.id, book.title);
}
Long id;
String title;
.....
}
The "new" (for me) Solution is to create only an interface like this:
public interface SlimBookDTO {
Long getId();
String getTitle();
}
And your BookRepository gets a new method:
#Repository
public interface BookRepository extends JpaRepository<Book , Long> {
List<SlimBookDTO> findAllByTitle(String title);
}
With this method I don't need the service layer any more for direct requests. Is this common? Does somebody has experience with this? Has it some downsides that I can't see in a small application but will face in larger scale?
Those are couple of ways of returning data from the database.
You create DTO and map necessary fields and return
Other is create an interface which is directly a kind of return type from Repository. this is what we call as JPA interface projection.
For second one, you know in detail by referring below link
https://www.baeldung.com/spring-data-jpa-projections
JPA interface projections are very useful when we query two or more entities in the Repository class
This is totally fine for simple GETs if the objects are straightforward enough, although of course you can't add additional logic, formatting or constraints. But as long as you don't need to do that, this will work well.
I don't think Hibernate analyzes the dto to only select a few fields though, so if you want to improve the performance too you can define the queries yourself, i.e. #Query("select new com.bla.SlimbookDTO(book.id, book.title) from Book book"), at the cost of not being able to just use automagically generated queries anymore based on the method name.
Related
Problem
To make my code cleaner i want to introduce a generic Repository that each Repository could extend and therefore reduce the code i have to have in each of them. The problem is, that the Ids differ from Class to Class. On one (see example below) it would be id and in the other randomNumber and on the other may even be an #EmbeddedId. I want to have a derived (or non derived) query in the respository that gets One by id.
Preferred solution
I Imagine having something like:
public interface IUniversalRepository<T, K>{
#Query("select t from # {#entityName} where #id = ?1")
public T findById(K id);
}
Ecample Code
(that does not work because attribute id cannot be found on Settings)
public interface IUniversalRepository<T, K>{
//should return the object with the id, reagardless of the column name
public T findById(K id);
}
// two example classes with different #Id fields
public class TaxRate {
#Id
#Column()
private Integer id;
...
}
public class Settings{
#Id
#Column() //cannot rename this column because it has to be named exactly as it is for backup reason
private String randomNumber;
...
}
// the Repository would be used like this
public interface TaxRateRepository extends IUniversalRepository<TaxRate, Integer> {
}
public interface SettingsRepository extends IUniversalRepository<TaxRate, String> {
}
Happy for suggestions.
The idea of retrieving JPA entities via "id query" is not so good as you might think, the main problem is that is much slower, especially when you are hitting the same entity within transaction multiple times: if flush mode is set to AUTO (with is actually the reasonable default) Hibernate needs to perform dirty checking and flush changes into database before executing JPQL query, moreover, Hibernate doesn't guarantee that entities, retrieved via "id query" are not actually stale - if entity was already present in persistence context Hibernate basically ignores DB data.
The best way to retrieve entities by id is to call EntityManager#find(java.lang.Class<T>, java.lang.Object) method, which in turn backs up CrudRepository#findById method, so, yours findByIdAndType(K id, String type) should actually look like:
default Optional<T> findByIdAndType(K id, String type) {
return findById(id)
.filter(e -> Objects.equals(e.getType(), type));
}
However, the desire to place some kind of id placeholder in JQPL query is not so bad - one of it's applications could be preserving order stability in queries with pagination. I would suggest you to file corresponding CR to spring-data project.
I was going through a document and I came across a term called DAO. I found out that it is a Data Access Object. Can someone please explain me what this actually is?
I know that it is some kind of an interface for accessing data from different types of sources, in the middle of this little research of mine I bumped into a concept called data source or data source object, and things got messed up in my mind.
I really want to know what a DAO is programmatically in terms of where it is used. How it is used? Any links to pages that explain this concept from the very basic stuff is also appreciated.
The Data Access Object is basically an object or an interface that provides access to an underlying database or any other persistence storage.
That definition from:
http://en.wikipedia.org/wiki/Data_access_object
Check also the sequence diagram here:
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Maybe a simple example can help you understand the concept:
Let's say we have an entity to represent an employee:
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The employee entities will be persisted into a corresponding Employee table in a database.
A simple DAO interface to handle the database operation required to manipulate an employee entity will be like:
interface EmployeeDAO {
List<Employee> findAll();
List<Employee> findById();
List<Employee> findByName();
boolean insertEmployee(Employee employee);
boolean updateEmployee(Employee employee);
boolean deleteEmployee(Employee employee);
}
Next we have to provide a concrete implementation for that interface to deal with SQL server, and another to deal with flat files, etc.
What is DATA ACCESS OBJECT (DAO) -
It is a object/interface, which is used to access data from database of data storage.
WHY WE USE DAO:
To abstract the retrieval of data from a data resource such as a database.
The concept is to "separate a data resource's client interface from its data access mechanism."
The problem with accessing data directly is that the source of the data can change. Consider, for example, that your application is deployed in an environment that accesses an Oracle database. Then it is subsequently deployed to an environment that uses Microsoft SQL Server. If your application uses stored procedures and database-specific code (such as generating a number sequence), how do you handle that in your application? You have two options:
Rewrite your application to use SQL Server instead of Oracle (or add conditional code to handle the differences), or
Create a layer in-between your application logic and data access layers
The DAO Pattern consists of the following:
Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).
Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource
which can be database / xml or any other storage mechanism.
Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.
See examples
I hope this has cleared up your understanding of DAO!
DAO (Data Access Object) is a very used design pattern in enterprise applications. It basically is the module that is used to access data from every source (DBMS, XML and so on). I suggest you to read some examples, like this one:
DAO Example
Please note that there are different ways to implements the original DAO Pattern, and there are many frameworks that can simplify your work. For example, the ORM (Object Relational Mapping) frameworks like iBatis or Hibernate, are used to map the result of SQL queries to java objects.
Hope it helps,
Bye!
Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern.
Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).
Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism.
Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.
Sample code here..
Don't get confused with too many explanations. DAO: From the name itself it means Accessing Data using Object. DAO is separated from other Business Logic.
I am going to be general and not specific to Java as DAO and ORM are used in all languages.
To understand DAO you first need to understand ORM (Object Relational Mapping). This means that if you have a table called "person" with columns "name" and "age", then you would create object-template for that table:
type Person {
name
age
}
Now with help of DAO instead of writing some specific queries, to fetch all persons, for what ever type of db you are using (which can be error-prone) instead you do:
list persons = DAO.getPersons();
...
person = DAO.getPersonWithName("John");
age = person.age;
You do not write the DAO abstraction yourself, instead it is usually part of some opensource project, depending on what language and framework you are using.
Now to the main question here. "..where it is used..". Well usually if you are writing complex business and domain specific code your life will be very difficult without DAO. Of course you do not need to use ORM and DAO provided, instead you can write your own abstraction and native queries. I have done that in the past and almost always regretted it later.
I think the best example (along with explanations) you can find on the oracle website : here. Another good tuturial could be found here.
Spring JPA DAO
For example we have some entity Group.
For this entity we create the repository GroupRepository.
public interface GroupRepository extends JpaRepository<Group, Long> {
}
Then we need to create a service layer with which we will use this repository.
public interface Service<T, ID> {
T save(T entity);
void deleteById(ID id);
List<T> findAll();
T getOne(ID id);
T editEntity(T entity);
Optional<T> findById(ID id);
}
public abstract class AbstractService<T, ID, R extends JpaRepository<T, ID>> implements Service<T, ID> {
private final R repository;
protected AbstractService(R repository) {
this.repository = repository;
}
#Override
public T save(T entity) {
return repository.save(entity);
}
#Override
public void deleteById(ID id) {
repository.deleteById(id);
}
#Override
public List<T> findAll() {
return repository.findAll();
}
#Override
public T getOne(ID id) {
return repository.getOne(id);
}
#Override
public Optional<T> findById(ID id) {
return repository.findById(id);
}
#Override
public T editEntity(T entity) {
return repository.saveAndFlush(entity);
}
}
#org.springframework.stereotype.Service
public class GroupServiceImpl extends AbstractService<Group, Long, GroupRepository> {
private final GroupRepository groupRepository;
#Autowired
protected GroupServiceImpl(GroupRepository repository) {
super(repository);
this.groupRepository = repository;
}
}
And in the controller we use this service.
#RestController
#RequestMapping("/api")
class GroupController {
private final Logger log = LoggerFactory.getLogger(GroupController.class);
private final GroupServiceImpl groupService;
#Autowired
public GroupController(GroupServiceImpl groupService) {
this.groupService = groupService;
}
#GetMapping("/groups")
Collection<Group> groups() {
return groupService.findAll();
}
#GetMapping("/group/{id}")
ResponseEntity<?> getGroup(#PathVariable Long id) {
Optional<Group> group = groupService.findById(id);
return group.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
#PostMapping("/group")
ResponseEntity<Group> createGroup(#Valid #RequestBody Group group) throws URISyntaxException {
log.info("Request to create group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.created(new URI("/api/group/" + result.getId()))
.body(result);
}
#PutMapping("/group")
ResponseEntity<Group> updateGroup(#Valid #RequestBody Group group) {
log.info("Request to update group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.ok().body(result);
}
#DeleteMapping("/group/{id}")
public ResponseEntity<?> deleteGroup(#PathVariable Long id) {
log.info("Request to delete group: {}", id);
groupService.deleteById(id);
return ResponseEntity.ok().build();
}
}
The Data Access Object manages the connection with the data source to obtain and store data.It abstracts the underlying data access implementation for the Business Object to enable transparent access to the data source.
A data source could be any database such as an RDBMS, XML repository or flat file system etc.
DAO is an act like as "Persistence Manager " in 3 tier architecture as well as DAO also design pattern as you can consult "Gang of Four" book.
Your application service layer just need to call the method of DAO class without knowing hidden & internal details of DAO's method.
Dao clases are used to reuse the jdbc logic & Dao(Data Access Object) is a design pattern.
dao is a simple java class which contains JDBC logic .
Data Access Layer has proven good in separate business logic layer and persistent layer. The DAO design pattern completely hides the data access implementation from its clients
The Java Data Access Object (Java DAO) is an important component in business applications. Business applications almost always need access to data from relational or object databases and the Java platform offers many techniques for accessingthis data. The oldest and most mature technique is to use the Java Database Connectivity (JDBC)API, which provides the capability to execute SQL queries against a databaseand then fetch the results, one column at a time.
Pojo also consider as Model class in Java where we can create getter and setter for particular variable defined in private .
Remember all variables are here declared with private modifier
I just want to explain it in my own way with a small story that I experienced in one of my projects. First I want to explain Why DAO is important? rather than go to What is DAO? for better understanding.
Why DAO is important?
In my one project of my project, I used Client.class which contains all the basic information of our system users. Where I need client then every time I need to do an ugly query where it is needed. Then I felt that decreases the readability and made a lot of redundant boilerplate code.
Then one of my senior developers introduced a QueryUtils.class where all queries are added using public static access modifier and then I don't need to do query everywhere. Suppose when I needed activated clients then I just call -
QueryUtils.findAllActivatedClients();
In this way, I made some optimizations of my code.
But there was another problem !!!
I felt that the QueryUtils.class was growing very highly. 100+ methods were included in that class which was also very cumbersome to read and use. Because this class contains other queries of another domain models ( For example- products, categories locations, etc ).
Then the superhero Mr. CTO introduced a new solution named DAO which solved the problem finally. I felt DAO is very domain-specific. For example, he created a DAO called ClientDAO.class where all Client.class related queries are found which seems very easy for me to use and maintain. The giant QueryUtils.class was broken down into many other domain-specific DAO for example - ProductsDAO.class, CategoriesDAO.class, etc which made the code more Readable, more Maintainable, more Decoupled.
What is DAO?
It is an object or interface, which made an easy way to access data from the database without writing complex and ugly queries every time in a reusable way.
I'm working on an exercise where we're supposed to create a car-rental program in Java where all the data should be stored in a PostgreSQL database using JPA and EclipseLink.
I've managed to create a test-class which connects and stores/reads data to/from the database. Now I'm wondering how I should proceed to make this "big" car-rental program work together with the database...
We've got about 10 classes (Car.java, Customer.java, etc.), which I think based on an earlier example, should be connected to the main/client-classes (Customer_Client.java, Admin_Client.java, etc.) using a Controller-class(?). But I'm not quite sure how and why. If I understand it right, I think the database connecting code etc. is supposed to happen in the main/client-classes?
Could someone which is familiar with this kind of programming/modelling (ORM) point me in the right direction about how the Controller-class should work together with the client-classes?
Based on the earlier example, I guess the Controller-class should contain a getCars, getCustomers etc. method for all the classes I need to access in the main/client-classes?
I'm also wondering how I should add "custom"/class attributes (e.g. Adress.java) as an column in a table in the database? When I'm trying using the same method as with the String and Integers for e.g. the Adress attribute, I get this exception:
"Exception Description: The type [class no.hib.dat101.Adress] for the attribute [adress] on the entity class [class no.hib.dat101.Customer] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface."
I guess this has something to do with the database table-column only supports certain datatypes?
A controller class in ORM is usually a DAO. DAO is a pattern which defines how to create/read/update/delete objects from database. A general DAO can look like this:
public interface Dao<E> implements Serializable{
public E find(int id);
public void insert(E entity);
public void update(E entity);
public void delete(int id);
}
And its implementation (for example for Car entity) can look like this:
public class CarDao implements Dao<Car>{
private EntityManager em;
public Car find(int id){
return em.find(id, Car.class);
}
public void insert(Car entity){
em.persist(entity);
}
public void update(Car entity){
em.merge(entity);
}
public void delete(int id){
em.delete(find(id));
}
}
For more info about DAO pattern please see Core J2EE Patterns - DAO (loooong but VERY good reading) or this link (shorter reading, but you will get a general idea about DAO faster :))
Entities update/insert is very easy, for example lets say that you want to set a new address for some customer.
private CustomerDao customerDao;
private Addressdao addressDao;
private int customerId;
public void updateCustomerWithAddress(){
Address address = new Address();
//init address variables
addressDao.insert(address);
Customer customer = customerDao.find(customerId);
//I assume you have a bidirectional oneToOne mapping between address and customer
address.setCustomer(customer);
customer.setAddress(address);
customerDao.update(customer);
}
In case of an exception you are getting, it says that your entities does not implement Serializable interface. So maybe by implementing this interface you will fix your issue, but we can really say much without actually seeing the code itself.
Basing on your exception, you should let no.hib.dat101.Adress implement java.util.Serializable so it is marked to serialize when saving a no.hib.dat101.Customer.
I guess this has something to do with the database table-column only supports certain datatypes?
No, your issue is not related with database. How about adding implementsSerializable to your Adress class declaration?
Read about it more here.
I was going through a document and I came across a term called DAO. I found out that it is a Data Access Object. Can someone please explain me what this actually is?
I know that it is some kind of an interface for accessing data from different types of sources, in the middle of this little research of mine I bumped into a concept called data source or data source object, and things got messed up in my mind.
I really want to know what a DAO is programmatically in terms of where it is used. How it is used? Any links to pages that explain this concept from the very basic stuff is also appreciated.
The Data Access Object is basically an object or an interface that provides access to an underlying database or any other persistence storage.
That definition from:
http://en.wikipedia.org/wiki/Data_access_object
Check also the sequence diagram here:
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Maybe a simple example can help you understand the concept:
Let's say we have an entity to represent an employee:
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The employee entities will be persisted into a corresponding Employee table in a database.
A simple DAO interface to handle the database operation required to manipulate an employee entity will be like:
interface EmployeeDAO {
List<Employee> findAll();
List<Employee> findById();
List<Employee> findByName();
boolean insertEmployee(Employee employee);
boolean updateEmployee(Employee employee);
boolean deleteEmployee(Employee employee);
}
Next we have to provide a concrete implementation for that interface to deal with SQL server, and another to deal with flat files, etc.
What is DATA ACCESS OBJECT (DAO) -
It is a object/interface, which is used to access data from database of data storage.
WHY WE USE DAO:
To abstract the retrieval of data from a data resource such as a database.
The concept is to "separate a data resource's client interface from its data access mechanism."
The problem with accessing data directly is that the source of the data can change. Consider, for example, that your application is deployed in an environment that accesses an Oracle database. Then it is subsequently deployed to an environment that uses Microsoft SQL Server. If your application uses stored procedures and database-specific code (such as generating a number sequence), how do you handle that in your application? You have two options:
Rewrite your application to use SQL Server instead of Oracle (or add conditional code to handle the differences), or
Create a layer in-between your application logic and data access layers
The DAO Pattern consists of the following:
Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).
Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource
which can be database / xml or any other storage mechanism.
Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.
See examples
I hope this has cleared up your understanding of DAO!
DAO (Data Access Object) is a very used design pattern in enterprise applications. It basically is the module that is used to access data from every source (DBMS, XML and so on). I suggest you to read some examples, like this one:
DAO Example
Please note that there are different ways to implements the original DAO Pattern, and there are many frameworks that can simplify your work. For example, the ORM (Object Relational Mapping) frameworks like iBatis or Hibernate, are used to map the result of SQL queries to java objects.
Hope it helps,
Bye!
Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern.
Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).
Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism.
Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.
Sample code here..
Don't get confused with too many explanations. DAO: From the name itself it means Accessing Data using Object. DAO is separated from other Business Logic.
I am going to be general and not specific to Java as DAO and ORM are used in all languages.
To understand DAO you first need to understand ORM (Object Relational Mapping). This means that if you have a table called "person" with columns "name" and "age", then you would create object-template for that table:
type Person {
name
age
}
Now with help of DAO instead of writing some specific queries, to fetch all persons, for what ever type of db you are using (which can be error-prone) instead you do:
list persons = DAO.getPersons();
...
person = DAO.getPersonWithName("John");
age = person.age;
You do not write the DAO abstraction yourself, instead it is usually part of some opensource project, depending on what language and framework you are using.
Now to the main question here. "..where it is used..". Well usually if you are writing complex business and domain specific code your life will be very difficult without DAO. Of course you do not need to use ORM and DAO provided, instead you can write your own abstraction and native queries. I have done that in the past and almost always regretted it later.
I think the best example (along with explanations) you can find on the oracle website : here. Another good tuturial could be found here.
Spring JPA DAO
For example we have some entity Group.
For this entity we create the repository GroupRepository.
public interface GroupRepository extends JpaRepository<Group, Long> {
}
Then we need to create a service layer with which we will use this repository.
public interface Service<T, ID> {
T save(T entity);
void deleteById(ID id);
List<T> findAll();
T getOne(ID id);
T editEntity(T entity);
Optional<T> findById(ID id);
}
public abstract class AbstractService<T, ID, R extends JpaRepository<T, ID>> implements Service<T, ID> {
private final R repository;
protected AbstractService(R repository) {
this.repository = repository;
}
#Override
public T save(T entity) {
return repository.save(entity);
}
#Override
public void deleteById(ID id) {
repository.deleteById(id);
}
#Override
public List<T> findAll() {
return repository.findAll();
}
#Override
public T getOne(ID id) {
return repository.getOne(id);
}
#Override
public Optional<T> findById(ID id) {
return repository.findById(id);
}
#Override
public T editEntity(T entity) {
return repository.saveAndFlush(entity);
}
}
#org.springframework.stereotype.Service
public class GroupServiceImpl extends AbstractService<Group, Long, GroupRepository> {
private final GroupRepository groupRepository;
#Autowired
protected GroupServiceImpl(GroupRepository repository) {
super(repository);
this.groupRepository = repository;
}
}
And in the controller we use this service.
#RestController
#RequestMapping("/api")
class GroupController {
private final Logger log = LoggerFactory.getLogger(GroupController.class);
private final GroupServiceImpl groupService;
#Autowired
public GroupController(GroupServiceImpl groupService) {
this.groupService = groupService;
}
#GetMapping("/groups")
Collection<Group> groups() {
return groupService.findAll();
}
#GetMapping("/group/{id}")
ResponseEntity<?> getGroup(#PathVariable Long id) {
Optional<Group> group = groupService.findById(id);
return group.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
#PostMapping("/group")
ResponseEntity<Group> createGroup(#Valid #RequestBody Group group) throws URISyntaxException {
log.info("Request to create group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.created(new URI("/api/group/" + result.getId()))
.body(result);
}
#PutMapping("/group")
ResponseEntity<Group> updateGroup(#Valid #RequestBody Group group) {
log.info("Request to update group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.ok().body(result);
}
#DeleteMapping("/group/{id}")
public ResponseEntity<?> deleteGroup(#PathVariable Long id) {
log.info("Request to delete group: {}", id);
groupService.deleteById(id);
return ResponseEntity.ok().build();
}
}
The Data Access Object manages the connection with the data source to obtain and store data.It abstracts the underlying data access implementation for the Business Object to enable transparent access to the data source.
A data source could be any database such as an RDBMS, XML repository or flat file system etc.
DAO is an act like as "Persistence Manager " in 3 tier architecture as well as DAO also design pattern as you can consult "Gang of Four" book.
Your application service layer just need to call the method of DAO class without knowing hidden & internal details of DAO's method.
Dao clases are used to reuse the jdbc logic & Dao(Data Access Object) is a design pattern.
dao is a simple java class which contains JDBC logic .
Data Access Layer has proven good in separate business logic layer and persistent layer. The DAO design pattern completely hides the data access implementation from its clients
The Java Data Access Object (Java DAO) is an important component in business applications. Business applications almost always need access to data from relational or object databases and the Java platform offers many techniques for accessingthis data. The oldest and most mature technique is to use the Java Database Connectivity (JDBC)API, which provides the capability to execute SQL queries against a databaseand then fetch the results, one column at a time.
Pojo also consider as Model class in Java where we can create getter and setter for particular variable defined in private .
Remember all variables are here declared with private modifier
I just want to explain it in my own way with a small story that I experienced in one of my projects. First I want to explain Why DAO is important? rather than go to What is DAO? for better understanding.
Why DAO is important?
In my one project of my project, I used Client.class which contains all the basic information of our system users. Where I need client then every time I need to do an ugly query where it is needed. Then I felt that decreases the readability and made a lot of redundant boilerplate code.
Then one of my senior developers introduced a QueryUtils.class where all queries are added using public static access modifier and then I don't need to do query everywhere. Suppose when I needed activated clients then I just call -
QueryUtils.findAllActivatedClients();
In this way, I made some optimizations of my code.
But there was another problem !!!
I felt that the QueryUtils.class was growing very highly. 100+ methods were included in that class which was also very cumbersome to read and use. Because this class contains other queries of another domain models ( For example- products, categories locations, etc ).
Then the superhero Mr. CTO introduced a new solution named DAO which solved the problem finally. I felt DAO is very domain-specific. For example, he created a DAO called ClientDAO.class where all Client.class related queries are found which seems very easy for me to use and maintain. The giant QueryUtils.class was broken down into many other domain-specific DAO for example - ProductsDAO.class, CategoriesDAO.class, etc which made the code more Readable, more Maintainable, more Decoupled.
What is DAO?
It is an object or interface, which made an easy way to access data from the database without writing complex and ugly queries every time in a reusable way.
I was trying to write a user authentication system in Java. So I wrote some DAO class. First I did write a class named Persistence which is abstract. It is responsible for holding some common attributes. And wrote a class named User extending Persistence class. Those classes are –
public abstract class Persistance {
private Date createdDate;
private Date lastUpdatedDate;
private long version;
private boolean isDeleted;
//getter and setters
}
and the user class
public class User extends Persistance{
private String username;
private String password;
private String passwordConfired;
// getters and setters
}
My questions are- what is the best way to write variable name, which one is good, createdDate or dateCreated, deleted or isDeleted etc.
And is this approach is okay or is there more good approach ?
And how to implement data versioning?
To write a DAO, typically you create an interface that defines the behavior of the DAO.
interface MyObjDao {
public int save(MyObj myObj);
public void delete (MyObj myObj);
// as many methods as you need for data acess
}
and then you create the actual implementation
class MyObjDaoImpl implements MyObjDao {
// implement methods here
}
The advantages of this are:
1) Because you define an interface, mocking DAOs is easy for any testing framework
2) The behavior is not tied to an implementation -- your DAOImpl could use jdbc, hibernate, whatever
Your Persistance class is really a base class for all entities -- i.e. all classes instances of which get saved, where you want to represent some common fields in one place. This is a good practice -- I wouldn't call the class Persistance, something like BaseEntity is better (IMHO). Be sure to have javadocs that explain the purpose of the class.
With respect to variable names, as long as they make sense and describe what they are for, its good.
so dateCreated or createdDate are both fine; they both get the idea across.
You are mixing a DAO (data access object) and a VO (value object) - also known as a DTO (data transfer object) - in the same class.
Example using an interface for DAO behavior (blammy and kpow might be webservice, oracle database, mysql database, hibernate, or anything meaningful):
public interface UserDTO
{
boolean deleteUser(String userId);
UserVO readUser(String userId);
void updateUser(String userId, UserVO newValues);
}
package blah.blammy;
public class UserDTOImpl implements UserDTO
{
... implement it based on blammy.
}
package blah.kpow;
public class UserDTOImpl implements UserDTO
{
... implement it based on kpow.
}
Example VO:
public class UserVO
{
String firstName;
String lastName;
String middleInitial;
... getters and setters.
}
I prefer to identify the target of the delete using an ID instead of a VO object. Also, it is possible that an update will change the target identified by user ID "smackdown" to have user ID "smackup", so I generally pass an id and a VO.
A good approach would be to use JPA with all of its features, this tutorial was really helpful.
It explains how to use the #PrePersist and #PreUpdate annotations for setting create and update timestamps. Optimistic locking is supported by the #Version annotation.
My questions are- what is the best way to write variable name, which
one is good, createdDate or dateCreated, deleted or isDeleted etc.
createdDate or dateCreated is very subjective. In databases, I have mostly seen createdDate though. Between deleted and isDeleted, I prefer (again subjective) deleted. I think the getter method can be named isDeleted().