Google

Sep 25, 2013

Spring CrudRepository with JPA example

Step 1: Add the jar dependency to your maven pom.xml file.


..
<spring.data.version>1.2.0.RELEASE</spring.data.version>
...
<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-jpa</artifactId>
 <version>${spring.data.version}</version>


Step 2: Define the JPA entity -- that is your model class that maps to the table in the database.




package com.mydomain.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.annotations.Type;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Table(name = "ReportStructure")
public class Node extends AbstractPersistable<Long>
{
    
    private static final long serialVersionUID = 1L;
    
    @ManyToOne
    @JoinColumn(name = "ParentId", insertable = false, updatable = false)
    private Node parent;
    
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "ParentId", nullable = false)
    private List<Node> children = new ArrayList<Node>();
    
    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    private NodeAttributes attributes;
    
    @ManyToOne(cascade = CascadeType.ALL, optional = false)
    @JoinColumn(name = "KeyId")
    private NodeKey key;
    
    @Column(name = "InactiveFlag", nullable = false, length = 1)
    @Type(type = "yes_no")
    private boolean isSoftDeleted;
    
   
    public Node()
    {
        this(null);
    }
    
    public Node(Long id)
    {
        this.setId(id);
    }
    
    public List<Node> getChildren()
    {
        return children;
    }
    
    public Node getParent()
    {
        return parent;
    }
    
    public void setParent(Node parent)
    {
        this.parent = parent;
        if (parent != null)
        {
            parent.addChild(this);
        }
    }
    
    public void setChildren(List<Node> children)
    {
        this.children = children;
    }
    
    public void addChild(Node child)
    {
        if (child == null)
        {
            return;
        }
        if (!children.contains(child))
        {
            children.add(child);
            synchronized (this)
            {
                if (child.parent == null)
                {
                    child.setParent(this);
                }
            }
        }
    }
    
    public NodeKey getKey()
    {
        return key;
    }
    
    public void setKey(NodeKey key)
    {
        this.key = key;
    }
    
    public NodeAttributes getAttributes()
    {
        return attributes;
    }
    
    public void setAttributes(NodeAttributes attributes)
    {
        this.attributes = attributes;
        this.attributes.setNode(this);
    }
    
    public boolean isSoftDeleted()
    {
        return isSoftDeleted;
    }
    
    public void setSoftDeleted(boolean isSoftDeleted)
    {
        this.isSoftDeleted = isSoftDeleted;
    }
    
        
    @Override
    public int hashCode()
    {
        return new HashCodeBuilder().append(key).append(parent).append(attributes).toHashCode();
    }
    
    @Override
    public boolean equals(final Object obj)
    {
        if (obj instanceof Node)
        {
            final Node other = (Node) obj;
            return new EqualsBuilder().append(key, other.getKey()).append(parent, other.getParent())
                    .append(attributes, other.getAttributes()).isEquals();
        }
        return false;
    }
    
    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}


Step 3: Define the CRUD reposotory by extending Spring's  CrudRepository class. The CrudRepository gives you out of the box access to the following standard methods


  • delete(T entity) which deletes the entity given as a parameter.
  • findAll() which returns a list of entities.
  • findOne(ID id) which returns the entity using the id given a parameter as a search criteria.
  • save(T entity) which saves the entity given as a parameter.


You can provide additional custom methods as shown below,


package com.mydomain.model.impl

import com.mydomain.model.Node;
import com.mydomain.model.NodeKey;

import java.util.Date;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;


public interface NodeRepository extends CrudRepository<Node, Long>
{
    @Query("SELECT n from Node n JOIN n.key k WITH k.clientId = ?1 and k.evalDate = ?2 "
            + "WHERE n.parent is null and n.isSoftDeleted = false ")
    List<Node> find(String clientId, Date evalDate);
    
    @Query("SELECT n from Node n JOIN n.key k WITH k.clientId = :clientId and k.evalDate = :evalDate "
            + "WHERE n.attributes.code = :code and n.isSoftDeleted = false ")
    List<Node> find(@Param("clientId") String clientId, @Param("evalDate") Date evalDate,
            @Param("code") String code);
    
    @Query("SELECT key from NodeKey key where key.isSoftDeleted = false")
    List<NodeKey> findNodeKey();
    
    @Query("SELECT key from NodeKey key WHERE key.clientId = ?1 and key.isSoftDeleted = false")
    List<NodeKey> fetch(String clientId);  
}


Step 4: The Spring config file to wire up JPA. This example uses HSQL.

<!-- Directory to scan for repository classes -->
<jpa:repositories
   base-package="com.mydomain.model" />
 
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
  id="transactionManager">
  <property name="entityManagerFactory"
      ref="entityManagerFactory" />
  <property name="jpaDialect">
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
  </property>
</bean>
 
<bean id="entityManagerFactory"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
      <property name="generateDdl" value="true" />
      <property name="database" value="HSQL" />
    </bean>
  </property>
</bean>

Step 5: Use the NodeRepository for CRUD operations in the service layer.

public class ReportServiceImpl extends ReportService {
 
   @Autowired
   NodeRepository nodeRepository;
 
  ...
}

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home