Slide 1

Slide 1 text

Data Access 2.0? …please welcome… Spring Data! Oliver Gierke

Slide 2

Slide 2 text

Oliver Gierke Spring Data Core/JPA/MongoDB [email protected] www.olivergierke.de olivergierke

Slide 3

Slide 3 text

What to expect?

Slide 4

Slide 4 text

Why? How? What?

Slide 5

Slide 5 text

A Developer‘s View

Slide 6

Slide 6 text

What to expect? NOT!

Slide 7

Slide 7 text

What to expect? NOT!

Slide 8

Slide 8 text

Retrospect

Slide 9

Slide 9 text

Relational databases

Slide 10

Slide 10 text

Scaling

Slide 11

Slide 11 text

Data structures

Slide 12

Slide 12 text

(No)SQL Redis Riak MongoDB Cassandra CouchDB Neo4J HBase SimpleDB OrientDB Membase Hibari Voldemort Sones

Slide 13

Slide 13 text

Key Value

Slide 14

Slide 14 text

Column families

Slide 15

Slide 15 text

Graphs

Slide 16

Slide 16 text

Documents

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

Document database JSON documents JSON queries

Slide 19

Slide 19 text

19 MongoDB Infrastructure API Mongo mongo = new Mongo(…); DB db = mongo.getDB("myDatabase"); Collection collection = db.getCollection("myCollection"); DBObject address = new BasicDBObject(); address.put("city", "London"); DBObject person = new BasicDBObject(); person.put("firstname", "Dave"); person.put("lastname", "Matthews"); person.put("address", address); collection.save(person);

Slide 20

Slide 20 text

20 MongoDB Query API Mongo mongo = new Mongo(…); DB db = mongo.getDB("myDatabase"); Collection collection = db.getCollection("myCollection"); DBObject query = new BasicDBObject(); query.put("address.city", "London"); DBCursor cursor = collection.find(query); for (DBObject element : cursor) { // Map data onto object }

Slide 21

Slide 21 text

Graph database Nodes / Relationships Traversals / Cypher / Gremlin

Slide 22

Slide 22 text

22 Neo4J Infrastructure API GraphDatabaseService database = new EmbeddedGraphDatabase(…); Transaction tx = database.beginTx(); try { Node mrAnderson = database.createNode(); mrAnderson.setProperty("name", "Thomas Anderson"); Node morpheus = database.createNode(); morpheus.setProperty("name", "Morpheus"); Relationship friendship = mrAnderson.createRelationshipTo( morpheus, FriendTypes.KNOWS); tx.success(); } finally { tx.finish(); }

Slide 23

Slide 23 text

23 Neo4J Query API GraphDatabaseService database = new EmbeddedGraphDatabase(…); CypherParser parser = new CypherParser(); Query query = parser.parse("start person = Person(id = *) match " + "person-[:colleagues]->colleague where colleague.firstname = {name}"); Map parameters = new HashMap(); parameters.put("name", "Dave"); ExecutionEngine engine = new ExecutionEngine(database); ExecutionResult result = engine.execute(query, parameters); for (EntrySet element : result) { // Map data onto object }

Slide 24

Slide 24 text

24 Neo4J entity class Actor { private final Node node; public Actor(Node node) { … } public String getName() { return (String) node.getProperty(„name“); } … }

Slide 25

Slide 25 text

Forest for the woods?

Slide 26

Slide 26 text

JPA?

Slide 27

Slide 27 text

" This document is the specification of the Java API for the management of persistence and object/relational mapping with Java EE and Java SE. The technical objective of this work is to provide an object/relational mapping facility for the Java application developer using a Java domain model to man- age a relational database.

Slide 28

Slide 28 text

" This document is the specification of the Java API for the management of persistence and object/relational mapping with Java EE and Java SE. The technical objective of this work is to provide an object/relational mapping facility for the Java application developer using a Java domain model to man- age a relational database.

Slide 29

Slide 29 text

JPA?

Slide 30

Slide 30 text

There‘s some Spring for that!

Slide 31

Slide 31 text

Spring Data

Slide 32

Slide 32 text

"… provide a familiar and consistent Spring-based programming model while retaining store-specific features and capabilities.

Slide 33

Slide 33 text

Spring Data JPA JDBC

Slide 34

Slide 34 text

Spring Data JPA JDBC

Slide 35

Slide 35 text

Spring Data JPA JDBC

Slide 36

Slide 36 text

Spring Data JPA JDBC

Slide 37

Slide 37 text

Building blocks

Slide 38

Slide 38 text

Spring

Slide 39

Slide 39 text

Mapping

Slide 40

Slide 40 text

40 JPA entity mapping @Entity class Person { @Id @GeneratedValue(strategy=GenerationType.AUTO) private BigInteger id; private String firstname, lastname; @Column(name="email") private String emailAddress; @OneToMany private Set colleagues; }

Slide 41

Slide 41 text

41 Entity mapping - MongoDB @Document class Person { @Id private BigInteger id; @Indexed private String firstname, lastname; @Field("email") private String emailAddress; @DBRef private Set colleagues; public Person(String firstname) { … } @PersistenceConstructor public Person(String firstname, String lastname) { … } … }

Slide 42

Slide 42 text

42 Entity mapping - Neo4J @NodeEntity class Person { @GraphId private long id; @Indexed private String firstname, lastname; @RelatedTo(direction = Direction.INCOMING) private Set colleagues; public Person(String firstname) { … } @PersistenceConstructor public Person(String firstname, String lastname) { … } … }

Slide 43

Slide 43 text

Templates

Slide 44

Slide 44 text

44 MongoOperations / -Template public interface MongoOperations { // Generic callback-accepting methods T execute(DbCallback action); T execute(Class entityClass, CollectionCallback action); T execute(String collectionName, CollectionCallback action); // Higher level access methods List find(Query query, Class entityClass); void save(Object objectToSave, String collectionName); WriteResult updateFirst(Query query, Update update, Class entityClass); // Geo API GeoResults geoNear(NearQuery near, Class entityClass); }

Slide 45

Slide 45 text

45 MongoTemplate usage // Setup infrastructure Mongo mongo = new Mongo(); MongoDbFactory factory = new SimpleMongoDbFactory(mongo, „foo“); MongoTemplate template = new MongoTemplate(factory); // Create and save entity Person dave = new Person("Dave", "Matthews"); dave.setEmailAddress("[email protected]"); template.save(person); // Query entity Query query = new Query(new Criteria("emailAddress") .is("[email protected]")); assertThat(template.find(query), is(dave));

Slide 46

Slide 46 text

Repositories

Slide 47

Slide 47 text

47 Repositories - JPA public interface PersonRepository extends Repository { // Finder for a single entity Person findByEmailAddress(String emailAddress); // Finder for multiple entities List findByLastnameLike(String lastname); // Finder with pagination Page findByFirstnameLike(String firstname, Pageable page); }

Slide 48

Slide 48 text

48 Repositories - MongoDB public interface PersonRepository extends Repository { // Finder for a single entity Person findByEmailAddress(String emailAddress); // Finder for multiple entities List findByLastnameLike(String lastname); // Finder with pagination Page findByFirstnameLike(String firstname, Pageable page); // Geospatial queries List findByLocationNear(Point location, Distance distance); GeoResults findByLocationNear(Point location); }

Slide 49

Slide 49 text

49 Repositories - MongoDB @Component public class MyClient { @Autowired private PersonRepository repository; public List doSomething() { Point point = new Point(43.7, 48.8); Distance distance = new Distance(200, Metrics.KILOMETERS); return repository.findByLocationNear(point, distance); } }

Slide 50

Slide 50 text

50 Repositories - Neo4J interface PersonRepository extends GraphRepository // Finder for a single entity Person findByEmailAddress(String emailAddress); // Finder for multiple entities List findByLastnameLike(String lastname); // Finder with pagination Page findByFirstnameLike(String firstname, Pageable page); @Query("start person = Person(id = *) " + "match person-[:colleagues]->colleague where " + "colleague.firstname = {name}") List getPersonsWithColleaguesName( @Param("name") Movie m); }

Slide 51

Slide 51 text

Repositories 51 Querydsl

Slide 52

Slide 52 text

52 Querydsl QPerson $ = QPerson.person; BooleanExpression left = $.lastname.contains("eth"); BooleanExpression right = $.firstname.is("Carter"); public interface QueryDslPredicateExecutor { T findOne(Predicate predicate); List findAll(Predicate predicate); } public interface PersonRepository extends Repository, QueryDslPredicateExecutor { … } List result = repository.findAll(left.or(right)); assertThat(result.size(), is(2)); assertThat(result, hasItems(dave, carter));

Slide 53

Slide 53 text

Wrap up

Slide 54

Slide 54 text

Sophisticated mapping support Templates Repositories Querydsl Spring namespace Geospatial support (MongoDB) Cross-store persistence Wrap up

Slide 55

Slide 55 text

Questions?

Slide 56

Slide 56 text

Resources • www.springframework.org/spring-data • github.com/SpringSource/spring-data-mongodb • github.com/SpringSource/spring-data-neo4j • http://www.se-radio.net/2010/07/episode-165-nosql-and- mongodb-with-dwight-merriman • http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis