org.hibernate.Session Java Examples

The following examples show how to use org.hibernate.Session. 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: SandalphonDataMigrator.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
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 #2
Source File: NamedParameterUnitTest.java    From tutorials with 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 File: SbiUserDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #4
Source File: DBQueryUtil.java    From kardio with 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 #5
Source File: Subselect.java    From HibernateDemos with 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 #6
Source File: ParameterUseDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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
Source File: WarningServiceImpl.java    From fastdfs-zyc with GNU General Public License v2.0 6 votes vote down vote up
@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 File: AbstractCachingDemo.java    From HibernateDemos with 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
Source File: RMDBManager.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
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 File: HibernateServletFilter.java    From chipster with 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 #11
Source File: PlainVersionNumerationAdapter.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
@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 #12
Source File: I18NMessagesDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #13
Source File: BookDaoImpl.java    From LibrarySystem with 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 #14
Source File: MailAccountDAO.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #15
Source File: DaoUtils.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #16
Source File: HibernateLifecycleUnitTest.java    From tutorials with 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 #17
Source File: TargetDAOImpl.java    From webcurator with 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
Source File: ProductTypeDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #19
Source File: SbiJobSourceDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void insertJobSource(SbiMetaJobSource aMetaJobSource) throws EMFUserError {
	logger.debug("IN");

	Session aSession = null;
	Transaction tx = null;

	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		insertJobSource(aSession, aMetaJobSource);

		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();
		}
	}
	logger.debug("OUT");
}
 
Example #20
Source File: GeneratedUpdateTableStatementsTests.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Sets up which pre-existing tables that Hibernate sees.
 */
private void setupTestTables(String... tables) throws SQLException {
  mockConnection.setMetaData(MockJdbcUtils.metaDataBuilder().setTables(tables).build());

  Metadata metadata =
      new MetadataSources(this.registry)
          .addAnnotatedClass(Employee.class)
          .buildMetadata();

  Session session = metadata.buildSessionFactory().openSession();
  session.beginTransaction();
  session.close();
}
 
Example #21
Source File: TimespanDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #22
Source File: MetaData.java    From dkpro-jwpl with Apache License 2.0 5 votes vote down vote up
/**
 * @return The number of pages in the current Wikipedia.
 */
public long getNumberOfPages()
{
	Session session = this.wiki.__getHibernateSession();
	session.beginTransaction();
	session.lock(hibernateMetaData, LockMode.NONE);
	long nrofPages = hibernateMetaData.getNrofPages();
	session.getTransaction().commit();
	return nrofPages;
}
 
Example #23
Source File: TestSchemaTools.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testFailingQuoteValidation() throws Exception{
	// database schema have been created thanks to the setUp method
	// we have 2 schemas SA et SB, SB must be set as the default schema
	// used by hibernate hibernate.default_schema SB
	SchemaExport se = new SchemaExport(getCfg());
	se.create(true,true);
	
	// here we modify the generated table in order to test SchemaUpdate
	Session session = openSession();
	Connection conn = session.connection();
	Statement stat = conn.createStatement();
	stat.execute("ALTER TABLE \"SB\".\"Team\" DROP COLUMN name ");
	
	// update schema
	//SchemaUpdate su = new SchemaUpdate(getCfg());
	//su.execute(true,true);
	
	try {
		SchemaValidator sv = new SchemaValidator(getCfg());
		sv.validate();
		fail("should fail since we mutated the current schema.");
	} catch(HibernateException he) {
		
	}
	
	// it's time to clean our database
	se.drop(true,true);
	
	// then the schemas and false table.

	stat.execute("DROP TABLE \"SA\".\"Team\" ");
	stat.execute(" DROP SCHEMA sa ");
	stat.execute("DROP SCHEMA sb ");
	stat.close();
	session.close();
}
 
Example #24
Source File: AbstractGeneratedPropertyTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public final void testGeneratedProperty() {
	GeneratedPropertyEntity entity = new GeneratedPropertyEntity();
	entity.setName( "entity-1" );
	Session s = openSession();
	Transaction t = s.beginTransaction();
	s.save( entity );
	s.flush();
	assertNotNull( "no timestamp retrieved", entity.getLastModified() );
	t.commit();
	s.close();

	byte[] bytes = entity.getLastModified();

	s = openSession();
	t = s.beginTransaction();
	entity = ( GeneratedPropertyEntity ) s.get( GeneratedPropertyEntity.class, entity.getId() );
	assertTrue( Hibernate.BINARY.isEqual( bytes, entity.getLastModified() ) );
	t.commit();
	s.close();

	assertTrue( Hibernate.BINARY.isEqual( bytes, entity.getLastModified() ) );

	s = openSession();
	t = s.beginTransaction();
	s.delete( entity );
	t.commit();
	s.close();
}
 
Example #25
Source File: HibernateTemplate.java    From spring4-understanding with 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 #26
Source File: TransactionAwareSessionContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Creates a transaction synchronization object for the specified session.
    *
    * @param session
    *            Session to synchronize using the created object. Cannot be null.
    * @return A valid transaction synchronization. Never returns null.
    */
   private TransactionSynchronization createTransactionSynchronization(final Session session) {
return new TransactionSynchronizationAdapter() {
    @Override
    public void afterCompletion(final int status) {
	session.close();
	ManagedSessionContext.unbind(sessionFactory);
    }
};
   }
 
Example #27
Source File: SbiMetaJobDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Checks for tables associated.
 *
 * @param sourceId
 *            the metatable id
 *
 * @return true, if checks for tables associated
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.metadata.dao.ISbiMetaJobDAOHibImpl#hasTablesAssociated(int)
 */
@Override
public boolean hasTablesAssociated(Integer id) throws EMFUserError {
	boolean bool = false;

	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		String hql = " from SbiMetaJobSource s where s.id.jobId = ?";
		Query aQuery = tmpSession.createQuery(hql);
		aQuery.setInteger(0, id);

		List bcAssociated = aQuery.list();
		if (bcAssociated.size() > 0)
			bool = true;
		else
			bool = false;
		tx.commit();
	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {
		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}
	}
	return bool;
}
 
Example #28
Source File: IntegrationTestBase.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void bindSession()
{
    SessionFactory sessionFactory = (SessionFactory) webApplicationContext.getBean( "sessionFactory" );
    Session session = sessionFactory.openSession();
    session.setHibernateFlushMode(FlushMode.ALWAYS);
    TransactionSynchronizationManager.bindResource( sessionFactory, new SessionHolder( session ) );
}
 
Example #29
Source File: SoapboxDao.java    From soapbox-race with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<ISoapBoxEntity> find(ISoapBoxEntity entity) {
	EntityManager manager = ConnectionDB.getManager();
	manager.clear();
	Session sessao = (Session) manager.getDelegate();
	Example example = Example.create(entity);
	example.excludeZeroes();
	Criteria criteria = sessao.createCriteria(entity.getClass());
	criteria.add(example);
	return criteria.list();
}
 
Example #30
Source File: CourseStudentService.java    From zevencourse with GNU General Public License v3.0 5 votes vote down vote up
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,"录入成绩失败");
}