Java Code Examples for org.hibernate.search.FullTextSession#beginTransaction()

The following examples show how to use org.hibernate.search.FullTextSession#beginTransaction() . 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: IndexRequestMasterListener.java    From development with Apache License 2.0 6 votes vote down vote up
private void handleListIndexing(
        Collection<? extends DomainObject<?>> list) {
    Session session = getSession();
    if (list == null || session == null) {
        return;
    }

    FullTextSession fts = Search.getFullTextSession(session);
    Transaction tx = fts.beginTransaction();

    for (DomainObject<?> obj : list) {
        if (obj != null) {
            fts.index(obj);
        }
    }

    tx.commit();
}
 
Example 2
Source File: IndexRequestMasterListener.java    From development with Apache License 2.0 5 votes vote down vote up
private void handleObjectIndexing(Object parameter) {

        Session session = getSession();
        if (parameter == null || session == null) {
            return;
        }

        FullTextSession fts = Search.getFullTextSession(session);
        Transaction tx = fts.beginTransaction();

        fts.index(parameter);

        tx.commit();
    }
 
Example 3
Source File: SystemService.java    From wallride with Apache License 2.0 5 votes vote down vote up
@Async
@Transactional(propagation = Propagation.SUPPORTS)
public void reIndex() throws Exception {
	logger.info("Re-Index started");

	FullTextSession fullTextSession = Search.getFullTextSession((entityManager.unwrap(Session.class)));

	fullTextSession.setFlushMode(FlushMode.MANUAL);
	fullTextSession.setCacheMode(CacheMode.IGNORE);

	for (Class persistentClass : fullTextSession.getSearchFactory().getIndexedTypes()) {
		Transaction transaction = fullTextSession.beginTransaction();

		// Scrollable results will avoid loading too many objects in memory
		ScrollableResults results = fullTextSession.createCriteria(persistentClass)
				.setFetchSize(BATCH_SIZE)
				.scroll(ScrollMode.FORWARD_ONLY);
		int index = 0;
		while (results.next()) {
			index++;
			fullTextSession.index(results.get(0)); //index each element
			if (index % BATCH_SIZE == 0) {
				fullTextSession.flushToIndexes(); //apply changes to indexes
				fullTextSession.clear(); //free memory since the queue is processed
			}
		}
		transaction.commit();
	}
	logger.info("Re-Index finished");
}
 
Example 4
Source File: SlaveNodeInitializer.java    From maven-framework-project with MIT License 4 votes vote down vote up
public void contextInitialized(ServletContextEvent event) {
	
	event.getServletContext().setAttribute("mode", "slave");

	// For demonstration purposes, we will have about half the data created by the master node... and the other half created by 
	// the slave node.  After a few seconds, both nodes will refresh their local copies of the index using the overall master... and 
	// all of the App entities will be searchable from either node.  
	FullTextSession fullTextSession = Search.getFullTextSession( openSession() );
	fullTextSession.beginTransaction();
	
	//
	// Get references to the 5 devices, which should have already been populated in the database by the master node
	//
	Device xPhone = (Device) fullTextSession.createQuery( "from Device as device where device.name = ?" ).setString(0, "xPhone").uniqueResult();
	Device xTablet = (Device) fullTextSession.createQuery( "from Device as device where device.name = ?" ).setString(0, "xTablet").uniqueResult();
	Device solarSystem = (Device) fullTextSession.createQuery( "from Device as device where device.name = ?" ).setString(0, "Solar System Phone").uniqueResult();
	Device flame = (Device) fullTextSession.createQuery( "from Device as device where device.name = ?" ).setString(0, "Flame Book Reader").uniqueResult();
	Device pc = (Device) fullTextSession.createQuery( "from Device as device where device.name = ?" ).setString(0, "Personal Computer").uniqueResult();
	
	//
	// Create and persist the remaining 6 of 12 apps with devices and customer reviews
	//		
	App frustratedFlamingos = new App(
			"Frustrated Flamingos", 
			"flamingo.jpg", 
			"A fun little game app, where you throw large birds around for no apparent reason.  Why else do you think they're so frustrated?",
			"Games",
			0.99f);
	frustratedFlamingos.setSupportedDevices( new HashSet<Device>(Arrays.asList(new Device[] { xPhone, xTablet, solarSystem, flame, pc })) );
	CustomerReview frustratedFlamingosReview = new CustomerReview("BirdSlinger", 4, "LOL, I love catapulting the flamingos into the cows!  I hate how the advertisement banner hides part of the view, tho.");
	frustratedFlamingos.setCustomerReviews( new HashSet<CustomerReview>(Arrays.asList(new CustomerReview[] { frustratedFlamingosReview })) );
	fullTextSession.save(frustratedFlamingos);
	logger.info("Persisting " + frustratedFlamingos.getName());
	
	App grype = new App(
			"Grype Video Conferencing", 
			"laptop.jpg", 
			"Make free local and international calls, with video, using this app and your home Internet connection.  Better yet, make free calls using your employer's Internet connection!",
			"Internet",
			3.99f);
	grype.setSupportedDevices( new HashSet<Device>(Arrays.asList(new Device[] { xPhone, xTablet, solarSystem, pc })) );
	CustomerReview grypeReview = new CustomerReview("office.casual", 4, "I wish they had not added video to this app in the latest version.  I liked it much more back when I didn't have to get dressed.");
	grype.setCustomerReviews( new HashSet<CustomerReview>(Arrays.asList(new CustomerReview[] { grypeReview })) );
	fullTextSession.save(grype);
	logger.info("Persisting " + grype.getName());
	
	App eReader = new App(
			"E-Book Reader", 
			"book.jpg", 
			"Read books on your computer, or on the go from your mobile device with this powerful e-reader app.  We recommend \"Hibernate Search by Example\", from Packt Publishing.",
			"Media",
			1.99f);
	eReader.setSupportedDevices( new HashSet<Device>(Arrays.asList(new Device[] { xPhone, xTablet, solarSystem, flame, pc })) );
	CustomerReview eReaderReview = new CustomerReview("StevePerkins", 5, "This 'Hibernate Search by Example' book is brilliant!  Thanks for the recommendation!");
	eReader.setCustomerReviews( new HashSet<CustomerReview>(Arrays.asList(new CustomerReview[] { eReaderReview })) );
	fullTextSession.save(eReader);
	logger.info("Persisting " + eReader.getName());
	
	App domeBrowser = new App(
			"Dome Web Browser", 
			"orangeswirls.jpg", 
			"This amazing app allows us to track all of your online activity.  We can figure out where you live, what you had for breakfast this morning, or what your closest secrets are.  The app also includes a web browser.",
			"Internet",
			0);
	domeBrowser.setSupportedDevices( new HashSet<Device>(Arrays.asList(new Device[] { solarSystem, flame, pc })) );
	CustomerReview domeBrowserReview = new CustomerReview("TinFoilHat", 1, "I uninstalled this app.  If the government would fake a moon landing, then they would definately use my browser history to come after me.");
	domeBrowser.setCustomerReviews( new HashSet<CustomerReview>(Arrays.asList(new CustomerReview[] { domeBrowserReview })) );
	fullTextSession.save(domeBrowser);
	logger.info("Persisting " + domeBrowser.getName());
	
	App athenaRadio = new App(
			"Athena Internet Radio", 
			"jamming.jpg", 
			"Listen to your favorite songs on streaming Internet radio!  When you like a song, this app will play more songs similar to that one.  Or at least it plays more songs... to be honest, sometimes they're not all that similar.  :(",
			"Media",
			3.99f);
	athenaRadio.setSupportedDevices( new HashSet<Device>(Arrays.asList(new Device[] { xPhone, xTablet, solarSystem, flame, pc })) );
	CustomerReview athenaRadioReview = new CustomerReview("lskinner", 5, "I requested 'Free Bird', and this app played 'Free Bird'.  What's not to like?");
	athenaRadio.setCustomerReviews( new HashSet<CustomerReview>(Arrays.asList(new CustomerReview[] { athenaRadioReview })) );
	fullTextSession.save(athenaRadio);
	logger.info("Persisting " + athenaRadio.getName());
	
	App mapJourney = new App(
			"Map Journey", 
			"compass.jpg", 
			"Do you need directions to help you reach a destination?  This GPS app will definitely produce enough turn-by-turn directions to get you there!  Eventually.",
			"Travel",
			0.99f);
	mapJourney.setSupportedDevices( new HashSet<Device>(Arrays.asList(new Device[] { xPhone, solarSystem, pc })) );
	CustomerReview mapJourneyReview = new CustomerReview("LostInSpace", 3, "Not great... but still WAY better than Orange maps.");
	mapJourney.setCustomerReviews( new HashSet<CustomerReview>(Arrays.asList(new CustomerReview[] { mapJourneyReview })) );
	fullTextSession.save(mapJourney);
	logger.info("Persisting " + mapJourney.getName());
	
	//
	// Close and cleanup the Hibernate session
	//
	fullTextSession.getTransaction().commit();
	fullTextSession.close();
	
}
 
Example 5
Source File: SearchServlet.java    From maven-framework-project with MIT License 4 votes vote down vote up
/**
 * This method contains the primary search functionality for this servlet, and is automatically invoked once for every HTTP
 * POST to the mapped URL. 
 */
@SuppressWarnings("unchecked")
@Override	
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	Logger logger = LoggerFactory.getLogger(SearchServlet.class);
	
	// Get the user's search keyword(s) from CGI variables
	String searchString = request.getParameter("searchString");
	logger.info("Received searchString [" + searchString + "]");

	// Start a Hibernate session.
	Session session = StartupDataLoader.openSession();
	
	// Create a Hibernate Search wrapper around the vanilla Hibernate session
	FullTextSession fullTextSession = Search.getFullTextSession(session);

	// Begin a transaction.  This may not be strictly necessary, but is a good practice in general.
	fullTextSession.beginTransaction();

	// Create a Hibernate Search QueryBuilder for the appropriate Lucene index (i.e. the index for "App" in this case)
	QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( App.class ).get();
	
	// Use the QueryBuilder to construct a Lucene keyword query... matching the user's search keywords against the "name" 
	// and "description" fields of App, as well as "name" field of associated Device entities, and the "comments" field of
	// embedded CustomerReview objects.
	org.apache.lucene.search.Query luceneQuery = queryBuilder
		.keyword()
		.onFields("name", "description", "supportedDevices.name", "customerReviews.comments")
		.matching(searchString)
		.createQuery();
	org.hibernate.Query hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, App.class);
	
	List<App> apps = hibernateQuery.list();
	logger.info("Found " + apps.size() + " apps");

	// Detach the results from the Hibernate session (to prevent unwanted interaction between the view layer 
	// and Hibernate when associated devices or embedded customer reviews are referenced)
	fullTextSession.clear();

	// Put the search results on the HTTP reqeust object
	request.setAttribute("apps", apps);

	// Close and clean up the Hibernate session
	fullTextSession.getTransaction().commit();
	session.close();
	
	// Forward the request object (including the search results) to the JSP/JSTL view for rendering
	getServletContext().getRequestDispatcher("/WEB-INF/pages/search.jsp").forward(request, response);
}
 
Example 6
Source File: SearchServlet.java    From maven-framework-project with MIT License 4 votes vote down vote up
/**
 * This method contains the primary search functionality for this servlet, and is automatically invoked once for every HTTP
 * POST to the mapped URL. 
 */
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	Logger logger = LoggerFactory.getLogger(SearchServlet.class);
	
	// Get the user's search keyword(s) from CGI variables
	String searchString = request.getParameter("searchString");
	logger.info("Received searchString [" + searchString + "]");

	// Start a Hibernate session.
	Session session = StartupDataLoader.openSession();
	
	// Create a Hibernate Search wrapper around the vanilla Hibernate session
	FullTextSession fullTextSession = Search.getFullTextSession(session);
	
	// Begin a transaction.  This may not be strictly necessary, but is a good practice in general.
	fullTextSession.beginTransaction();

	// Create a Hibernate Search QueryBuilder for the appropriate Lucene index (i.e. the index for "App" in this case)
	QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( App.class ).get();
	
	// Use the QueryBuilder to construct a Lucene keyword query, matching the user's search keywords against the name 
	// and description fields of App.
	org.apache.lucene.search.Query luceneQuery = queryBuilder
		.keyword()
		.onFields("name", "description")
		.matching(searchString)
		.createQuery();
	org.hibernate.Query hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, App.class);
	
	// Perform the search query, and put its results on the HTTP request object
	List<App> apps = 	hibernateQuery.list();
	logger.info("Found " + apps.size() + " search results");
	request.setAttribute("apps", apps);
    
	// Close and clean up the Hibernate session
	fullTextSession.getTransaction().commit();
	session.close();
	
	// Forward the request object (including the search results) to the JSP/JSTL view for rendering
	getServletContext().getRequestDispatcher("/WEB-INF/pages/search.jsp").forward(request, response);
}
 
Example 7
Source File: SearchServlet.java    From maven-framework-project with MIT License 4 votes vote down vote up
/**
 * This method contains the primary search functionality for this servlet, and is automatically invoked once for every HTTP
 * POST to the mapped URL. 
 */
@SuppressWarnings("unchecked")
@Override	
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	Logger logger = LoggerFactory.getLogger(SearchServlet.class);
	
	// Get the user's search keyword(s) from CGI variables
	String searchString = request.getParameter("searchString");
	logger.info("Received searchString [" + searchString + "]");

	// Start a Hibernate session.
	Session session = StartupDataLoader.openSession();
	
	// Create a Hibernate Search wrapper around the vanilla Hibernate session
	FullTextSession fullTextSession = Search.getFullTextSession(session);

	// Begin a transaction.  This may not be strictly necessary, but is a good practice in general.
	fullTextSession.beginTransaction();

	// Create a Hibernate Search QueryBuilder for the appropriate Lucene index (i.e. the index for "App" in this case)
	QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( App.class ).get();
	
	// Use the QueryBuilder to construct a Lucene keyword query... matching the user's search keywords against the "name" 
	// and "description" fields of App, as well as "name" field of associated Device entities, and the "comments" field of
	// embedded CustomerReview objects.
	org.apache.lucene.search.Query luceneQuery = queryBuilder
		.keyword()
		.onFields("name", "description", "supportedDevices.name", "customerReviews.comments")
		.matching(searchString)
		.createQuery();
	org.hibernate.Query hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, App.class);
	
	List<App> apps = hibernateQuery.list();
	logger.info("Found " + apps.size() + " apps");

	// Detach the results from the Hibernate session (to prevent unwanted interaction between the view layer 
	// and Hibernate when associated devices or embedded customer reviews are referenced)
	fullTextSession.clear();

	// Put the search results on the HTTP reqeust object
	request.setAttribute("apps", apps);

	// Close and clean up the Hibernate session
	fullTextSession.getTransaction().commit();
	session.close();
	
	// Forward the request object (including the search results) to the JSP/JSTL view for rendering
	getServletContext().getRequestDispatcher("/WEB-INF/pages/search.jsp").forward(request, response);
}
 
Example 8
Source File: SearchServlet.java    From maven-framework-project with MIT License 4 votes vote down vote up
/**
 * This method contains the primary search functionality for this servlet, and is automatically invoked once for every HTTP
 * POST to the mapped URL. 
 */
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	Logger logger = LoggerFactory.getLogger(SearchServlet.class);
	
	// Get the user's search keyword(s) from CGI variables
	String searchString = request.getParameter("searchString");
	logger.info("Received searchString [" + searchString + "]");

	// Start a Hibernate session.
	Session session = StartupDataLoader.openSession();
	
	// Create a Hibernate Search wrapper around the vanilla Hibernate session
	FullTextSession fullTextSession = Search.getFullTextSession(session);
	
	// Begin a transaction.  This may not be strictly necessary, but is a good practice in general.
	fullTextSession.beginTransaction();

	// Create a Hibernate Search QueryBuilder for the appropriate Lucene index (i.e. the index for "App" in this case)
	QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( App.class ).get();
	
	// Use the QueryBuilder to construct a Lucene keyword query, matching the user's search keywords against the name 
	// and description fields of App.
	org.apache.lucene.search.Query luceneQuery = queryBuilder
		.keyword()
		.onFields("name", "description")
		.matching(searchString)
		.createQuery();
	org.hibernate.Query hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, App.class);
	
	// Perform the search query, and put its results on the HTTP request object
	List<App> apps = 	hibernateQuery.list();
	logger.info("Found " + apps.size() + " search results");
	request.setAttribute("apps", apps);
    
	// Close and clean up the Hibernate session
	fullTextSession.getTransaction().commit();
	session.close();
	
	// Forward the request object (including the search results) to the JSP/JSTL view for rendering
	getServletContext().getRequestDispatcher("/WEB-INF/pages/search.jsp").forward(request, response);
}
 
Example 9
Source File: SearchServlet.java    From maven-framework-project with MIT License 4 votes vote down vote up
/**
 * This method contains the primary search functionality for this servlet, and is automatically invoked once for every HTTP
 * POST to the mapped URL. 
 */
@SuppressWarnings("unchecked")
@Override	
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	Logger logger = LoggerFactory.getLogger(SearchServlet.class);
	
	// Get the user's search keyword(s) from CGI variables
	String searchString = request.getParameter("searchString");
	logger.info("Received searchString [" + searchString + "]");

	// Start a Hibernate session.
	Session session = StartupDataLoader.openSession();
	
	// Create a Hibernate Search wrapper around the vanilla Hibernate session
	FullTextSession fullTextSession = Search.getFullTextSession(session);

	// Begin a transaction.  This may not be strictly necessary, but is a good practice in general.
	fullTextSession.beginTransaction();

	// Create a Hibernate Search QueryBuilder for the appropriate Lucene index (i.e. the index for "App" in this case)
	QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( App.class ).get();
	
	// Use the QueryBuilder to construct a Lucene keyword query... matching the user's search keywords against the "name" 
	// and "description" fields of App, as well as "name" field of associated Device entities, and the "comments" field of
	// embedded CustomerReview objects.
	org.apache.lucene.search.Query luceneQuery = queryBuilder
		.keyword()
		.onFields("name", "description", "supportedDevices.name", "customerReviews.comments")
		.matching(searchString)
		.createQuery();
	org.hibernate.Query hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, App.class);
	
	List<App> apps = hibernateQuery.list();
	logger.info("Found " + apps.size() + " apps");

	// Detach the results from the Hibernate session (to prevent unwanted interaction between the view layer 
	// and Hibernate when associated devices or embedded customer reviews are referenced)
	fullTextSession.clear();

	// Put the search results on the HTTP reqeust object
	request.setAttribute("apps", apps);

	// Close and clean up the Hibernate session
	fullTextSession.getTransaction().commit();
	session.close();
	
	// Forward the request object (including the search results) to the JSP/JSTL view for rendering
	getServletContext().getRequestDispatcher("/WEB-INF/pages/search.jsp").forward(request, response);
}