Git Product home page Git Product logo

guice-persist-orient's Introduction

Guice integration for OrientDB

License CI Appveyor build status codecov

DOCUMENTATION: http://xvik.github.io/guice-persist-orient/

Examples repository

Support: Gitter chat

guice-persist-orient wins 4th place in Software Quality Award 2015

About

OrientDB is document, graph and object database (see intro and starter course). Underlying format is almost the same for all database types, which allows us to use single database in any way. For example, schema creation and updates may be performed as object database (jpa style) and graph api may be used for creating relations.

Features:

  • For orient 3.1 (java 8)
  • Integration through guice-persist (UnitOfWork, PersistService, @Transactional)
  • Support for document, object and graph databases
  • Database types support according to classpath (object and graph db support activated by adding jars to classpath)
  • All three database types may be used in single transaction (changes will be visible between different apis)
  • Hooks for schema migration and data initialization extensions
  • Extension for orient object to scheme mapper with plugins support
  • Auto mapping entities in package to db scheme or using classpath scanning to map annotated entities
  • Auto db creation (for memory, local and plocal)
  • Different db users may be used (for example, for schema initialization or to use orient security model), including support for user change inside transaction
  • Support method retry on ONeedRetryException
  • Spring-data like repositories with advanced features (e.g. generics usage in query). Great abilities for creating reusable parts (mixins). Support plugins.
  • Basic crud mixins with ability to use object api for graphs
  • Compatible with Play framework

Thanks to

Setup

Maven Central

Maven:

<dependency>
    <groupId>ru.vyarus</groupId>
    <artifactId>guice-persist-orient</artifactId>
    <version>4.1.0</version>
</dependency>
<!--
<dependency>
    <groupId>com.orientechnologies</groupId>
    <artifactId>orientdb-object</artifactId>
    <version>3.1.12</version>
</dependency>
<dependency>
    <groupId>com.orientechnologies</groupId>
    <artifactId>orientdb-graphdb</artifactId>
    <version>3.1.12</version>
</dependency>-->

Gradle:

implementation 'ru.vyarus:guice-persist-orient:4.1.0'
//implementation "com.orientechnologies:orientdb-object:3.1.12"
//implementation "com.orientechnologies:orientdb-graphdb:3.1.12"

Commented imports required to enable object and graph db support.

OrientDB Guice guice-persist-orient
3.1 5.0.1 4.1.0
3.0 5.0.1 4.0.0
2.2 4.2.0 3.3.2
2.1 4.1.0 3.2.0
2.0 4.0.0 3.1.1
1.0 4.0.0 2.1.0

NOTE: It's very important for object db to use exact javassist version it depends on. If other libraries in your classpath use javassist, check that newer or older version not appear in classpath.

Snapshots

You can use snapshot versions through JitPack:

  • Go to JitPack project page
  • Select Commits section and click Get it on commit you want to use (top one - the most recent)
  • Follow displayed instruction: add repository and change dependency (NOTE: due to JitPack convention artifact group will be different)

Usage

Read documentation

Might also like

  • generics-resolver - extracted library, used for generics resolution during finders analysis
  • dropwizard-orient-server - embedded orientdb server for dropwizard
  • guice-validator - hibernate validator integration for guice (objects validation, method arguments and return type runtime validation)
  • guice-ext-annotations - @Log, @PostConstruct, @PreDestroy and utilities for adding new annotations support

Contribution

Contributions are always welcome, but please check before patch submission:

$ gradlew check

java lib generator

guice-persist-orient's People

Contributors

bertvanbrakel avatar dependabot[bot] avatar xvik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

guice-persist-orient's Issues

Duplicate class creation

I've setup a simple example.

Package "model" contains VertexA and VertexB, both annotated with "VertexType".
Guice module installs OrientModule and PackageSchemeModule configured to scan package "model".

After starting PersistService I get the following exception:


Caused by: com.orientechnologies.orient.core.exception.OSchemaException: Class VertexA already exists in current database
    at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.doCreateClass(OSchemaShared.java:906)
    at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:363)
    at com.orientechnologies.orient.core.metadata.schema.OSchemaProxy.createClass(OSchemaProxy.java:111)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLCreateClass.execute(OCommandExecutorSQLCreateClass.java:144)
    at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.execute(OCommandExecutorSQLDelegate.java:64)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.executeCommand(OAbstractPaginatedStorage.java:1189)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.command(OAbstractPaginatedStorage.java:1178)
    at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:63)
    at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.command(ONetworkProtocolBinary.java:1178)
    at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:385)
    at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:217)
    at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:69)

I'm using guice-persist-orient 3.0.0 with OrientDB v2.0.8 (local dependency) connected to a remote OrientDB v2.0.7 with a newly created database.

After doing a simple analysis it seems that the problem is with VertexTypeExtension, shouldn't it be implemented with "afterRegistration" instead of "beforeRegistration"?

Trouble getting Pojo from (Composite) index through Repository

Hi there, I'm pretty new with this library and using OrientDB but I am stuck on selecting some entities from an index (in my case composite but i have same result on single/multiple).
The class at: https://github.com/xvik/guice-persist-orient/blob/ece1980d4dff42fac1d74d46a70053862a8e2f84/src/test/groovy/ru/vyarus/guice/persist/orient/study/index/ci/IndexCiRepository.groovy triggered my attention that it should be possible to use the index to fetch the entity directly. Unfortunately upon doing so I keep getting:

java.lang.ClassCastException:
com.orientechnologies.orient.core.record.impl.ODocument cannot be cast to orientdb.test.index.IndexTest$TestEntity

My query on the repository is:

@Query("select from index:t where key=[?,?]")

I am wondering if i am doing something wrong.
Here is my TestNG test reproducing this problem for me:

package orientdb.test.index;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.ProvidedBy;
import com.google.inject.internal.DynamicSingletonProvider;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.Transactional;
import com.orientechnologies.orient.core.metadata.schema.OClass.INDEX_TYPE;

import ru.vyarus.guice.persist.orient.OrientModule;
import ru.vyarus.guice.persist.orient.RepositoryModule;
import ru.vyarus.guice.persist.orient.db.scheme.annotation.Persistent;
import ru.vyarus.guice.persist.orient.db.scheme.initializer.ext.type.index.CompositeIndex;
import ru.vyarus.guice.persist.orient.model.VersionedEntity;
import ru.vyarus.guice.persist.orient.repository.command.query.Query;
import ru.vyarus.guice.persist.orient.support.AutoScanSchemeModule;
import ru.vyarus.guice.persist.orient.support.repository.mixin.crud.ObjectCrud;

public class IndexTest {

    @BeforeTest
    public void init() throws Exception {       
        Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                install(new OrientModule("memory:test", "admin", "admin"));
                install(new AutoScanSchemeModule(this.getClass().getPackage().getName()));
                install(new RepositoryModule());
                bind(Initializer.class).asEagerSingleton();
            }
        }).injectMembers(this);
    }

    @Inject TestEntityRepository testRepo;

    @Test
    public void run() throws Exception {
        final TestEntity te = new TestEntity();
        te.id1 = 1;
        te.id2 = 2;
        testRepo.save(te);

        testRepo.loadIndex(1,2);
    }

    @Persistent @CompositeIndex(name="t", fields={"id1", "id2" }, type = INDEX_TYPE.NOTUNIQUE)
    class TestEntity extends VersionedEntity {
        long id1;
        long id2;
    }

    @Transactional @ProvidedBy(DynamicSingletonProvider.class)
    public interface TestEntityRepository extends ObjectCrud<TestEntity> {
        @Query("select from index:t where key=[?,?]")
        TestEntity loadIndex(long id1, long id2);
    }

    @Singleton
    public static class Initializer {
        @Inject
        public Initializer(PersistService service) {
            service.start();
        }
    }
}

Basically I have TestEntity with id1 and id2 that are a composite index as well. I use TestEntityRepository to save entity and use loadIndex using the composite key to fetch the TestEntity. Unfortunately the TestEntityRepository generated loadIndex returns a ClassCastException because ODocument cannot be cast to TestEntity.

What am I missing?

Thanks for your help and this great guice integration

Plans for OSGi support

I just downloaded the jar and find it has no OSGi manifest headers. Have you thought about adding those?

If not, if I create a PR with OSGi support, would you be interested? If not, I will clone the project and add it, but as both Guice and OrientDB are OSGi ready, it would be good for your project to have the same support.

Thanks!

@Var using a list of type <String> and IN does not work

Hi there,

I am using the following query:

@Query("update Required set done = false where requiredId IN $rids")
void undo(@Var("rids") List<String> rids);

This works if rids is of type List<Long> because it results in [232,2232]
But in case this is a List<String> I would expect ["232Ad8d","sadA34d"] but it results in [232Ad8d,sadA34d] when the query get's executed.

Am I doing something wrong? Is there an easy way to log queries?

Question: How do I register my custom types serializer with guice-persist-orient

I am consuming some CXF generated WebService and have XMLGregorianCalendar as XMLElement type. I need to register a custom serializer for this class. The description on how to do this is here http://orientdb.com/docs/2.2/Object-2-Record-Java-Binding.html#custom-types

OObjectSerializerContext serializerContext = new OObjectSerializerContext();
serializerContext.bind(new OObjectSerializer<XMLGregorianCalendar, Long>() {
	@Override
	public Object serializeFieldValue(Class<?> iClass, XMLGregorianCalendar iFieldValue) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object unserializeFieldValue(Class<?> iClass, Long iFieldValue) {
		// TODO Auto-generated method stub
		return null;
	}
}, database?);

Is there a way to register?

Update: I am able to use jaxb:bindings to generate different property types and use adapters to fix this but I wanted to try and do it the naive way first.

Multiple instances

Hi, your project looks interesting, but could you tell me if it supports multiple instances of OrientDb? From your README it looks as though it is built on guice-persist, which supports only one instance. (I prefer to use Onami persist for that reason)

Configuration

can any body tell me how to configure guice for orientdb with spring boot

setNullValuesIgnored seems to always be false when using @Index(value=INDEX_TYPE.NOTUNIQUE

Hi there!
I'm using version 3.3.0. Using the following index annotation
@Index(value=INDEX_TYPE.NOTUNIQUE)
which defaults to ignoreNullValues=true will always force a rebuilt of the index when restarting.
When specifically setting @Index(value=INDEX_TYPE.NOTUNIQUE, ignoreNullValues=false) it will not rebuild after every restart.
Perhaps this is a bug in OrientDB but I came across a few issues about this and I don't really know where to look.

See orientechnologies/orientdb#6746 (closed but not really fixed?)
Or might this be a bug in the IndexFieldExtension not picking up from OrientDB

Please close this if it is not a guice-persist-orient bug.

Thanks for this wonderful library!

Feature: Support Non Orient Based Repositories - Potentially Extract Repository Framework into Separate Project

Ok, so we really like how this project uses Guice AOP and https://github.com/xvik/guice-ext-annotations to create "Repositories" for data. Specifically, we like how the @Delegate can be used to define our DAOs using interfaces and then assign their method execution to base implementation classes.

We have been looking for such a capability and have come across:
Warp-persist: https://code.google.com/p/warp-persist/
Guice-repository: https://code.google.com/p/guice-repository/

Unfortunately, both of these projects are still hosted on Google Code and appear quite outdated.

In addition to using Orient, we are also using Postgres with Hibernate/JPA. We'd really like to use your "repository" Pattern implementation, but there are a few things:

  1. We don't want all the other Orient overhead stuff in projects where we are not also using Orient.
  2. When we tried to "extend" the existing guice-persist-orient library, the limited DbType enum would not allow us to set a new DbType such as SQL or JPA, which we would need to register our own RepositoryExtensions.

Any interest in extracting out the entire repository framework into its own project?

I've started such an implementation using your code as inspiration but you've already developed and architected so many excellent pieces it seems somewhat silly to do so much.

Multi-tenancy support

I really like the comprehensive set of features that covered with this.

I have a multi-tenancy application where I have one database per customer and all the databases will have the same schema. I want to switch the data source based on a ThreadLocal property. Is there a way this project support that? Few hints are good enough. I will take it from there.

Thank you very much for this awesome repo.

Failed to initialize scheme

Hi,
I'm trying to configure and bootstrap framework as part of a TestNG test:

@Guice(modules = {PersistenceModule.class})
public class PlayerRepositoryTests {

    @Inject
    PersistService persistService;

    @Inject
    PlayerRepository playerRepository;

    @BeforeTest
    public void persistenceService_isStarted() {
        persistService.start();
    }

    @BeforeTest
    public void repoIsInjected() {
        Assert.assertNotNull(playerRepository);
    }

    @Test
    public void testFindAll() {
        List<Player> result = playerRepository.findAll();
        Assert.assertNotNull(result);
        Assert.assertEquals(0, result.size());
    }
}

Per the guide provided on GitHub, I install the appropriate modules with:

public class PersistenceModule extends AbstractModule {

    private static final Logger LOG = LoggerFactory.getLogger( PersistenceModule.class );

    @Named("database.url")
    private String url = "memory:acmedb";

    @Named("database.user")
    private String user = "admin";

    @Named("database.password")
    private String password = "admin";

    @Override
    protected void configure() {

        OrientModule orientModule = new OrientModule(url,user,password);
        install(orientModule);

        AutoScanSchemeModule schemeModule = new AutoScanSchemeModule("com.acme.domain.entity");
        install(schemeModule);

        RepositoryModule repositoryModule = new RepositoryModule();
        repositoryModule.defaultConnectionType(DbType.GRAPH);
        install(repositoryModule);
    }
}

Define a single VertexType entity in the package to scan:

@Persistent
@VertexType
public class Player {

    private String firstName;
    private String lastName;

    @Id
    private String id;
    @Version
    private Long version;
    // 
}

And a simple repository definition:

@Transactional
@ProvidedBy(DynamicSingletonProvider.class)
public interface PlayerRepository {

    @Query("select from Player")
    public List<Player> findAll();
}

I'm getting the following the following stacktrace when I run the test:

Jun 16, 2015 9:58:03 PM com.orientechnologies.common.log.OLogManager log
INFO: OrientDB auto-config DISKCACHE=10,695MB (heap=3,641MB os=16,384MB disk=135,208MB)
ru.vyarus.guice.persist.orient.db.scheme.SchemeInitializationException: Failed to initialize scheme
    at ru.vyarus.guice.persist.orient.db.DatabaseManager.start(DatabaseManager.java:99)
    at com.nextlevel.repo.PlayerRepositoryTests.persistenceService_isStarted(PlayerRepositoryTests.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    at org.testng.TestRunner.beforeRun(TestRunner.java:641)
    at org.testng.TestRunner.run(TestRunner.java:609)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
    at org.testng.SuiteRunner.run(SuiteRunner.java:254)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:125)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: ru.vyarus.guice.persist.orient.db.scheme.SchemeInitializationException: Failed to register model class com.nextlevel.domain.entity.Player
    at ru.vyarus.guice.persist.orient.db.scheme.initializer.ObjectSchemeInitializer.register(ObjectSchemeInitializer.java:74)
    at ru.vyarus.guice.persist.orient.db.scheme.impl.AbstractObjectInitializer.registerClasses(AbstractObjectInitializer.java:88)
    at ru.vyarus.guice.persist.orient.db.scheme.impl.AbstractObjectInitializer.initialize(AbstractObjectInitializer.java:52)
    at ru.vyarus.guice.persist.orient.db.DatabaseManager$2.execute(DatabaseManager.java:94)
    at ru.vyarus.guice.persist.orient.db.DatabaseManager$2.execute(DatabaseManager.java:91)
    at ru.vyarus.guice.persist.orient.db.transaction.template.TxTemplate.doInTransaction(TxTemplate.java:58)
    at ru.vyarus.guice.persist.orient.db.DatabaseManager.start(DatabaseManager.java:91)
    ... 29 more
Caused by: ru.vyarus.guice.persist.orient.db.scheme.SchemeInitializationException: Failed to create extension VertexTypeExtension declared by annotation @VertexType on class Player
    at ru.vyarus.guice.persist.orient.db.scheme.initializer.core.ext.ExtensionsDescriptorFactory.createTypeExtension(ExtensionsDescriptorFactory.java:72)
    at ru.vyarus.guice.persist.orient.db.scheme.initializer.core.ext.ExtensionsDescriptorFactory.prepareTypeExtensions(ExtensionsDescriptorFactory.java:60)
    at ru.vyarus.guice.persist.orient.db.scheme.initializer.core.ext.ExtensionsDescriptorFactory.resolveExtensions(ExtensionsDescriptorFactory.java:43)
    at ru.vyarus.guice.persist.orient.db.scheme.initializer.ObjectSchemeInitializer.processType(ObjectSchemeInitializer.java:90)
    at ru.vyarus.guice.persist.orient.db.scheme.initializer.ObjectSchemeInitializer.register(ObjectSchemeInitializer.java:71)
    ... 35 more
Caused by: com.google.inject.ConfigurationException: Guice configuration errors:

1) Unable to create binding for ru.vyarus.guice.persist.orient.db.DatabaseManager. It was already configured on one or more child injectors or private modules
    (bound by a just-in-time binding)
  If it was in a PrivateModule, did you forget to expose the binding?
  while locating ru.vyarus.guice.persist.orient.db.DatabaseManager
    for parameter 0 at ru.vyarus.guice.persist.orient.db.scheme.initializer.ext.type.vertex.VertexTypeExtension.<init>(VertexTypeExtension.java:29)
  while locating ru.vyarus.guice.persist.orient.db.scheme.initializer.ext.type.vertex.VertexTypeExtension

1 error
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1042)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1001)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
    at ru.vyarus.guice.persist.orient.db.scheme.initializer.core.ext.ExtensionsDescriptorFactory.createTypeExtension(ExtensionsDescriptorFactory.java:70)
    ... 39 more

What am I missing or doing wrong? Appreciate any insight or help you can provide. Thanks.

Repository query: boolean parameter not supported?

Dear Vyacheslav,

maybe I did something wrong, but the following is not working for me:

@query("select from User where username = ? and active = ? limit 1")
User findByUsernameAndActive(String username, boolean active);

It will always return null, if I call it with a username that exists and active == true, even if the user is set active in the database.
If I remove the boolean parameter, it works. (with non-primitive Boolean it also doesn't work)

Maybe you could take a look at this sometime, but it's not urgent - thank you!

Feature request; Master-Master replication configuration

Hi, maybe some strange request but would it be nice to easily bind multiple servers together to create a master-master or master-slave kinda setup or perhaps post an example on how to do it with guice-persist-orient if it is possible with current codebase?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.