Www.jroller

download Www.jroller

of 4

Transcript of Www.jroller

  • 8/12/2019 Www.jroller

    1/4

    23/10/13 www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao

    www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao 1/4

    All technology misc jsf maven hibernate spring

    Detached Criteria...| Main| Crank Generic DAO...

    About the author

    Rick Hightower is CTO of Mammatusand is an expert on Java and Cloud Computing. Rick is involved with Java EE and Spring Training and consulting in the

    San Francisco / Silicon Valley area , not to mention NoSQL, MongoDB training and consulting.

    CDI Implementations - Resin Candi- Seam Weld- Apache OpenWebBeans

    Tuesday April 24, 2007

    Using the JPA Generic DAO and Criteria DSL for JPA

    Using the JPA Generic DAO

    Introduction

    This document describes how to use Crank's JPA Generic DAO support. Now that a few people are using this. I thought it was time to do a quick write up. Seehttp://code.google.com/p/krank/for more details (view the Wiki).

    Features of JPA Generic DAO covered in this document

    JPA support for CRUD operations Create, Read, Update, Delete

    Support for defining no-code finder methods

    Support for Criteria API/DSL

    Support for easy to use finder methods

    Getting Started with JPAGeneric DAO

    The DAO support is based on the Spring JPA support . There is some talk on the Crank team for supporting similar features for non-Spring developers, but for now

    both of you will have to use Spring to use this DAO support.

    Everything that applies to `org.springframework.orm.jpa.support.JpaDaoSupport` also applies to Cranks DAO support (`org.crank.crud.GenericDaoJpa`) as it subclasses

    `JpaDaoSupport` fromSpring. Note that all of our DAO objects implement `org.crank.crud.GenericDao`.

    Steps to using Crank JPA DAO support

    1. Setup Spring environment

    2. Configure DAO object

    3. Start using the DAO

    Step 1 Setup Spring environment

    Here is how the example projects sets up the Spring environment:

    Main context

    Resource context

    See Spring JPA support for more details.

    Of course you will have to setup a persistence.xml file as well refer to JPAdocuments for how to setup a persistence.xml file. For this project, the persistence.xml file

    is as follows:

    /META-INF/persistence.xml

    org.hibernate.ejb.HibernatePersistence

    org.crank.crud.test.model.Employee

    http://www.thearcmind.com/confluence/display/ArcMindOutlines/JPA+QuickStart+Training+Course+Outlinehttp://www.springframework.org/docs/reference/orm.htmlhttp://www.thearcmind.com/confluence/display/ArcMindOutlines/JPA+QuickStart+Training+Course+Outlinehttp://www.caucho.com/http://seamframework.org/Weldhttp://openwebbeans.apache.org/1.1.0-SNAPSHOT/index.htmlhttp://java-ee-spring.mammatustech.com/http://www.jroller.com/RickHigh/entry/i_implemented_a_detached_criteriahttp://www.jroller.com/RickHigh/http://www.jroller.com/RickHigh/entry/crank_generic_dao_ready_forhttp://www.jroller.com/RickHigh/category/technologyhttp://www.jroller.com/RickHigh/category/mischttp://www.jroller.com/RickHigh/category/mavenhttp://www.jroller.com/RickHigh/category/hibernatehttp://www.jroller.com/RickHigh/category/springhttp://www.thearcmind.com/confluence/display/ArcMindOutlines/JPA+QuickStart+Training+Course+Outlinehttp://www.springframework.org/docs/reference/orm.htmlhttp://www.springframework.org/docs/reference/orm.htmlhttp://www.thearcmind.com/confluence/display/ArcMindOutlines/JPA+QuickStart+Training+Course+Outlinehttp://code.google.com/p/krank/http://www.jroller.com/RickHigh/date/20070424http://openwebbeans.apache.org/1.1.0-SNAPSHOT/index.htmlhttp://seamframework.org/Weldhttp://www.caucho.com/http://nosql.mammatustech.com/http://java-ee-spring.mammatustech.com/http://cloud.mammatustech.com/http://www.mammatustech.com/http://profiles.google.com/RichardHightower/abouthttp://www.jroller.com/RickHigh/entry/crank_generic_dao_ready_forhttp://www.jroller.com/RickHigh/http://www.jroller.com/RickHigh/entry/i_implemented_a_detached_criteriahttp://www.jroller.com/RickHigh/category/springhttp://www.jroller.com/RickHigh/category/hibernatehttp://www.jroller.com/RickHigh/category/mavenhttp://www.jroller.com/RickHigh/category/jsfhttp://www.jroller.com/RickHigh/category/mischttp://www.jroller.com/RickHigh/category/technology
  • 8/12/2019 Www.jroller

    2/4

    23/10/13 www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao

    www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao 2/4

    Step 2 Configure DAO object

    In order to use the DAO object, you must configure it. The DAO object needs to know which entity it is managing; thus, you need to pass it an Entity class as follows:

    DAO Beans context file

    Next inject the genericDao through a setter method as follows (using normal Spring injections):

    private GenericDao genericDao;

    public void setGenericDao( final GenericDao baseJpaDao ) {

    this.genericDao = baseJpaDao;

    }

    Notice that we define the genericDao as a DAO that works with Employees who have a PK that is a Long.

    Step 3 Start using the DAO

    Once you have the DAO defined and injected, you can start using it.

    You can read objects by id:

    Employee employee = (Employee) genericDao.read( 1L );

    You can create new objects:

    genericDao.create(new Employee("Rick", "Hightower"));

    You can update objects (not needed if in same transaction):

    Employee employee = (Employee) genericDao.read( 1L );

    ... //Present to user

    employee.setFirstName("Rick");

    genericDao.update( employee );

    JPAdoes dirty checking so the update is not needed if run in the same transaction.

    You can also delete objects as follows:

    You can delete an object as well:

    Employee employee = (Employee) genericDao.read( 1L );

    genericDao.delete( employee.getId() );

    There are helper methods for finding objects as follows:

    Map params = new HashMap();

    params.put("firstName", "Rick");

    List employees = genericDao.find( params, new String[] { "firstName" });

    The above finds and employee with the first name of Rick. If there are more than one employees named Rick, the list will be ordered by firstName.

    You can also search by related objects. Below we search for employees who are in the department named Engineering (where Employee has an related entity called

    Department).

    List employees = genericDao.find("department.name", "Engineering");

    The above is shorthand for the following:

    import static org.crank.crud.criteria.Example.*;

    import static org.crank.crud.criteria.Comparison.*;

    import static org.crank.crud.criteria.Group.*;

    ...

    ...

    List employees = genericDao.find(eq("department.name", "Engineering"));

    http://www.thearcmind.com/confluence/display/ArcMindOutlines/JPA+QuickStart+Training+Course+Outline
  • 8/12/2019 Www.jroller

    3/4

    23/10/13 www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao

    www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao 3/4

    Notice the use of the `eq` method. We provided a Criteria DSL where you can any number of criterion.

    Here are some examples of using the Criteria DSL

    employees = genericDao.find(

    eq("department.name", "Engineering"),

    or( startsLike("firstName", "Rick"),like("firstName", "Ri"))

    );

    employees = genericDao.find(

    or (

    eq("department.name", "Engineering"),

    like("firstName", "Ri")

    )

    );

    employees = genericDao.find( in("age", 1, 2, 3, 4, 5, 6, 40) );

    The Criteria DSL has all of the operators that you expect, e.g., and, or, eq, ne, gt, ge, etc.

    The Criteria DSL even has support for Query by Example (QBE):

    Employee employee = new Employee();

    employee.setActive(true);

    employee.setAge(40);

    employee.setFirstName("Rick");

    employee.setLastName("Rick");

    List employees = genericDao.find(

    like(employee).excludeProperty("lastName"));

    You can even refer to nested QBE objects:

    employee = new Employee();

    employee.setFirstName("Ric");

    employee.setAge(0);

    employee.setActive(true);

    Department department = new Department();

    department.setName("Eng");

    employee.setDepartment(department);

    employees = genericDao.find(like(employee));

    See that the above uses an Employee that has a Department. Both the Employee data and the Department data will be used in the geneated query.

    Using DAO methods to Named Queries mapping

    In addition to using the API provided you can extend the API with your own custom Named Queries.

    To this you need to:

    1. Define an interface with finder methods that start with "find"2. Define named queries that match the name of your finder methods

    3. Use the DaoFactory to configure a Generic DAO

    4. Use the new finder methods

    Define an interface with finder methods that start with "find"

    package org.crank.crud.test.dao;

    import java.util.List;

    import org.crank.crud.GenericDao;

    import org.crank.crud.test.model.Employee;

    public interface EmployeeDAO extends GenericDao{

    List findEmployeesByDepartment(String deptName);

    }

    Notice that this interface extends GenericDao.

    Define named queries that match the name of your finder methods

    package org.crank.crud.test.model;

    import javax.persistence.Entity;

    import javax.persistence.GeneratedValue;

    import javax.persistence.GenerationType;

    import javax.persistence.Id;

    import javax.persistence.ManyToOne;

    import javax.persistence.NamedQueries;

    import javax.persistence.NamedQuery;

    @Entity

    @NamedQueries( {

    @NamedQuery(name="Employee.findEmployeesByDepartment", query="from Employee employee where employee.department.name=?"

    })

    public class Employee {

    @Id

    @GeneratedValue( strategy = GenerationType.AUTO )

    private Long id;

  • 8/12/2019 Www.jroller

    4/4

    23/10/13 www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao

    www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao 4/4

    ...

    Notice the name of the named query is findEmployeesByDepartment and this matches the name in the EmployeeDAO interface.

    Use the DaoFactory to configure a Generic DAO

    org.crank.crud.test.dao.EmployeeDAO

    org.crank.crud.test.model.Employee

    Notice that the daoFactory only has to be defined once per project while the genericDao is defined per DAO object (per entity) (perhaps a better name for this example

    would be employeeDao instead of genericDao).

    Use the new finder methods

    EmployeeDAO employeeDAO = (EmployeeDAO) this.genericDao;

    List employees = employeeDAO.findEmployeesByDepartment("Engineering");

    The first one may be somewhat difficult to setup, but your next finder method is a mere matter of adding it to the DAO interface and then creating the named query.

    see http://code.google.com/p/krank/for more details.

    Posted at 03:22PM Apr 24, 2007by Rick Hightower in technology | Comments[2]

    Comments:

    I love using th is dao approach. The simplicity is just awesome. When I wanna cr eate a new dao I simply cr eate an interfac e, and spring config...t hat 's it. No mad

    repetition of classes and meth ods happening. A dding a new m ethod is as simple as adding a n amed query annotat ion, and a meth od with a prefix of "find" to the

    interface. Poof. I'm done. New m ethod. This approach is a beau tiful adoption of DRY. I can't wait to play with the cr iteria a pi piece. Thanks Rick!

    Posted by Chris Math iason April 25, 2 007 a t 12 :27 PM MST

    Can't use search fu nctionality on your blog, it's broken.

    Posted by Chandana on A pri l 2 7, 2 007 at 09:57 A M MST

    Home Sunsets Theme by Matt RaibleAbout the author

    Rick Hightoweris CTO of Mammatusand is an expert on Java and Cloud Computing. Rick is invovled in Java CDI advocacy and Java EE.

    CDI Implementations - Resin Candi- Seam Weld- Apache OpenWebBeans, Java EE Tutorial, Servlet Tutorial Part 1, Servlet Tutorial Part 2, JSP Tutorial

    http://wiki4.caucho.com/Java_EE_Servlet_tutorial_:_Using_JSPs_to_create_header,_footer_area,_formatting,_and_basic_CSS_for_bookstorehttp://wiki4.caucho.com/Java_EE_Servlet_tutorial_:_Adding_create,_update_and_delete_to_the_bookstore_listinghttp://wiki4.caucho.com/Building_a_simple_listing_in_JSPhttp://wiki4.caucho.com/Java_EE_Tutorial_covering_JSP_2.2,_and_Servlets_3.0http://openwebbeans.apache.org/1.1.0-SNAPSHOT/index.htmlhttp://seamframework.org/Weldhttp://www.caucho.com/resin-application-server/java-cdi-java-ee-candi/http://cloud.mammatustech.com/http://www.mammatustech.com/http://profiles.google.com/RichardHightower/abouthttp://raibledesigns.com/http://www.jroller.com/RickHigh/http://jroller.com/page/chrismhttp://www.jroller.com/RickHigh/entry/using_the_jpa_generic_dao#commentshttp://www.jroller.com/RickHigh/entry/using_the_jpa_generic_daohttp://code.google.com/p/krank/