Java Code Examples for org.hibernate.Session

The following examples show how to use org.hibernate.Session. These examples are extracted from open source projects. 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
@Override
public void updateSbiUserAttributes(SbiUserAttributes attribute) {
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		aSession.saveOrUpdate(attribute);
		aSession.flush();
		tx.commit();
	} catch (HibernateException he) {
		if (tx != null)
			tx.rollback();
		throw new SpagoBIDAOException("Error while update user attribute " + attribute, he);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
}
 
Example 2
Source Project: tutorials   Source File: NamedParameterUnitTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .configure()
            .build();
    try {
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(new Event("Event 1"));
        session.save(new Event("Event 2"));
        session.getTransaction().commit();
        session.close();
    } catch (Exception e) {
        fail(e);
        StandardServiceRegistryBuilder.destroy(registry);
    }
}
 
Example 3
Source Project: kardio   Source File: DBQueryUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the Component Id from Component Name.
 * 
 * @param compName
 * @return
 */
private static int getComponentIdFromCompName(String compName){
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	Criteria componentCriteria = session.createCriteria(ComponentEntity.class);
	componentCriteria.add(Restrictions.eq("componentName",compName));
	componentCriteria.add(Restrictions.eq("delInd", 0));
	componentCriteria.setMaxResults(1);
	ComponentEntity com =(ComponentEntity) componentCriteria.uniqueResult();
	int compId = 0;
	if(com != null){
		compId = com.getComponentId();
	}
	txn.commit();
	return compId;
}
 
Example 4
Source Project: HibernateDemos   Source File: Subselect.java    License: The Unlicense 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<User> getUsers() {
	final Session session = openSession();
	session.getTransaction().begin();

	final List<User> users = session
			.createCriteria( User.class )
			.add( Restrictions.gt( "id", 0 ) )
			.list();
	
	// init (#skills uses @Fetch(SUBSELECT))
	users.get( 0 ).getSkills().size();
	// NOTE: All skills, for all returned Users, will be initialized automatically!!!

	session.getTransaction().commit();
	return users;
}
 
Example 5
@Override
public List<SbiProductType> loadAllProductType() {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		String q = "from SbiProductType";
		Query query = aSession.createQuery(q);
		ArrayList<SbiProductType> result = (ArrayList<SbiProductType>) query.list();
		return result;
	} catch (HibernateException he) {
		logger.error(he.getMessage(), he);
		if (tx != null)
			tx.rollback();
		throw new SpagoBIRuntimeException("Error getting product types", he);
	} finally {
		logger.debug("OUT");
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
}
 
Example 6
/**
 * Load by id.
 *
 * @param id
 *            the id
 *
 * @return the sbi paruse
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IParameterUseDAO#loadById(java.lang.Integer)
 */
@Override
public SbiParuse loadById(Integer id) throws EMFUserError {
	SbiParuse toReturn = null;
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		toReturn = (SbiParuse) aSession.load(SbiParuse.class, id);
		tx.commit();
	} catch (HibernateException he) {
		logException(he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	return toReturn;
}
 
Example 7
@Override
@Transactional(propagation = Propagation.REQUIRED)
public List<WarningData> findWarning(WarningData wd,PageInfo pageInfo) throws IOException, MyException {
    //To change body of implemented methods use File | Settings | File Templates.
    List<WarningData> warningDatas = new ArrayList<WarningData>();
    Session session = getSession();
    StringBuilder queryString = new StringBuilder("from WarningData as wd ");
    if(!StringUtils.isNullOrEmpty(wd.getWdIpAddr())){
        queryString.append("where wd.wdIpAddr like '%"+wd.getWdIpAddr()+"%'");
    }
    Query query = session.createQuery(queryString.toString());
    pageInfo.setTotalCount(query.list().size());
    query.setMaxResults(pageInfo.getNumPerPage());
    query.setFirstResult((pageInfo.getPageNum()-1)*pageInfo.getNumPerPage());
    warningDatas = query.list();
    return warningDatas;
}
 
Example 8
Source Project: HibernateDemos   Source File: AbstractCachingDemo.java    License: The Unlicense 6 votes vote down vote up
public long persistData() {
	final Project project = new Project();
	project.setName( "Foo Project" );
	final User user = new User();
	user.setName( "Brett Meyer" );
	final Skill skill = new Skill();
	skill.setName( "Hibernate ORM" );
	user.getSkills().add( skill );
	user.getProjects().add( project );
	project.setAssignee( user );
	
	final Session s = openSession();
	s.getTransaction().begin();
	s.persist(skill);
	s.persist(user);
	s.persist(project);
	s.getTransaction().commit();
	s.close();
	
	return project.getId();
}
 
Example 9
public Collection<RMNodeData> getNodesByNodeSource(final String nodeSourceName) {
    logger.debug(REQUEST_BUFFER_STRING + "retrieve node with node source name " + nodeSourceName +
                 IN_DATABASE_STRING);
    rmdbManagerBuffer.debounceNodeUpdatesIfNeeded();
    try {
        logger.debug("Retrieve nodes from node source " + nodeSourceName + IN_DATABASE_STRING);
        return executeReadTransaction(new SessionWork<Collection<RMNodeData>>() {
            @Override
            @SuppressWarnings("unchecked")
            public Collection<RMNodeData> doInTransaction(Session session) {
                Query query = session.getNamedQuery("getRMNodeDataByNodeSource").setParameter("name",
                                                                                              nodeSourceName);
                return (Collection<RMNodeData>) query.list();
            }
        });
    } catch (RuntimeException e) {
        throw new RuntimeException("Exception occurred while getting node by node source name " + nodeSourceName,
                                   e);
    }
}
 
Example 10
Source Project: tutorials   Source File: HibernateLifecycleUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenTransientEntity_whenSave_thenManaged() throws Exception {
    SessionFactory sessionFactory = HibernateLifecycleUtil.getSessionFactory();
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = startTransaction(session);

        FootballPlayer neymar = new FootballPlayer();
        neymar.setName("Neymar");

        session.save(neymar);
        assertThat(getManagedEntities(session)).size().isEqualTo(1);
        assertThat(neymar.getId()).isNotNull();

        int count = queryCount("select count(*) from Football_Player where name='Neymar'");
        assertThat(count).isEqualTo(0);

        transaction.commit();

        count = queryCount("select count(*) from Football_Player where name='Neymar'");
        assertThat(count).isEqualTo(1);

        transaction = startTransaction(session);
        session.delete(neymar);
        transaction.commit();
    }
}
 
Example 11
Source Project: chipster   Source File: HibernateServletFilter.java    License: MIT License 6 votes vote down vote up
public void destroy()
{
	logger.debug("Destroying HibernateServletFilter");
	final Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	
	if (session.getTransaction().isActive())
	{
		logger.debug("Committing the final active transaction");
		session.getTransaction().commit();
	}

	if (session.isOpen())
	{
		logger.debug("Closing the final open session");
		session.close();
	}
}
 
Example 12
@Override
public String getNextVersionNumber(Session session, NodeDocument nDoc, NodeDocumentVersion nDocVer, int increment) {
	String versionNumber = nDocVer.getName();
	int nextVerNumber = Integer.parseInt(versionNumber);
	Query q = session.createQuery(qs);
	NodeDocumentVersion ndv = null;

	do {
		nextVerNumber++;
		q.setString("parent", nDoc.getUuid());
		q.setString("name", String.valueOf(nextVerNumber));
		ndv = (NodeDocumentVersion) q.setMaxResults(1).uniqueResult();
	} while (ndv != null);

	return String.format(Config.VERSION_NUMERATION_FORMAT, nextVerNumber);
}
 
Example 13
private List<SbiI18NMessages> getSbiI18NMessagesByLabel(SbiI18NMessages message, String tenant, Session curSession) {
	logger.debug("IN");
	List<SbiI18NMessages> toReturn = new ArrayList<SbiI18NMessages>();
	try {
		String hql = "from SbiI18NMessages m where m.label = :label and m.commonInfo.organization = :organization and m.languageCd != :languageCd";
		Query query = curSession.createQuery(hql);
		query.setString("label", message.getLabel());
		query.setString("organization", tenant);
		query.setInteger("languageCd", message.getLanguageCd());
		toReturn = query.list();
	} catch (HibernateException e) {
		logException(e);
		throw new RuntimeException();
	}
	logger.debug("OUT");
	return toReturn;
}
 
Example 14
Source Project: LibrarySystem   Source File: BookDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param hql传入的hql语句
 * @param pageCode当前页
 * @param pageSize每页显示大小
 * @return
 */
public List doSplitPage(final String hql,final int pageCode,final int pageSize){
    //调用模板的execute方法,参数是实现了HibernateCallback接口的匿名类,
    return (List) this.getHibernateTemplate().execute(new HibernateCallback(){
        //重写其doInHibernate方法返回一个object对象,
        public Object doInHibernate(Session session)
                throws HibernateException, SQLException {
            //创建query对象
            Query query=session.createQuery(hql);
            //返回其执行了分布方法的list
            return query.setFirstResult((pageCode-1)*pageSize).setMaxResults(pageSize).list();
             
        }
         
    });
     
}
 
Example 15
/**
 * Update
 */
public static void updateRule(MailFilterRule fr) throws DatabaseException {
	log.debug("updateRule({})", fr);
	Session session = null;
	Transaction tx = null;

	try {
		session = HibernateUtil.getSessionFactory().openSession();
		tx = session.beginTransaction();
		session.update(fr);
		HibernateUtil.commit(tx);
	} catch (HibernateException e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	} finally {
		HibernateUtil.close(session);
	}

	log.debug("updateRule: void");
}
 
Example 16
public static void optimize ()
{
   HibernateDaoLocalSupport support = ApplicationContextProvider.getBean (
         HibernateDaoLocalSupport.class);
   support.getHibernateTemplate ().flush ();
   support.getHibernateTemplate ().executeWithNativeSession (
      new HibernateCallback<Void> ()
      {
         @Override
         public Void doInHibernate (Session session) throws
               HibernateException, SQLException
         {
            SQLQuery query = session.createSQLQuery ("CHECKPOINT DEFRAG");
            query.executeUpdate ();
            return null;
         }
      });
}
 
Example 17
Source Project: webcurator   Source File: TargetDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find all the groups that need to be end dated.
 * @return A List of groups to be end dated.
 */
@SuppressWarnings("unchecked")
public List<TargetGroup> findEndedGroups() {
	return getHibernateTemplate().executeFind(new HibernateCallback() {
		public Object doInHibernate(Session aSession) throws HibernateException, SQLException {
			List<TargetGroup> results = aSession.createCriteria(TargetGroup.class)
				.add(Restrictions.ne("state", TargetGroup.STATE_ACTIVE))
				.add(Restrictions.lt("toDate", new Date()))
				.setFetchMode("schedules", FetchMode.JOIN)
				.setFetchMode("parents", FetchMode.JOIN)
				.setFetchMode("children", FetchMode.JOIN)
				.list();
			
			log.debug("Found " + results.size() + " groups that need to be unscheduled");
			
			return results;
		}
	});
}
 
Example 18
private void migrateV1toV2() throws SQLException {
    SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class);
    Connection connection = session.getJdbcConnectionAccess().obtainConnection();

    String programmingSubmissionTable = "sandalphon_submission_programming";
    String newProgrammingSubmissionTable = "sandalphon_programming_submission";
    String bundleSubmissionTable = "sandalphon_submission_bundle";
    String newBundleSubmissionTable = "sandalphon_bundle_submission";
    Statement statement = connection.createStatement();

    statement.execute("ALTER TABLE " + programmingSubmissionTable + " CHANGE contestJid containerJid VARCHAR(255);");
    statement.execute("ALTER TABLE " + bundleSubmissionTable + " CHANGE contestJid containerJid VARCHAR(255);");

    statement.execute("DROP TABLE " + newProgrammingSubmissionTable + ";");
    statement.execute("DROP TABLE " + newBundleSubmissionTable + ";");

    statement.execute("RENAME TABLE " + programmingSubmissionTable + " TO " + newProgrammingSubmissionTable + ";");
    statement.execute("RENAME TABLE " + bundleSubmissionTable + " TO " + newBundleSubmissionTable + ";");
}
 
Example 19
/**
 * Get value of failed login attemtpts counter from DB.
 *
 * @author Marco Libanori
 */
@Override
public int getFailedLoginAttempts(String userId) {
	logger.debug("IN");

	Session aSession = null;
	Transaction tx = null;
	try {

		Integer result = 0;

		if (isUserIdAlreadyInUse(userId) != null) {

			aSession = getSession();
			tx = aSession.beginTransaction();

			ProjectionList projList = Projections.projectionList().add(Projections.property("failedLoginAttempts"), "failedLoginAttempts");

			SimpleExpression eq = Restrictions.eq("userId", userId);

			result = (Integer) aSession.createCriteria(SbiUser.class).add(eq).setProjection(projList).uniqueResult();

			tx.commit();
		}

		return result;
	} catch (HibernateException he) {
		if (tx != null)
			tx.rollback();
		throw new SpagoBIDAOException("Error while reading failed login attempts counter for user " + userId, he);
	} finally {
		logger.debug("OUT");
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
}
 
Example 20
Source Project: dkpro-jwpl   Source File: Category.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return The set of article ids that are categorized under this category.
 */
public Set<Integer> getArticleIds() {
    Session session = this.wiki.__getHibernateSession();
    session.beginTransaction();
    session.lock(hibernateCategory, LockMode.NONE);
    Set<Integer> tmpSet = new HashSet<Integer>(hibernateCategory.getPages());
    session.getTransaction().commit();

    return tmpSet;
}
 
Example 21
Source Project: sakai   Source File: PagePresenceDaoImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
public List findBySpaceOnly(final String pageSpace, final String pageName)
{
	long start = System.currentTimeMillis();
	try
	{
		// there is no point in sorting by version, since there is only one
		// version in
		// this table.
		// also using like is much slower than eq
		HibernateCallback callback = new HibernateCallback()
		{
			public Object doInHibernate(Session session)
					throws HibernateException
			{
				return session.createCriteria(PagePresence.class).add(
						Expression.eq("pagespace", pageSpace))
						.add(
								Expression.not(Expression.eq("pagename",
										pageName))).addOrder(
								Order.desc("lastseen")).list();
			}
		};
		List l = (List) getHibernateTemplate().execute(callback);
		log.info("Found " + l.size() + " in " + pageSpace + " : "
				+ pageName);
		return l;
	}
	finally
	{
		long finish = System.currentTimeMillis();
		TimeLogger.printTimer("PagePresenceDaoImpl.findBySpaceOnly: "
				+ pageSpace + " :" + pageName, start, finish);
	}
}
 
Example 22
Source Project: hibernate-types   Source File: PostgreSQLInetTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJDBCQuery() {
    doInJPA(new JPATransactionFunction<Void>() {

        @Override
        public Void apply(EntityManager entityManager) {
            Session session = entityManager.unwrap(Session.class);
            session.doWork(new Work() {
                @Override
                public void execute(Connection connection) throws SQLException {
                    PreparedStatement ps = null;
                    try {

                        ps = connection.prepareStatement(
                            "SELECT * " +
                            "FROM Event e " +
                            "WHERE " +
                            "   e.ip && ?::inet = true"
                        );

                        ps.setObject(1, "192.168.0.1/24");
                        ResultSet rs = ps.executeQuery();
                        while(rs.next()) {
                            Long id = rs.getLong(1);
                            String ip = rs.getString(2);
                            assertEquals("192.168.0.123/24", ip);
                        }
                    } finally {
                        if (ps != null) {
                            ps.close();
                        }
                    }
                }
            });

            return null;
        }
    });
}
 
Example 23
private TrackerTypeReport handleRelationships( Session session, TrackerBundle bundle )
{
    List<Relationship> relationships = bundle.getRelationships();
    TrackerTypeReport typeReport = new TrackerTypeReport( TrackerType.RELATIONSHIP );

    relationships.forEach( o -> bundleHooks.forEach( hook -> hook.preCreate( Relationship.class, o, bundle ) ) );

    for ( int idx = 0; idx < relationships.size(); idx++ )
    {
        Relationship relationship = relationships.get( idx );
        org.hisp.dhis.relationship.Relationship toRelationship = relationshipTrackerConverterService
            .from( bundle.getPreheat(), relationship );

        TrackerObjectReport objectReport = new TrackerObjectReport( TrackerType.EVENT, toRelationship.getUid(),
            idx );
        typeReport.addObjectReport( objectReport );

        Date now = new Date();

        if ( bundle.getImportStrategy().isCreate() )
        {
            toRelationship.setCreated( now );
        }

        toRelationship.setLastUpdated( now );
        toRelationship.setLastUpdatedBy( bundle.getUser() );

        session.persist( toRelationship );
        typeReport.getStats().incCreated();

        if ( FlushMode.OBJECT == bundle.getFlushMode() )
        {
            session.flush();
        }
    }

    relationships.forEach( o -> bundleHooks.forEach( hook -> hook.postCreate( Relationship.class, o, bundle ) ) );

    return typeReport;
}
 
Example 24
Source Project: spring4-understanding   Source File: HibernateTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<?> findByNamedQueryAndValueBean(final String queryName, final Object valueBean)
		throws DataAccessException {

	return executeWithNativeSession(new HibernateCallback<List<?>>() {
		@Override
		public List<?> doInHibernate(Session session) throws HibernateException {
			Query queryObject = session.getNamedQuery(queryName);
			prepareQuery(queryObject);
			queryObject.setProperties(valueBean);
			return queryObject.list();
		}
	});
}
 
Example 25
@Override
public List<SbiTimespan> listDynTimespan() {
	return list(new ICriterion<SbiTimespan>() {
		@Override
		public Criteria evaluate(Session session) {
			Criteria c = session.createCriteria(SbiTimespan.class);
			c.add(Restrictions.eq("staticFilter", false));
			return c;
		}
	});
}
 
Example 26
public Message recordGrade(int tid, int cid, int sid, double grade){
    Session session = getSession();
    if(session.createQuery("FROM TeacherCourse WHERE tid = (:tid) and cid = (:cid)")
            .setParameter("tid",tid)
            .setParameter("cid",cid).list().size()==0)
        return new Message(-1,"您非此课程的授课教师,无法录入成绩");
    Transaction tx = session.beginTransaction();
    int row = session.createQuery("UPDATE CourseStudent SET grade = (:grade) WHERE cid = (:cid) and sid = (:sid)")
            .setParameter("grade",grade)
            .setParameter("cid",cid)
            .setParameter("sid",sid)
            .executeUpdate();
    tx.commit();
    return row>0?new Message(1,"ok"):new Message(-2,"录入成绩失败");
}
 
Example 27
Source Project: hibernate-types   Source File: OracleJsonBinaryTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void afterInit() {
    doInJPA(new JPATransactionFunction<Void>() {
        @Override
        public Void apply(EntityManager entityManager) {
            entityManager.unwrap(Session.class).doWork(new Work() {
                @Override
                public void execute(Connection connection) throws SQLException {
                    Statement statement = null;
                    try {
                        statement = connection.createStatement();

                        statement.executeUpdate(
                            "ALTER TABLE event MOVE LOB (location) STORE AS (CACHE)"
                        );

                        statement.executeUpdate(
                            "ALTER TABLE participant MOVE LOB (ticket, metadata) STORE AS (CACHE)"
                        );
                    } finally {
                        if(statement != null) {
                            statement.close();
                        }
                    }
                }
            });

            return null;
        }
    });
}
 
Example 28
Source Project: webcurator   Source File: SiteDAOImpl.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Site> listSitesByTitle(final String aTitle) {		
	Object o = getHibernateTemplate().execute(new HibernateCallback() {
		public Object doInHibernate(final Session session) {
			Query query = session.createQuery("from Site s where lower(s.title) = :siteTitle");
			query.setString("siteTitle", aTitle);
			
			return query.list();
		}
	});
	
	return (List<Site>) o;
}
 
Example 29
Source Project: uyuni   Source File: KickstartFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup a crypto key by its id.
 * @param keyId to lookup
 * @param org who owns the key
 * @return CryptoKey if found.  Null if not
 */
public static CryptoKey lookupCryptoKeyById(Long keyId, Org org) {
    Session session = null;
    CryptoKey retval = null;
    //look for Kickstart data by id
    session = HibernateFactory.getSession();
    retval = (CryptoKey) session.getNamedQuery("CryptoKey.findByIdAndOrg")
            .setLong("key_id", keyId.longValue())
            .setLong("org_id", org.getId().longValue())
            .uniqueResult();
    return retval;
}
 
Example 30
@Override
public boolean deleteProgressThread(Integer progressThreadId) throws EMFUserError {
	// logger.debug("IN");

	boolean found = false;

	Session aSession = null;
	Transaction tx = null;

	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		Query hibPT = aSession.createQuery("from SbiProgressThread h where h.progressThreadId = ? ");
		hibPT.setInteger(0, progressThreadId);
		Object sbiProgressThreadO = hibPT.uniqueResult();

		if (sbiProgressThreadO != null) {
			SbiProgressThread pT = (SbiProgressThread) sbiProgressThreadO;
			found = true;
			aSession.delete(pT);
			tx.commit();
		}

	} catch (HibernateException he) {
		logger.error("Error while deletering Progress Thread with progressThreadId = " + progressThreadId, he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
			// logger.debug("OUT");
		}
	}
	// logger.debug("OUT");
	return found;
}