Hibernate Books

All times are UTC - 5 hours [ DST ]



Post new topic Reply to topic  [ 6 posts ] 
Author Message
 Post subject: Cassandra Test Project
PostPosted: Thu Jul 23, 2015 5:02 am 
Newbie

Joined: Thu Jul 23, 2015 4:50 am
Posts: 3
Hello,

I have been using Hibernate for some time, and now i am researching and trying to create a java project that will be able to use Hibernate OGM with Cassandra (Datastax). Until now I have already created a fully working project with Kundera.

In detail I have followed the documentation but i keep getting the error message: javax.persistence.TransactionRequiredException: no transaction is in progress.

Has anyone came up with this problem before?

Furthermore has anyone created a fully working project that can connect to Cassandra? If yes it would be nice to share it with the community as a reference.

Keep up the good job!

Best Regards


Top
 Profile  
 
 Post subject: Re: Cassandra Test Project
PostPosted: Fri Jul 24, 2015 8:16 am 
Hibernate Team
Hibernate Team

Joined: Fri Sep 09, 2011 3:18 am
Posts: 294
Hi,
I don't think there is a shared example project for Cassandra at the moment.
If you can share the project with us or give us more details about it, we might be able to help.

This kind of feedback is very valuable for us, in particular with cassandra that it's one of the latest additions to OGM.

Cheers,
Davide


Top
 Profile  
 
 Post subject: Re: Cassandra Test Project
PostPosted: Fri Jul 24, 2015 9:14 am 
Hibernate Team
Hibernate Team

Joined: Sat Jan 24, 2009 12:46 pm
Posts: 386
Hi,

Hibernate OGM relies on the known Hibernate/JPA/JTA APIs for demarcating units of work, also on non-transactional datastores such as Cassandra. The error message you got indicates you did not open up a "transaction" in your code prior to e.g. persting objects via the Session/EntityManager. You may find this FAQ entry helpful: http://hibernate.org/ogm/faq/#how-does-hibernate-ogm-handle-transactions.

Regarding an example, you just could take the one from the "Getting Started" section in the reference guide (see http://docs.jboss.org/hibernate/ogm/4.2/reference/en-US/html_single/#ogm-gettingstarted). Just replace the dependency with the one to the hibernate-ogm-cassandra modules.

If you can share your specific piece of code causing the exception we also can try and help you fixing it.

Cheers,

--Gunnar

_________________
Visit my blog at http://musingsofaprogrammingaddict.blogspot.com/


Top
 Profile  
 
 Post subject: Re: Cassandra Test Project
PostPosted: Sun Jul 26, 2015 10:14 am 
Newbie

Joined: Thu Jul 23, 2015 4:50 am
Posts: 3
Hello,

Following you can find the code and configuration i am using for my cassandra test project:

Code:
package org.hibernate.ogm.examples.gettingstarted;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name = "orders", schema = "flexbridge@cassandra_pu")
public class SimpleOrder {

    @Id
    @Column(name = "unique_id")
    private String uniqueId;

    @Column(name="account")
    private String account;

    public SimpleOrder() {

    }

    public SimpleOrder(String uniqueId, String account) {
        this.uniqueId = uniqueId;
        this.account = account;
    }


    @Override
    public String toString() {
        StringBuilder b = new StringBuilder();
        b.append("Order {").append("\n");
        b.append("\t").append("Unique ID = ").append(uniqueId).append("\n");
        b.append("\t").append("Account = ").append(account).append("\n");
        b.append("}");
        return b.toString();
    }

}



Code:
package org.hibernate.ogm.examples.gettingstarted;

import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.jpa.HibernateEntityManagerFactory;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.TransactionManager;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class OrderTest {

   private static final String JBOSS_TM_CLASS_NAME = "com.arjuna.ats.jta.TransactionManager";

   public static void main(String[] args) {

      TransactionManager tm = getTransactionManager();

      //build the EntityManagerFactory as you would build in in Hibernate Core
      
      Map<String, String> propertyMap = new HashMap<String, String>();
        propertyMap.put("cql.version", "3.0.0");
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("cassandra_pu", propertyMap);

      //Persist entities the way you are used to in plain JPA
      try {
         tm.begin();
         
         final EntityManager em = emf.createEntityManager();
         
         String uniqueId = "unique-id-3";
           String account = "Account3";

           SimpleOrder order;

           order = new SimpleOrder(uniqueId, account);
          
           em.persist(order);
           tm.commit();
          
           em.clear();
          
           em.flush();
         
         em.close();
         
         emf.close();
         
      } catch ( Exception e ) {
         e.printStackTrace();
      }

   }

   
   private static TransactionManager extractJBossTransactionManager(EntityManagerFactory factory) {
       SessionFactoryImplementor sessionFactory =
           (SessionFactoryImplementor) ( (HibernateEntityManagerFactory) factory ).getSessionFactory();
       return sessionFactory.getServiceRegistry().getService( JtaPlatform.class ).retrieveTransactionManager();
   }
   
   public static TransactionManager getTransactionManager() {
      try {
         Class<?> tmClass = OrderTest.class.getClassLoader().loadClass( JBOSS_TM_CLASS_NAME );
         return (TransactionManager) tmClass.getMethod( "transactionManager" ).invoke( null );
      } catch ( ClassNotFoundException e ) {
         e.printStackTrace();
      } catch ( InvocationTargetException e ) {
         e.printStackTrace();
      } catch ( NoSuchMethodException e ) {
         e.printStackTrace();
      } catch ( IllegalAccessException e ) {
         e.printStackTrace();
      }
      return null;
   }
}



Code:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <persistence-unit name="cassandra_pu">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>     
        <properties>           
                 <property name="hibernate.ogm.datastore.provider" value="org.hibernate.ogm.datastore.cassandra.impl.CassandraDatastoreProvider"/>
                 <property name="hibernate.ogm.datastore.database" value="flexbridge"/>
                <property name="hibernate.ogm.cassandra.host" value="127.0.0.1"/>
                <property name="hibernate.ogm.cassandra.port" value="9160"/>
                <property name="hibernate.ogm.cassandra.database" value="odm_hibernate"/>
                 <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
        </properties>       
    </persistence-unit>
</persistence>





Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<!--
~ Hibernate OGM, Domain model persistence for NoSQL datastores
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
~
~
~ @author JBoss, a division of Red Hat.
  -->
<properties>
    <!--
    This is the JBossTS configuration file for running ArjunaJTA.
    It should be called jbossts-properties.xml.
    You need a different version for ArjunaCore or JTS usage.

    ***************************

    Property values may be literals or be tokens of the form ${p1[,p2][:v]}
    in which case the token values are substituted for the values of the corresponding system
    properties as follows:

    - Any occurance of ${p} with the System.getProperty(p) value.
    If there is no such property p defined, then the ${p} reference will remain unchanged.

    - If the property reference is of the form ${p:v} and there is no such property p,
    then the default value v will be returned.

    - If the property reference is of the form ${p1,p2} or ${p1,p2:v} then
    the primary and the secondary properties will be tried in turn, before
    returning either the unchanged input, or the default value.

    The property ${/} is replaced with System.getProperty("file.separator")
    value and the property ${:} is replaced with System.getProperty("path.separator").

    Note this substitution applies to property values only at the point they are read from
    the config file. Tokens in system properties won't be substituted.
    -->
   
    <!-- Disable to avoid creating temporary transaction logs on disk (default is YES) -->
    <entry key="CoordinatorEnvironmentBean.transactionStatusManagerEnable">NO</entry>

    <!-- (default is YES) -->
    <entry key="CoordinatorEnvironmentBean.commitOnePhase">YES</entry>

    <!-- default is under user.home - must be writeable!)
    <entry key="ObjectStoreEnvironmentBean.objectStoreDir">PutObjectStoreDirHere</entry> -->
   
    <!-- The VolatileStore won't be able to recover anything - use only for simple tests! -->
    <entry key="ObjectStoreEnvironmentBean.objectStoreType">com.arjuna.ats.internal.arjuna.objectstore.VolatileStore</entry>

    <!-- (default is ON) -->
    <entry key="ObjectStoreEnvironmentBean.transactionSync">ON</entry>

    <!-- (Must be unique across all Arjuna instances.) -->
    <entry key="CoreEnvironmentBean.nodeIdentifier">1</entry>

   <!-- Which Xid types to recover -->
   <entry key="JTAEnvironmentBean.xaRecoveryNodes">1</entry>

    <entry key="JTAEnvironmentBean.xaResourceOrphanFilterClassNames">
        com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter
        com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter
    </entry>

    <!--
      Base port number for determining a unique number to associate with an instance of the transaction service
      (which is needed in order to support multiple instances on the same machine).
      Use the value 0 to allow the system to select the first available port number.
      If the port number is non-zero and the port is in use then the value will be incremented until either a successful binding
      to the loopback address is created or until the the maximum number of ports (specified by the
      CoreEnvironmentBean.socketProcessIdMaxPorts property) have been tried or until the port number
      reaches the maximum possible port number.
    -->
    <entry key="CoreEnvironmentBean.socketProcessIdPort">0</entry>

    <!--
      Periodic recovery modules to use.  Invoked in the order they appear in the list.
         Check http://www.jboss.org/community/docs/DOC-10788 for more information
         on recovery modules and their configuration when running in various
         deployments.
    -->
    <entry key="RecoveryEnvironmentBean.recoveryModuleClassNames">
        com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule
        com.arjuna.ats.internal.txoj.recovery.TORecoveryModule
        com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule
    </entry>

    <!-- Expiry scanners to use (order of invocation is random). -->
    <entry key="RecoveryEnvironmentBean.expiryScannerClassNames">
        com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner
    </entry>

    <!--
        Add the following to the set of expiryScannerClassNames above to move logs that cannot be completed by failure recovery.
            But be sure you know what you are doing and why!
             com.arjuna.ats.internal.arjuna.recovery.AtomicActionExpiryScanner
    -->

    <!--
      The address and port number on which the recovery manager listens
      If running within an AS then the address the AS is bound to (jboss.bind.address) takes precedence
    -->
    <entry key="RecoveryEnvironmentBean.recoveryPort">4712</entry>

    <entry key="RecoveryEnvironmentBean.recoveryAddress">127.0.0.1</entry>

    <!--
      Use this to fix the port on which the TransactionStatusManager listens,
      The default behaviour is to use any free port.
    -->
    <entry key="RecoveryEnvironmentBean.transactionStatusManagerPort">0</entry>

    <!--
      Use this to fix the address on which the TransactionStatusManager binds,
      The default behaviour is to use the loopback address (ie localhost).
      If running within an AS then the address the AS is bound to (jboss.bind.address) takes precedence
    -->
    <entry key="RecoveryEnvironmentBean.transactionStatusManagerAddress">127.0.0.1</entry>

    <!--
      For cases where the recovery manager is in process with the transaction manager and nothing else uses
      the ObjectStore, it is possible to disable the socket based recovery listener by setting this to NO.
      Caution: use of this property can allow multiple recovery processes to run on the same ObjectStore
      if you are not careful. That in turn can lead to incorrect transaction processing. Use with care.
    -->
    <entry key="RecoveryEnvironmentBean.recoveryListener">NO</entry>

</properties>



I have added the required libraries manually by downloading the package, and adding any additional jar files that are necessary (this may be the reason it is not working as exptected)

The extra libraries i had to download and use are:

commons-logging-1.1.1.jar
concurrent-1.3.3.jar
guava-18.0.jar
jbossjta-4.2.2.GA.jar
jbossts-common-4.2.3-sp5-osgi.jar
jta-1.1.jar
log4j-1.2.17.jar
netty-3.2.10.Final.jar
slf4j-api-1.7.12.jar

Please let me know if you require anything else.

Thanks for the assistance,

Darksu


Top
 Profile  
 
 Post subject: Re: Cassandra Test Project
PostPosted: Tue Jul 28, 2015 3:04 am 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
I think that you forgot to set transaction-type="JTA" to your persistence unit

Code:
<persistence-unit name="cassandra_pu" transaction-type="JTA">

_________________
Emmanuel


Top
 Profile  
 
 Post subject: Re: Cassandra Test Project
PostPosted: Tue Jul 28, 2015 5:38 am 
Newbie

Joined: Thu Jul 23, 2015 4:50 am
Posts: 3
Hello emmanuel,

After your correct suggestion i updated my persistence.xml file as shown below:

Code:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <persistence-unit name="cassandra_pu" transaction-type="JTA">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>     
        <properties>           
                 <property name="hibernate.ogm.datastore.provider" value="org.hibernate.ogm.datastore.cassandra.impl.CassandraDatastoreProvider"/>
                 <property name="hibernate.ogm.datastore.database" value="flexbridge"/>
                <property name="hibernate.ogm.cassandra.host" value="127.0.0.1"/>
                <property name="hibernate.ogm.cassandra.port" value="9160"/>
                <property name="hibernate.ogm.cassandra.database" value="odm_hibernate"/>
                 <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
        </properties>       
    </persistence-unit>
</persistence>


The good thing is that i was able to insert a record in the database!

Now i am working on retrieving the data from the database but with no success until now (There are issues with the libraries that are required "Hibernate Search, etc")

So i will continue working on the project, and will post the updated version, but if anyone wants to contribute please be free to add it to this post.

Best Regards.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.