by BehindJava

How to generate DAO(data access object) using spring roo

Home » interview » How to generate DAO(data access object) using spring roo

In this blog, we are going to learn about generating the DAO’s (data access object) using spring roo.

Spring Roo

  • A Rapid Application Development (RAD) tool called Spring Roo is designed to produce quick, immediate results for Spring web apps and newer Spring technologies. With a few few commands, it enables us to build boilerplate code and project structures for Spring applications.
  • You can launch Roo from the operating system command line as a standalone application. We may write code using any text editor instead of having to use Eclipse, Spring Tool Suite (STS), or any other IDE!
  • To keep things simple, though, we’ll employ STS IDE and the Roo Extension.
  • Also, refer to the Spring Roo official Documentation.

Lets take an example, Where you have a User class with fields username, password and you need to create abstraction layers.
Entity -> Repository (DAO) -> Service
as
User-> UserRepository -> UserService

There are basically 2 ways of doing things - first one with JPA Repository and second one with Mongo Repository, apart from default ActiveRecord style. Setting up with Mongo or JPA is similar. I am explaining commands for JPA Repository here.

  1. execute setup command.

    jpa setup --provider HIBERNATE --database HYPERSONIC_PERSISTENT
  2. define new User entity setting default activeRecord to false (important).

    entity --class ~.domain.User --activeRecord false
  3. define fields for this User entity.

    field string --fieldName userName --notNull --sizeMin 3 --class ~.domain.User
    field string --fieldName password --notNull --sizeMin 3 --class ~.domain.User
  4. Create a new JPA repository interface using repository jpa command, which is equivalent to creating new repository interface by extending the spring data JpaRepository class public interface UserRepository extends JpaRepository<User, Long> {/Code/}. This provides all the CRUD functionalities and you don’t need to add anything. You can add other searching functionalities. Repository interface is similar to DAO interface. DAO is more tightly coupled with the persistence entities while Repository is more related to the domain objects.

    repository jpa --interface ~.repository.UserRepository --entity ~.domain.User
  5. Now add Service layer, where you can add all the business logic to your application. This step will create UserService interface and UserServiceImpl classes.

    service --interface ~.service.UserService --entity ~.domain.User

    The layering setup is finished. You can now create web layer and execute your code.

    web mvc setup
    web mvc all --package ~.web