I can't drop databases or collections using Hibernate OGM. I've tried using these native queries but an exception is thrown for both
entityManagerFactory = Persistence.createEntityManagerFactory("myPersistence-unit");
EntityManager entityManager = openEntityManager( entityManagerFactory);
entityManager.getTransaction().begin();
String queryDropCollection = "db.Person.drop()";
String queryDropDB = "db.dropDatabase()";
entityManager.createNativeQuery(queryDropCollection).executeUpdate();
entityManager.createNativeQuery(queryDropDB).executeUpdate();
entityManager.getTransaction().commit();
entityManager.close();
The exception for dropping the collection:
Exception in thread "main" com.mongodb.util.JSONParseException:
db.Person.drop()
^
The exception for dropping the database:
Exception in thread "main" com.mongodb.util.JSONParseException:
db.dropDatabase()
^
Sorry, this is not possible right now.
I'm not sure if it would be a good idea to drop the database while OGM is using it, though.
I've created these two issues to keep track from it:
Thanks for the feedback. If you feel like trying to help us even more, you could try to solve the issues in the project and send us a fix. We will help you.
So, just to give a concrete example of how to use this in tests, I am adding this answer.
My working repeatable test class using OGM and MongoDB looks like this:
class OgmAccessorTest {
private static EntityManagerFactory entityManagerFactory;
private static EntityManager entityManager;
private static TransactionManager transactionManager;
@BeforeAll
static void initialize() {
entityManagerFactory = Persistence.createEntityManagerFactory("ogm-mongodb");
entityManager = entityManagerFactory.createEntityManager();
transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
}
@BeforeEach
void clearDatabase() throws NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
transactionManager.begin();
// Collection == name of the class being saved ⮧
entityManager.createNativeQuery("db.GameCharacter.drop()").executeUpdate();
transactionManager.commit();
}
@Test
void writeShouldBeAbleToWriteRetreivableGameCharacterToMongoDB() throws SecurityException, IllegalStateException, NotSupportedException, SystemException, HeuristicMixedException, HeuristicRollbackException, RollbackException {
GameCharacter sylvia = GameCharacters.sylvia();
OgmAccessor.write(sylvia, entityManagerFactory);
transactionManager.begin();
GameCharacter loadedGameCharacter
= entityManager.find(GameCharacter.class, sylvia._id);
assertNotNull(loadedGameCharacter);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.