I am writing a small application that implements select - insert operations in MongoDB .
There was a problem in initializing the database using the “initDB” method with the @PostConstruct annotation.
Session Bean Code:
package Library; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.Stateless; import javax.inject.Inject; import javax.inject.Named; @Stateless @Named public class BookSessionBean { @Inject Book book; private DBCollection bookCollection; /** * * @throws UnknownHostException */ @PostConstruct public void initDB() throws UnknownHostException { Mongo mongo = new Mongo(); DB db = mongo.getDB("booksDB"); bookCollection = db.getCollection("books"); if (bookCollection == null) { bookCollection = db.createCollection("books", null); } } public void createBook() { BasicDBObject doc = book.toDBObject(); bookCollection.insert(doc); } public List<Book> getBooks() { List<Book> books = new ArrayList<Book>(); DBCursor cursor = bookCollection.find(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); books.add(Book.fromDBObject(dbo)); } return books; } } The error itself:
The “initDB” method with the @PostConstruct annotation should not result in a raised exception being called
