Hibernate OGM Neo4j Tutorial

hibernate ogm named queries and hibernate ogm mongodb native query and hibernate ogm neo4j server and hibernate-ogm-neo4j maven dependency
OliviaCutts Profile Pic
OliviaCutts,France,Teacher
Published Date:01-08-2017
Your Website URL(Optional)
Comment
Hibernate OGM Reference Guide 4.0.0.Beta4 by Emmanuel Bernard (Red Hat) and Sanne Grinovero (Red Hat)Preface Hibernate Object/Grid Mapper (OGM) is a persistence engine providing Java Persistence (JPA) support for NoSQL datastores. It reuses Hibernate ORM’s object life cycle management and (de)hydration engine but persists entities into a NoSQL store (key/value, document, column- oriented, etc) instead of a relational database. It reuses the Java Persistence Query Language (JP-QL) as an interface to querying stored data. The project is still very young and very ambitious at the same time. Many things are on the roadmap (more NoSQL, query, denormalization engine, etc). If you wish to help, please check Chapter 1, How to get help and contribute on Hibernate OGM. Hibernate OGM is released under the LGPL open source license. Warning This documentation and this project are work in progress. Please give us feedback on • what you like • what you don’t like • what is confusing Check Section 1.2, “How to contribute” on how to contact us. 1. Goals Hibernate OGM: • offers a familiar programming paradigm to deal with NoSQL stores • moves model denormalization from a manual imperative work to a declarative approach handled by the engine • encourages new data usage patterns and NoSQL exploration in more "traditional" enterprises • helps scale existing applications with a NoSQL front end to a traditional database NoSQL can be very disconcerting as it is composed of many disparate solutions with different benefits and drawbacks. Speaking only of the main ones, NoSQL is at least categorized in four families: • graph oriented databases vPreface • key/value stores: essentially Maps but with different behaviors and ideas behind various products (data grids, persistent with strong or eventual consistency, etc) • document based datastores: contains as value semi-structured documents (think JSON) • column based datastores Figure 1. Various NoSQL families Each have different benefits and drawbacks and one solution might fit a use case better than an other. However access patterns and APIs are different from one product to the other. Hibernate OGM is not expected to be the Rosetta stone used to interact with all NoSQL solution in all use cases. But for people modeling their data as a domain model, it provides distinctive advantages over raw APIs and has the benefit of providing an API and semantic known to Java developers. Reusing the same programmatic model and trying different (No)SQL engines will hopefully help people to explore alternative datastores. Hibernate OGM also aims at helping people scale traditional relational databases by providing a NoSQL front-end and keeping the same JPA APIs and domain model. 2. What we have today Today, Hibernate OGM does not support all of these goals. Here is a list of what we have: viUse cases • store data in key/value stores (Infinispan’s datagrid and Ehcache) • store data in document stores (MongoDB) • Create, Read, Update and Delete operations (CRUD) for entities • polymorphic entities (support for superclasses, subclasses etc). • embeddable objects (aka components) • support for basic types (numbers, String, URL, Date, enums, etc) • support for associations • support for collections (Set, List, Map, etc) • support for Hibernate Search’s full-text queries • JPA and native Hibernate ORM API support 3. Use cases Here are a few areas where Hibernate OGM can be beneficial: • need to scale your data store up and down rapidly (via the underlying NoSQL datastore capability) • keep your domain model independent of the underlying datastore technology (RDBMS, Infinispan, NoSQL) • explore the best tool for the use case while using a familiar programming model • use a familiar JPA front end to datagrids (in particular Infinispan) • use Hibernate Search full-text search / text analysis capabilities and store the data set in an elastic grid These are a few ideas and the list will grow as we add more capabilities to Hibernate OGM. viiChapter 1. How to get help and contribute on Hibernate OGM Hibernate OGM is a young project. The code, the direction and the documentation are all in flux and being built by the community. Join and help us shape it 1.1. How to get help First of all, make sure to read this reference documentation. This is the most comprehensive formal source of information. Of course, it is not perfect: feel free to come and ask for help, comment or propose improvements in our Hibernate OGM forum https://forum.hibernate.org/viewforum.php? f=31. You can also: • open bug reports in JIRA https://hibernate.atlassian.net/browse/OGM • propose improvements on the development mailing list http://www.hibernate.org/community/ mailinglists • join us on IRC to discuss developments and improvements (hibernate-dev on freenode.net; you need to be registered on freenode: the room does not accept "anonymous" users). 1.2. How to contribute Welcome There are many ways to contribute: • report bugs in JIRA https://hibernate.atlassian.net/browse/OGM • give feedback in the forum, IRC or the development mailing list • improve the documentation • fix bugs or contribute new features • propose and code a datastore dialect for your favorite NoSQL engine Hibernate OGM’s code is available on GitHub at https://github.com/hibernate/hibernate-ogm. 1.2.1. How to build Hibernate OGM Hibernate OGM uses Git and Maven 3, make sure to have both installed on your system. 1Chapter 1. How to get help an... Clone the git repository from GitHub: get the sources git clone https://github.com/hibernate/hibernate-ogm cd hibernate-ogm Run maven build project mvn clean install -s settings-example.xml Note Note that Hibernate OGM uses artifacts from the Maven repository hosted by JBoss. Make sure to either use the -s settings-example.xml option or adjust your /.m2/settings.xml according to the descriptions available on this jboss.org wiki page http://community.jboss.org/wiki/MavenGettingStarted-Users. To build the documentation, set the buildDocs property to true: mvn clean install -DbuildDocs=true -s settings-example.xml Tip If you just want to build the documentation only, run it from the hibernate-ogm- documentation/manual subdirectory. 1.2.2. How to contribute code effectively The best way to share code is to fork the Hibernate OGM repository on GitHub, create a branch and open a pull request when you are ready. Make sure to rebase your pull request on the latest version of the master branch before offering it. Here are a couple of approaches the team follows: • We do small independent commits for each code change. In particular, we do not mix stylistic code changes (import, typos, etc) and new features in the same commit. • Commit messages follow this convention: the JIRA issue number, a short commit summary, an empty line, a longer description if needed. Make sure to limit line length to 80 characters, even at this day and age it makes for more readable commit comments. OGM-123 Summary of commit operation 2How to contribute code effectively Optional details on the commit and a longer description can be added here. • A pull request can contain several commits but should be self contained: include the implementation, its unit tests, its documentation and javadoc changes if needed. • All commits are proposed via pull requests and reviewed by another member of the team before being pushed to the reference repository. That’s right, we never commit directly upstream without code review. 3Chapter 2. Getting started with Hibernate OGM If you are familiar with JPA, you are almost good to go :-) We will nevertheless walk you through the first few steps of persisting and retrieving an entity using Hibernate OGM. Before we can start, make sure you have the following tools configured: • Java JDK 6 or above • Maven 3.x Hibernate OGM is published in the JBoss hosted Maven repository. Adjust your /.m2/ settings.xml file according to the guidelines found on this webpage http://community.jboss.org/ wiki/MavenGettingStarted-Users. In this example we will use Infinispan as the targeted datastore. Add org.hibernate.ogm:hibernate-ogm-infinispan:4.0.0.Beta4 to your project dependencies. dependency groupIdorg.hibernate.ogm/groupId artifactIdhibernate-ogm-infinispan/artifactId version4.0.0.Beta4/version /dependency dependency groupIdorg.hibernate.javax.persistence/groupId artifactIdhibernate-jpa-2.0-api/artifactId version1.0.1.Final/version /dependency Note While Hibernate OGM depends on JPA 2.0, it is marked as provided in the Maven POM file. If you run outside a Java EE container, make sure to explicitly add the dependency. We will use the JPA APIs in this tutorial. Let’s now map our first Hibernate OGM entity. Entity public class Dog Id GeneratedValue(strategy = GenerationType.TABLE, generator = "dog") TableGenerator( name = "dog", table = "sequences", pkColumnName = "key", pkColumnValue = "dog", valueColumnName = "seed" 5Chapter 2. Getting started wi... ) public Long getId() return id; public void setId(Long id) this.id = id; private Long id; public String getName() return name; public void setName(String name) this.name = name; private String name; ManyToOne public Breed getBreed() return breed; public void setBreed(Breed breed) this.breed = breed; private Breed breed; Entity public class Breed Id GeneratedValue(generator = "uuid") GenericGenerator(name="uuid", strategy="uuid2") public String getId() return id; public void setId(String id) this.id = id; private String id; public String getName() return name; public void setName(String name) this.name = name; private String name; I lied to you, we have already mapped two entities If you are familiar with JPA, you can see that there is nothing specific to Hibernate OGM in our mapping. In this tutorial, we will use JBoss Transactions for our JTA transaction manager. The final list of dependencies should look like this: dependencies Hibernate OGM dependency dependency groupIdorg.hibernate.ogm/groupId artifactIdhibernate-ogm-core/artifactId version4.0.0.Beta4/version /dependency standard APIs dependencies - provided in a Java EE container dependency groupIdorg.hibernate.javax.persistence/groupId artifactIdhibernate-jpa-2.0-api/artifactId version1.0.1.Final/version /dependency dependency groupIdorg.jboss.spec.javax.transaction/groupId artifactIdjboss-transaction-api_1.1_spec/artifactId version1.0.0.Final/version scopeprovided/scope /dependency 6 JBoss Transactions dependency dependency groupIdorg.jboss.jbossts/groupId artifactIdjbossjta/artifactId version4.16.4.Final/version /dependency /dependencies Next we need to define the persistence unit. Create a META-INF/persistence.xml file. ?xml version="1.0"? 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="ogm-jpa-tutorial" transaction-type="JTA" Use Hibernate OGM provider: configuration will be transparent providerorg.hibernate.ogm.jpa.HibernateOgmPersistence/provider properties property optional if you plan and use Infinispan, otherwise adjust to your favorite NoSQL Datastore provider. property name="hibernate.ogm.datastore.provider" value="org.hibernate.ogm.datastore.infinispan.impl.InfinispanDatastoreProvider"/ defines which JTA Transaction we plan to use property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/ /properties /persistence-unit /persistence Let’s now persist a set of entities and retrieve them. //accessing JBoss's Transaction can be done differently but this one works nicely TransactionManager tm = getTransactionManager(); //build the EntityManagerFactory as you would build in in Hibernate ORM EntityManagerFactory emf = Persistence.createEntityManagerFactory( "ogm-jpa-tutorial"); final Logger logger = LoggerFactory.getLogger(DogBreedRunner.class); .. //Persist entities the way you are used to in plain JPA tm.begin(); logger.infof("About to store dog and breed"); EntityManager em = emf.createEntityManager(); Breed collie = new Breed(); collie.setName("Collie"); 7Chapter 2. Getting started wi... em.persist(collie); Dog dina = new Dog(); dina.setName("Dina"); dina.setBreed(collie); em.persist(dina); Long dinaId = dina.getId(); em.flush(); em.close(); tm.commit(); .. //Retrieve your entities the way you are used to in plain JPA tm.begin(); logger.infof("About to retrieve dog and breed"); em = emf.createEntityManager(); dina = em.find(Dog.class, dinaId); logger.infof("Found dog %s of breed %s", dina.getName(), dina.getBreed().getName()); em.flush(); em.close(); tm.commit(); .. emf.close(); public static TransactionManager getTransactionManager() throws Exception Class? tmClass = Main.class.getClassLoader().loadClass(JBOSS_TM_CLASS_NAME); return (TransactionManager) tmClass.getMethod("transactionManager").invoke(null); Note Some JVM do not handle mixed IPv4/IPv6 stacks properly (older Mac OS X JDK in particular http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7144274), if you experience trouble starting the Infinispan cluster, pass the following property: -Djava.net.preferIPv4Stack=true to your JVM or upgrade to a recent JDK version. jdk7u6 (b22) is known to work on Max OS X. A working example can be found in Hibernate OGM’s distribution under hibernate-ogm- documentation/examples/gettingstarted. What have we seen? • Hibernate OGM is a JPA implementation and is used as such both for mapping and in API usage • It is configured as a specific JPA provider: org.hibernate.ogm.jpa.HibernateOgmPersistence Let’s explore more in the next chapters. 8Chapter 3. Architecture Note Hibernate OGM defines an abstraction layer represented by DatastoreProvider and GridDialect to separate the OGM engine from the datastores interaction. It has successfully abstracted various key/value stores and MongoDB. We are working on testing it on other NoSQL families. In this chapter we will will explore: • the general architecture • how the data is persisted in the NoSQL datastore • how we support JP-QL queries Let’s start with the general architecture. 3.1. General architecture Hibernate OGM is really made possible by the reuse of a few key components: • Hibernate ORM for JPA support • Hibernate Search for indexing and query purposes • the NoSQL drivers to interact with the underlying datastore • Infinispan’s Lucene Directory to store indexes in Infinispan itself, or in many other NoSQL using Infinispan’s write-through cachestores • Hibernate OGM itself 9Chapter 3. Architecture Figure 3.1. General architecture Hibernate OGM reuses as much as possible from the Hibernate ORM infrastructure. There is no need to rewrite an entirely new JPA engine. The Persisters and the Loaders (two interfaces used by Hibernate ORM) have been rewritten to persist data in the NoSQL store. These implementations are the core of Hibernate OGM. We will see in Section 3.2, “How is data persisted” how the data is structured. 10How is data persisted The particularities between NoSQL stores are abstracted by the notion of a DatastoreProvider and a GridDialect. • DatastoreProvider abstracts how to start and maintain a connection between Hibernate OGM and the datastore. • GridDialect abstracts how data itself including association is persisted. Think of them as the JDBC layer for our NoSQL stores. Other than these, all the Create/Read/Update/Delete (CRUD) operations are implemented by the Hibernate ORM engine (object hydration and dehydration, cascading, lifecycle etc). As of today, we have implemented four datastore providers: • a Map based datastore provider (for testing) • an Infinispan based datastore provider to persist your entities in Infinispan • a Ehcache based datastore provider to persist your entities in Ehcache • a MongoDB based datastore provider to persist data in a MongoDB database To implement JP-QL queries, Hibernate OGM parses the JP-QL string and calls the appropriate translator functions to build a native query. If the query is too complex for the native capabilities of the NoSQL store, the Teiid query engine is used as an intermediary engine to implement the missing features (typically joins between entities, aggregation). Finally, if the underlying engine does not have any query support, we use Hibernate Search as an external query engine. Reality is a bit more nuanced, we will discuss the subject of querying in more details in Section 3.3, “How is data queried”. Hibernate OGM best works in a JTA environment. The easiest solution is to deploy it on a Java EE container. Alternatively, you can use a standalone JTA TransactionManager . We explain how to in Section 4.2.2, “In a standalone JTA environment”. Let’s now see how and in which structure data is persisted in the NoSQL data store. 3.2. How is data persisted Hibernate OGM tries to reuse as much as possible the relational model concepts, at least when they are practical and make sense in OGM’s case. For very good reasons, the relational model brought peace in the database landscape over 30 years ago. In particular, Hibernate OGM inherits the following traits: • abstraction between the application object model and the persistent data model • persist data as basic types • keep the notion of primary key to address an entity 11Chapter 3. Architecture • keep the notion of foreign key to link two entities (not enforced) If the application data model is too tightly coupled with your persistent data model, a few issues arise including: • any change in the application object hierarchy / composition must be reflected in the persistent data • any change in the application object model will require a migration at the data level • any access to the data by another application ties both applications losing flexibility • any access to the data from another platform become somewhat more challenging • serializing entities leads to many additional problems (see note below) Why aren’t entities serialized in the key/value entry There are a couple of reasons why serializing the entity directly in the datastore can lead to problems: • When entities are pointing to other entities are you storing the whole graph? Hint: this can be quite big • If doing so, how do you guarantee object identity or even consistency amongst duplicated objects? It might make sense to store the same object graph from different root objects. • What happens in case of class schema change? If you add or remove a property or include a superclass, you must migrate all entities in your datastore to avoid deserialization issues. Entities are stored as tuples of values by Hibernate OGM. More specifically, each entity is conceptually represented by a MapString,Object where the key represents the column name (often the property name but not always) and the value represents the column value as a basic type. We favor basic types over complex ones to increase portability (across platforms and across type / class schema evolution over time). For example a URL object is stored as its String representation. The key identifying a given entity instance is composed of: • the table name • the primary key column name(s) • the primary key column value(s) 12How is data persisted Figure 3.2. Storing entities The GridDialect specific to the NoSQL datastore you target is then responsible to convert this map into the most natural model: • for a key/value store or a data grid, we use the logical key as the key in the grid and we store the map as the value. Note that it’s an approximation and some key/value providers will use more tailored approaches. 13Chapter 3. Architecture • for a document oriented store, the map is represented by a document and each entry in the map corresponds to a property in a document. Associations are also stored as tuple as well or more specifically as a set of tuples. Hibernate OGM stores the information necessary to navigate from an entity to its associations. This is a departure from the pure relational model but it ensures that association data is reachable via key lookups based on the information contained in the entity tuple we want to navigate from. Note that this leads to some level of duplication as information has to be stored for both sides of the association. The key in which association data are stored is composed of: • the table name • the column name(s) representing the foreign key to the entity we come from • the column value(s) representing the foreign key to the entity we come from Using this approach, we favor fast read and (slightly) slower writes. 14How is data persisted Figure 3.3. Storing associations Note that this approach has benefits and drawbacks: • it ensures that all CRUD operations are doable via key lookups • it favors reads over writes (for associations) • but it duplicates data Note We might offer alternative association data persistence options in the future based on feedback. Again, there are specificities in how data is inherently stored in the specific NoSQL store. For example, in document oriented stores, the association information including the identifier to the 15Chapter 3. Architecture associated entities can be stored in the entity owning the association. This is a more natural model for documents. TODO: this sentence might be worth a diagram to show the difference with the key/value store. Some identifiers require to store a seed in the datastore (like sequences for examples). The seed is stored in the value whose key is composed of: • the table name • the column name representing the segment • the column value representing the segment Make sure to check the chapter dedicated to the NoSQL store you target to find the specificities. Many NoSQL stores have no notion of schema. Likewise, the tuple stored by Hibernate OGM is not tied to a particular schema: the tuple is represented by a Map, not a typed Map specific to a given entity type. Nevertheless, JPA does describe a schema thanks to: • the class schema • the JPA physical annotations like Table and Column. While tied to the application, it offers some robustness and explicit understanding when the schema is changed as the schema is right in front of the developers' eyes. This is an intermediary model between the strictly typed relational model and the totally schema-less approach pushed by some NoSQL families. 3.3. How is data queried Note Query support is in active development. This section describes where the project is going. Since Hibernate OGM wants to offer all of JPA, it needs to support JP-QL queries. Hibernate OGM parses the JP-QL query string and extracts its meaning. From there, several options are available depending of the capabilities of the NoSQL store you target: • it directly delegates the native query generation to the datastore specific query translator implementation 16How is data queried • it uses Teiid as an intermediary engine, Teiid delegating parts of the query to the datastore specific query translator implementation • it uses Hibernate Search as a query engine to execute the query If the NoSQL datastore has some query capabilities and if the JP-QL query is simple enough to be executed by the datastore, then the JP-QL parser directly pushes the query generation to the NoSQL specific query translator. The query returns the list of matching identifiers snd uses Hibernate OGM to return managed objects. Some of the JP-QL features are not supported by NoSQL solutions. Two typical examples are joins between entities - which you should limit anyways in a NoSQL environment - and aggregations like average, max, min etc. When the NoSQL store does not support the query, we use Teiid - a database federation engine - to build simpler queries executed to the datastore and perform the join or aggregation operations in Teiid itself. Finally some NoSQL stores have poor query support, or none at all. In this case Hibernate OGM can use Hibernate Search as its indexing and query engine. Hibernate Search is able to index and query objects - entities - and run full-text queries. It uses the well known Apache Lucene to do that but adds a few interesting characteristics like clustering support and an object oriented abstraction including an object oriented query DSL. Let’s have a look at the architecture of Hibernate OGM when using Hibernate Search: 17

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.