Skip to main content

Easy-Cassandra 1.0.9: With annotations jpa and JPQL

Posted by otaviojava on April 21, 2012 at 11:02 AM PDT

Release the newest version of the framework to persist objects in Apache Cassandra in easy way. Among improvement is the JPA annotations, also JPQL.

  JCassandra jCassandra=persistence.createJCassandra("select * from Person");
 List persons=jCassandra.getResultList();

table 1: sample using JPQL in Easy-Cassandra



Easy-Cassandra 1.0.8
Easy-Cassandra 1.0.9 (Com JPA anotação)
org.easycassandra.annotations.ColumnFamilyValue

javax.persistence.Entity
org.easycassandra.annotations.ColumnValue
javax.persistence.Column
org.easycassandra.annotations.EmbeddedValue
javax.persistence.Embedded
org.easycassandra.annotations.EnumeratedValue
javax.persistence.Enumerated
org.easycassandra.annotations.KeyValue
javax.persistence.Id
org.easycassandra.annotations.KeyValue equals
true
javax.persistence.GeneratedValue
org.easycassandra.annotations.IndexValue
org.easycassandra.annotations.Index

Also was added functionality for the @Version annotation, its objective is see the timestamp common between fields in objects.

@Entity(name = "autocount")

public class Count implements Serializable {



    private static final long serialVersionUID = 3L;

    

    @Id

    @GeneratedValue

    private BigInteger id;

    

  

    @Column(name = "name")

    private String name;

    

    @Version

    private Long timeStampLong;



    @Version

    private Date timeStampDate;

    

    @Version

    private Calendar timeStampCalendar;



//getter and setter

}

table 3: using the Version annotation

For show the new resources for framework will do an example with musical albuns that can call for any platform, this way, will use web services. For do this sample will use the Java EE 6 platform. After object modeling like show table 4.

@XmlRootElement
@Entity
public class Album implements Serializable{
   
    @Id
    private Long id;
   
    @Column(name="nameOfAlbum")
    private String name;
   
    @Column 
    private String style;
   
    @Column
    private Calendar release;
   
    @Column
    private Double price;
   
    @Embedded
    private Artist artist;
//getter and setter
    }
@XmlRootElement
public class Artist implements  Serializable{

    /**
     * name of the artist
     */
    @Column(name="nameOfArtist")
    private String name;
   
    /**
     * was born
     */
    @Column
    private String country;
   
    @Enumerated
    private Sex sex;
//getter and setter
}

@XmlRootElement
public enum Sex {
    MALE,FAMALE
}

table 4: class with jpa annotations for Easy-Cassandra

With the class done, now will do the JPQL the Jcassandra's interface extended javax.persistence.Query, so you may use the Query interface if you wat. But there are some method not implement yet.
Other thing important is the way how the Easy-Cassandra manager the classes. It no use xml. To manage use the method addFamilyObject in the EasyCassandraManager Class. You should add the Class before use in the jpql.

@ApplicationScoped
public class PersistenceManagement {
   
   @Produces
   private Persistence persistence;
     
  @Inject
    public void init(){
    persistence=EasyCassandraManager.getPersistence("javabahia", "localhost", 9160);
   
    EasyCassandraManager.addFamilyObject(Album.class);
    }    
}



@RequestScoped
public class PersistenceService {

@Inject   
private Persistence persistence;
  
    public List findAllAlbum() {
        Query query=persistence.createJCassandra(" select * from Album");
        return query.getResultList();
    }

    public Album findById(Long id) {
        Query query=persistence.createJCassandra(" select * from Album where id =:id");
        query.setParameter("id", id);
        return (Album) query.getSingleResult();
       
    }

    public boolean save(Album album) {
      return  persistence.insert(album);
    }

    public void remove(Long id) {
        persistence.deleteByKeyValue(id, Album.class);
    }

    public String update(Long id, String name, String style, Double price,String nameOfArtis,String country) {
       StringBuilder query=new StringBuilder();
     AuxQuery auxQuery=new AuxQuery();
       String conecion="";
       query.append("update Album set ");
       if(!isnull(name)){
           query.append(conecion);
           query.append(" name =:name ");
           auxQuery.updatable=true;
           conecion=" , ";
       }
       if(!isnull(style)){
       query.append(conecion);
           query.append(" style =:style ");
           auxQuery.updatable=true;
           conecion=" , ";
       }
       if(!isnull(price)){
           query.append(conecion);
           query.append(" price =:price ");
           auxQuery.updatable=true;
       }
      
         if(!isnull(country)){
       query.append(conecion);
           query.append(" artist.country =:country ");
           auxQuery.updatable=true;
           conecion=" , ";
       }
       if(!isnull(nameOfArtis)){
           query.append(conecion);
           query.append(" artist.name =:artist ");
           auxQuery.updatable=true;
       }
      
       query.append(" where id =:id ");
    
       if(!auxQuery.updatable){
            return "nothing is update";
       }
      
       Query jCassandra=persistence.createJCassandra(query.toString());
      
          if(!isnull(name)){
          jCassandra.setParameter("name", name);
       }
       if(!isnull(style)){
   
        jCassandra.setParameter("style", style);
       }
       if(!isnull(price)){
         jCassandra.setParameter("price", price);
       }
       if(!isnull(nameOfArtis)){
     
        jCassandra.setParameter("artist", nameOfArtis);
       }
       if(!isnull(country)){
         jCassandra.setParameter("country", country);
       }
     
       jCassandra.setParameter("id", id);
       return jCassandra.executeUpdate()==1?"executed with sucess":" error in update ";
    
    }
  
    class AuxQuery{
      boolean updatable=false;
   
    }
   
    private boolean isnull(Object object){
   
        return object==null;
    }
   
}

table 5: do jpql in Cassandra

Then, now will create the resource for restful's service like show the table 6.

@Path("/album")
@RequestScoped
public class AlbumResource {
  
    
@Inject   
private PersistenceService persistenceService;


@GET
@Produces(MediaType.TEXT_XML)
public List getProdutos() {
return persistenceService.findAllAlbum();
}

@Path("{id}")
@GET
@javax.ws.rs.Produces(MediaType.TEXT_XML)
public Album getAlbum(@PathParam("id") long id) {
    return persistenceService.findById(id);
}

@Path("update/{id}")
@GET
@javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
public String updateAlbum(@PathParam("id") Long id ,@QueryParam("name") String name,@QueryParam("style") String style,@QueryParam("price") Double price,@QueryParam("artist") String nameOfArtis,@QueryParam("country") String country) {

    return persistenceService.update(id,name,style,price,nameOfArtis,country);
}
   
   
@POST
@Consumes(MediaType.TEXT_XML)
@Produces(MediaType.TEXT_PLAIN)
public String addAlbum(Album album) {
    boolean sucess=persistenceService.save(album);
    if(sucess){
    return album.getName() + " added!";
    }
   return album.getName() + " not added!";
}



@Path("{id}")
@DELETE
@Produces(MediaType.TEXT_PLAIN)
public String removeAlbum(@PathParam("id") Long id) {
    persistenceService.remove(id);
    return "Album removed.";
}
   

}
table 6: create rest service with JAX-RS

One way for test is using the poster, a plugin for firefox. With this plugin you able do test in all resources (post, get and remove), but just with browser you able test get methods.


list of album
Object album with id equals 1
Object album with id equals N
Insert or update an album wit id equals 12, with name equals Brasil, style eletronic, price 23 and artist me

table 7: sample with rest services.

With this has showed the improvements in new Easy-Cassandra version, the 1.0.9. Was showed the change with annotations, replacement now to jpa, and the jpql improvement that now supported in Easy-Cassandra.

Reference:
Sample rest service rest (AlbumServerRest.rar): https://github.com/otaviojava/Easy-Cassandra/downloads

Poster Plugin Firefox: https://addons.mozilla.org/en-US/firefox/addon/poster/
Easy-Cassandra: https://github.com/otaviojava/Easy-Cassandra/
Download for source and documentation to version 1.0.9 ( documento 03): https://github.com/otaviojava/Easy-Cassandra/downloads