org.mongodb.morphia.Morphia Java Examples

The following examples show how to use org.mongodb.morphia.Morphia. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MongodbRepository.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void initialize(String name, boolean skipEnsureSteps, Class<? extends T>... entityClasses)
{
	morphia = new Morphia();
	inheritanceRoot = (Class<T>) entityClasses[0];

	for (Class<?> entityClass : entityClasses)
	{
		morphia.map(entityClass);
	}

	datastore = morphia.createDatastore(mongo, name);
	if (!skipEnsureSteps) {
		datastore.ensureIndexes();
		datastore.ensureCaps();
	}
}
 
Example #2
Source File: UIQueryServiceImpl.java    From lumongo with Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws ServletException {
	super.init();

	try {
		LumongoPoolConfig lumongoPoolConfig = new LumongoPoolConfig().addMember("localhost").setDefaultRetries(2);
		lumongoPoolConfig.setMemberUpdateEnabled(false);
		lumongoWorkPool = new LumongoWorkPool(lumongoPoolConfig);

		Properties properties = new Properties();
		properties.load(UIQueryServiceImpl.class.getResourceAsStream("/version.properties"));
		lumongoVersion = properties.getProperty("lumongoVersion");
		luceneVersion = properties.getProperty("luceneVersion");

		MongoClientOptions mongoClientOptions = MongoClientOptions.builder().connectionsPerHost(32).build();
		MongoClient mongoClient = new MongoClient("localhost", mongoClientOptions);
		Morphia morphia = new Morphia();
		morphia.map(UIQueryObject.class);
		datastore = morphia.createDatastore(mongoClient, QUERY_HISTORY);
		datastore.ensureIndexes();
	}
	catch (Exception e) {
		LOG.error("Failed to initiate lumongo work pool.", e);
	}

}
 
Example #3
Source File: HelperMongo.java    From helper with MIT License 6 votes vote down vote up
public HelperMongo(@Nonnull MongoDatabaseCredentials credentials) {
    MongoCredential mongoCredential = MongoCredential.createCredential(
            credentials.getUsername(),
            credentials.getDatabase(),
            credentials.getPassword().toCharArray()
    );

    this.client = new MongoClient(
            new ServerAddress(credentials.getAddress(), credentials.getPort()),
            mongoCredential,
            MongoClientOptions.builder().build()
    );
    this.database = this.client.getDatabase(credentials.getDatabase());
    this.morphia = new Morphia();
    this.morphiaDatastore = this.morphia.createDatastore(this.client, credentials.getDatabase());
    this.morphia.getMapper().getOptions().setObjectFactory(new DefaultCreator() {
        @Override
        protected ClassLoader getClassLoaderForClass() {
            return LoaderUtils.getPlugin().getClassloader();
        }
    });
}
 
Example #4
Source File: TestingModule.java    From DotCi with MIT License 5 votes vote down vote up
@Provides
@Singleton
Datastore provideDatastore(final Mongo mongo) {
    final String databaseName = SetupConfig.get().getDbName();

    final Mapper mapper = new JenkinsMapper();
    final Morphia morphia = new Morphia(mapper);
    return morphia.createDatastore(mongo, databaseName);

}
 
Example #5
Source File: AbsMongoManager.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 创建mongodb连接
 *
 * @param configPath
 */
public void createConnect(String configPath) {
    mongoConfig = FileUtil.getConfigXML(configPath, "mongoClientConfig.xml", MongoClientConfig.class);
    if (mongoConfig == null) {
        throw new RuntimeException(String.format("mongodb 配置文件 %s/MongoClientConfig.xml 未找到", configPath));
    }
    MongoClientURI uri = new MongoClientURI(mongoConfig.getUrl());
    mongoClient = new MongoClient(uri);
    morphia = new Morphia();
    morphia.mapPackage("");

    initDao();
}
 
Example #6
Source File: DotCiModule.java    From DotCi with MIT License 5 votes vote down vote up
@Provides
@Singleton
Datastore provideDatastore(final Mongo mongo) {
    final String databaseName = SetupConfig.get().getDbName();

    final Mapper mapper = new JenkinsMapper();
    final Morphia morphia = new Morphia(mapper);
    return morphia.createDatastore(mongo, databaseName);

}
 
Example #7
Source File: DataStoreProvider.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public static Datastore getDataStore(Config config) {

        String[] addresses = config.getParameter(ExtConfig.MONGO_ADDRESSES, new String[]{"127.0.0.1:27017"});
        String database = config.getParameter(ExtConfig.MONGO_DATABASE, "lts");
        String username = config.getParameter(ExtConfig.MONGO_USERNAME);
        String pwd = config.getParameter(ExtConfig.MONGO_PASSWORD);

        String cachedKey = StringUtils.concat(StringUtils.concat(addresses), database, username, pwd);

        Datastore datastore = DATA_STORE_MAP.get(cachedKey);
        if (datastore == null) {
            try {
                synchronized (lock) {
                    datastore = DATA_STORE_MAP.get(cachedKey);
                    if (datastore != null) {
                        return datastore;
                    }
                    Morphia morphia = new Morphia();
                    MongoFactoryBean mongoFactoryBean = new MongoFactoryBean(addresses, username, database, pwd);
                    MongoClient mongo = mongoFactoryBean.createInstance();
                    datastore = morphia.createDatastore(mongo, database);
                    DATA_STORE_MAP.put(cachedKey, datastore);
                }
            } catch (Exception e) {
                throw new IllegalStateException(
                        StringUtils.format("connect mongo failed! addresses: {}, database: {}",
                                addresses, database), e);
            }
        }
        return datastore;
    }
 
Example #8
Source File: MorphiaFactoryBean.java    From game-server with MIT License 5 votes vote down vote up
@Override
protected Morphia createInstance() throws Exception {
	Morphia m = new Morphia();
	if (mapPackages != null) {
		for (String packageName : mapPackages) {
			m.mapPackage(packageName, ignoreInvalidClasses);
		}
	}
	if (mapClasses != null) {
		for (String entityClass : mapClasses) {
			m.map(Class.forName(entityClass));
		}
	}
	return m;
}
 
Example #9
Source File: MongoStoreProvider.java    From alchemy with MIT License 5 votes vote down vote up
public MongoStoreProvider(MongoClient client, String database) {
    final Morphia morphia = new Morphia();
    morphia.getMapper().getOptions().setStoreEmpties(true);
    morphia.getMapper().getConverters().addConverter(DateTimeConverter.class);

    this.client = client;
    final AdvancedDatastore ds = (AdvancedDatastore) morphia.createDatastore(client, database);
    final RevisionManager revisionManager = new RevisionManager(ds);
    this.store = new MongoExperimentsStore(ds, revisionManager);
    this.cache = new MongoExperimentsCache(ds, revisionManager);
}
 
Example #10
Source File: MongoTest.java    From pampas with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void init() {
    Morphia morphia = new Morphia();

    // 告诉Morphia在哪里找到你的类
    // 可以为不同的包或者类进行多次的调用
    morphia.mapPackage("com.github.pampas.persist.entity");

    //创建datastore,并连接到指定数据库
    //datastore有两个参数,第一个用来连接到MongoDB,第二个是数据库的名字。
    datastore = morphia.createDatastore(new MongoClient(), "morphia_example");
    datastore.ensureIndexes();

}
 
Example #11
Source File: MongoDatabase.java    From MineCloud with ISC License 5 votes vote down vote up
@Override
public void setup() {
    MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(10000)
            .heartbeatConnectTimeout(10)
            .heartbeatFrequency(10)
            .build();
    List<ServerAddress> hosts = new ArrayList<>();

    for (String host : credentials.hosts()) {
        hosts.add(new ServerAddress(host));
    }

    if (hosts.size() == 0) {
        MineCloud.logger().log(Level.SEVERE, "No viable host was found for MongoDB!", new MineCloudException());
        return;
    }

    MongoClient client;

    if (credentials.username() != null && !credentials.username().equalsIgnoreCase("")) {
        MongoCredential credential = MongoCredential.createCredential(credentials.username(),
                credentials.database(), credentials.password());

        client = new MongoClient(hosts, Arrays.asList(credential), options);
    } else {
        client = new MongoClient(hosts, options);
    }

    if (hosts.size() > 1) {
        client.setWriteConcern(WriteConcern.REPLICA_ACKNOWLEDGED);
        client.setReadPreference(ReadPreference.nearest());
    }

    database = client.getDB(credentials.database());
    morphia = new Morphia();
    datastore = morphia.createDatastore(client, credentials.database());
}
 
Example #12
Source File: HelperMongo.java    From helper with MIT License 4 votes vote down vote up
@Override
public Morphia getMorphia() {
    return this.morphia;
}
 
Example #13
Source File: DatastoreFactory.java    From acmeair with Apache License 2.0 4 votes vote down vote up
public static Datastore getDatastore(Datastore ds)
{
	Datastore result =ds;
	
	if (mongourl!=null)
	{
		try{
			Properties prop = new Properties();
			prop.load(DatastoreFactory.class.getResource("/acmeair-mongo.properties").openStream());
			boolean fsync = new Boolean(prop.getProperty("mongo.fsync"));
			int w = new Integer(prop.getProperty("mongo.w"));
			int connectionsPerHost = new Integer(prop.getProperty("mongo.connectionsPerHost"));
			int threadsAllowedToBlockForConnectionMultiplier = new Integer(prop.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier"));
			
			// To match the local options
			MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
				.writeConcern(new WriteConcern(w, 0, fsync))
				.connectionsPerHost(connectionsPerHost)
				.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
		
			MongoClientURI mongoURI = new MongoClientURI(mongourl, builder);
			MongoClient mongo = new MongoClient(mongoURI);
			Morphia morphia = new Morphia();				
			result = morphia.createDatastore( mongo ,mongoURI.getDatabase());
			System.out.println("create mongo datastore with options:"+result.getMongo().getMongoClientOptions());
		}catch (Exception e)
		{
			e.printStackTrace();
		}
	}
   	// The converter is added for handing JDK 7 issue
//	result.getMapper().getConverters().addConverter(new BigDecimalConverter());		
   //	result.getMapper().getConverters().addConverter(new BigIntegerConverter());
   	
	// Enable index
	result.ensureIndex(Booking.class, "pkey.customerId");
	result.ensureIndex(Flight.class, "pkey.flightSegmentId,scheduledDepartureTime");
	result.ensureIndex(FlightSegment.class, "originPort,destPort");

   	return result;
}
 
Example #14
Source File: MongoDatabase.java    From MineCloud with ISC License 4 votes vote down vote up
public Morphia morphia() {
    return morphia;
}
 
Example #15
Source File: MongoManaged.java    From katharsis-framework with Apache License 2.0 4 votes vote down vote up
public MongoManaged (MongoConfiguration mongoConfig) throws Exception {
    mongoClient = new MongoClient(mongoConfig.host, mongoConfig.port);
    datastore = new Morphia().createDatastore(mongoClient, mongoConfig.db);
}
 
Example #16
Source File: MorphiaFactoryBean.java    From game-server with MIT License 4 votes vote down vote up
@Override
public Class<?> getObjectType() {
	return Morphia.class;
}
 
Example #17
Source File: DataStoreFactoryBean.java    From game-server with MIT License 4 votes vote down vote up
public void setMorphia(Morphia morphia) {
	this.morphia = morphia;
}
 
Example #18
Source File: DataStoreFactoryBean.java    From game-server with MIT License 4 votes vote down vote up
public Morphia getMorphia() {
	return morphia;
}
 
Example #19
Source File: AbsMongoManager.java    From game-server with MIT License 4 votes vote down vote up
public Morphia getMorphia() {
    return morphia;
}
 
Example #20
Source File: MongoLogConnector.java    From heimdall with Apache License 2.0 3 votes vote down vote up
private AdvancedDatastore datastore() {

		Morphia morphia = new Morphia();

		if (this.client == null) {
			this.createMongoClient();
		}

		return (AdvancedDatastore) morphia.createDatastore(this.client, this.databaseName);
	}
 
Example #21
Source File: Mongo.java    From helper with MIT License 2 votes vote down vote up
/**
 * Gets the Morphia instance for this datasource
 *
 * @return the morphia instance
 */
Morphia getMorphia();
 
Example #22
Source File: DBMockImpl.java    From heimdall with Apache License 2.0 2 votes vote down vote up
private Datastore datastore() {

        Morphia morphia = new Morphia();

        return morphia.createDatastore(createMongoClient(), this.databaseName);
    }
 
Example #23
Source File: DBMongoImpl.java    From heimdall with Apache License 2.0 2 votes vote down vote up
private Datastore datastore() {
 
     return new Morphia().createDatastore(this.mongoClient, this.databaseName);
}