我无法使用Hibernate OGM删除数据库或集合。我尝试过使用这些本机查询,但两者都抛出异常
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();
删除集合的例外:
Exception in thread "main" com.mongodb.util.JSONParseException:
db.Person.drop()
^
删除数据库的例外:
Exception in thread "main" com.mongodb.util.JSONParseException:
db.dropDatabase()
^
答案 0 :(得分:0)
抱歉,目前无法做到这一点。
我不确定在OGM使用数据库的同时删除数据库是不是一个好主意。
我已经创建了这两个问题以跟踪它:
感谢您的反馈。 如果您想尝试更多地帮助我们,您可以尝试解决项目中的问题并向我们发送修复程序。我们会帮助你。
答案 1 :(得分:0)
所以,为了给出一个在测试中如何使用它的具体示例,我添加了这个答案。
我使用OGM和MongoDB的可重复工作的测试类如下:
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);
}
}