Java Code Examples for org.hibernate.Session.delete()

The following are Jave code examples for showing how to use delete() of the org.hibernate.Session class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: bdf2   File: HibernateComponentConfigManager.java   Source Code and License Vote up 6 votes
@SuppressWarnings("unchecked")
public void deleteComponentProfileByControlId(String controlId, String name) {
	DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ComponentConfig.class);
	detachedCriteria.add(Restrictions.eq("controlId", controlId));
	detachedCriteria.add(Restrictions.eq("name", name));
	Session session = this.getSessionFactory().openSession();
	try {
		org.hibernate.Criteria criteria = detachedCriteria.getExecutableCriteria(session);
		List<ComponentConfig> list = criteria.list();
		if (list.size() > 0) {
			String hql = "delete " + ComponentConfigMember.class.getName()
					+ " m where m.componentConfig.id = :configId";
			session.createQuery(hql).setString("configId", list.get(0).getId()).executeUpdate();
			session.delete(list.get(0));
		}
	} finally {
		session.flush();
		session.close();
	}
}
 
Example 2
Project: bdf2   File: DeleteProcessController.java   Source Code and License Vote up 6 votes
@Override
protected ModelAndView doHandleRequest(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	String lobId=request.getParameter("lobId");
	String deploymentId=request.getParameter("deploymentId");
	String id=request.getParameter("id");
	DesignerProcess process=new DesignerProcess();
	process.setId(id);
	Session session=hibernateDao.getSessionFactory().openSession();
	try{
		session.delete(process);
		lobStoreService.deleteString(lobId);
		bpmService.deleteDeployment(deploymentId);
	}finally{
		session.flush();
		session.close();
	}
	return null;
}
 
Example 3
Project: unitimes   File: Exam.java   Source Code and License Vote up 6 votes
public String unassign(String managerExternalId, Session hibSession) {
    Transaction tx = null;
    try {
        if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive())
            tx = hibSession.beginTransaction();
        
        ExamAssignment oldAssignment = new ExamAssignment(this);
        
        setAssignedPeriod(null);
        if (getAssignedRooms()==null) setAssignedRooms(new HashSet());
        getAssignedRooms().clear();
        setAssignedPreference(null);
        
        HashSet otherExams = new HashSet();
        
        for (Iterator j=getConflicts().iterator();j.hasNext();) {
            ExamConflict conf = (ExamConflict)j.next();
            for (Iterator i=conf.getExams().iterator();i.hasNext();) {
                Exam x = (Exam)i.next();
                if (!x.equals(this)) {
                    x.getConflicts().remove(conf);
                    otherExams.add(x);
                }
            }
            hibSession.delete(conf);
            j.remove();
        }

        ExamEvent event = getEvent();
        if (event!=null) hibSession.delete(event);
        
        hibSession.update(this);
        for (Iterator i=otherExams.iterator();i.hasNext();)
            hibSession.update((Exam)i.next());
        
        SubjectArea subject = null;
        Department dept = null;
        for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
            ExamOwner owner = (ExamOwner)i.next();
            subject = owner.getCourse().getSubjectArea();
            dept = subject.getDepartment();
            break;
        }
        
        ChangeLog.addChange(hibSession,
                TimetableManager.findByExternalId(managerExternalId),
                getSession(),
                this,
                getName()+" ("+
                (oldAssignment.getPeriod()==null?"N/A":oldAssignment.getPeriodAbbreviation()+" "+oldAssignment.getRoomsName(", "))+
                " &rarr; N/A)",
                ChangeLog.Source.EXAM_INFO,
                ChangeLog.Operation.UNASSIGN,
                subject,
                dept);

        if (tx!=null) tx.commit();
        return null;
    } catch (Exception e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
        return "Unassignment of "+getName()+" failed, reason: "+e.getMessage();
    }
}
 
Example 4
Project: unitimes   File: StandardEventNotes.java   Source Code and License Vote up 5 votes
protected void delete(StandardEventNote note, SessionContext context, Session hibSession) {
	if (note == null) return;
	ChangeLog.addChange(hibSession,
			context,
			note,
			note.getLabel(),
			Source.SIMPLE_EDIT, 
			Operation.DELETE,
			null,
			note instanceof StandardEventNoteDepartment ? ((StandardEventNoteDepartment)note).getDepartment() : null);
	hibSession.delete(note);
}
 
Example 5
Project: bdf2   File: ReportMaintain.java   Source Code and License Vote up 5 votes
@DataResolver
public void saveDefinitions(Collection<ReportDefinition> definitions){
	Session session=this.getSessionFactory().openSession();
	try{
		IFileService fileService=ContextHolder.getBean(IFileService.BEAN_ID);
		for(ReportDefinition definition:definitions){
			EntityState state=EntityUtils.getState(definition);
			if(state.equals(EntityState.NEW)){
				definition.setCreateDate(new Date());
				session.save(definition);
			}
			if(state.equals(EntityState.MODIFIED)){
				session.update(definition);
			}
			if(state.equals(EntityState.DELETED)){
				fileService.deleteUploadDefinition(definition.getReportFile());
				String hql="delete "+ReportParameter.class.getName()+" where reportDefinitionId=:definitionId";
				session.createQuery(hql).setString("definitionId", definition.getId()).executeUpdate();
				hql="delete "+ReportResource.class.getName()+" where reportDefinitionId=:definitionId";
				session.createQuery(hql).setString("definitionId", definition.getId()).executeUpdate();
				session.delete(definition);
			}
			if(definition.getParameters()!=null){
				this.saveParameters(definition.getParameters());
			}
			if(definition.getResources()!=null){
				this.saveResources(definition.getResources());
			}
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 6
Project: bdf2   File: GroupMaintain.java   Source Code and License Vote up 5 votes
@DataResolver
public void saveGroups(Collection<Group> groups) throws Exception{
	IUser user=ContextHolder.getLoginUser();
	if(user==null){
		throw new NoneLoginException("Please login first");
	}
	String companyId=user.getCompanyId();
	if(StringUtils.isNotEmpty(getFixedCompanyId())){
		companyId=getFixedCompanyId();
	}
	Session session=this.getSessionFactory().openSession();
	try{
		for(Group g:groups){
			EntityState state=EntityUtils.getState(g);
			if(state.equals(EntityState.NEW)){
				g.setId(UUID.randomUUID().toString());
				g.setCompanyId(companyId);
				g.setCreateDate(new Date());
				session.save(g);
			}else if(state.equals(EntityState.MODIFIED)){
				session.update(g);
			}else if(state.equals(EntityState.DELETED)){
				roleService.deleteRoleMemeber(g.getId(), MemberType.Group);
				groupService.deleteGroupMemeber(g.getId(), MemberType.Group);
				session.delete(g);
			}
		}
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 7
Project: unitimes   File: InstructorAttributeTypes.java   Source Code and License Vote up 5 votes
protected void delete(InstructorAttributeType type, SessionContext context, Session hibSession) {
	if (type == null) return;
	ChangeLog.addChange(hibSession,
			context,
			type,
			type.getReference(),
			Source.SIMPLE_EDIT, 
			Operation.DELETE,
			null,
			null);
	hibSession.delete(type);
}
 
Example 8
Project: docker-restful-java   File: ChannelController.java   Source Code and License Vote up 5 votes
/**
 * Delete a Channel
 * @param id channel ID.
 * @return A response.
 */
@DELETE
@Path("{id}/")
public Response destroy(@PathParam("id") Long id) {
    LOGGER.info("#DELETE " + id);
    Response response = null;
    if (this.authorization) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            Channel channel = session.get(Channel.class, id);

            if (channel == null) {
                response = Error.notFound(String.valueOf(id))
                        .getResponse();
                LOGGER.warning("#DELETE {" + id + "} " + response.toString());
            } else {
                session.delete(channel);
                response = Response
                        .ok(channel)
                        .build();
                LOGGER.info("#DELETE {" + id + "} " + response.toString());
            }
            session.getTransaction().commit();
            session.close();
        } catch (Exception exception) {
            response = Error.internalServer(exception)
                    .getResponse();
            LOGGER.warning("#DELETE {" + id + "} " + exception.getLocalizedMessage());
            session.getTransaction().rollback();
        }
    } else {
        response = this.getUnauthorization();
    }
    return response;
}
 
Example 9
Project: unitimes   File: Majors.java   Source Code and License Vote up 5 votes
protected void delete(PosMajor major, SessionContext context, Session hibSession) {
	if (major == null) return;
	ChangeLog.addChange(hibSession,
			context,
			major,
			major.getCode() + " " + major.getName(),
			Source.SIMPLE_EDIT, 
			Operation.DELETE,
			null,
			null);
	hibSession.delete(major);		
}
 
Example 10
Project: OSWf-OSWorkflow-fork   File: HibernatePersistentVarsDAO.java   Source Code and License Vote up 5 votes
public void remove(Long piid) {

        if( piid == null)
            throw new PersistentVarsException("Could not remove properties for 'null' piid");

        Session session = null;
        Transaction transaction = null;

        try  {
            session = this.sessionFactory.openSession();
            transaction = session.beginTransaction();

            Collection<String> keys = getKeys(piid, null, null);

            for(String key : keys)
                session.delete(getItem(session, piid, key));

            transaction.commit();
            
        } catch( HibernateException hibernateException ) {
            throw new PersistentVarsException("Could not remove all keys: " + hibernateException.getMessage());
        } finally {
            // Rollback if 'commit' failed 
            if(transaction != null && transaction.isActive())
                transaction.rollback();

            if (session != null) 
                session.close();
        }
    }
 
Example 11
Project: bdf2   File: FileServiceImpl.java   Source Code and License Vote up 5 votes
public void deleteUploadDefinition(String id) {
	Session session=this.getSessionFactory().openSession();
	try{
		UploadDefinition definition=(UploadDefinition)session.get(UploadDefinition.class, id);
		if(definition==null){
			throw new RuntimeException("Upload definition ["+id+"] is not exist!");
		}
		if(StringUtils.isEmpty(definition.getUploadProcessorKey())){
			throw new RuntimeException("Upload definition ["+definition.getId()+"] has not set processor!");
		}
		String key=definition.getUploadProcessorKey();
		IFileProcessor targetProcessor=null;
		for(IFileProcessor processor:processors){
			if(processor.key().equals(key)){
				targetProcessor=processor;
				break;
			}
		}
		if(targetProcessor==null){
			throw new RuntimeException("The processor ["+key+"] is not exist!");
		}
		targetProcessor.deleteFile(definition);
		session.delete(definition);
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 12
Project: uflo   File: ExecuteEndNodeCommand.java   Source Code and License Vote up 5 votes
private void removeProcessInstances(ProcessInstance pi,Session session){
	long pid=pi.getParentId();
	if(pid>0){
		ProcessInstance parent=(ProcessInstance)session.get(ProcessInstance.class, pid);
		parent.setState(ProcessInstanceState.End);
		session.delete(parent);
		removeProcessInstances(parent,session);
	}
}
 
Example 13
Project: unitimes   File: InstructionalOfferingModifyAction.java   Source Code and License Vote up 5 votes
private void deleteClasses(InstructionalOfferingModifyForm frm, InstrOfferingConfig ioc, Session hibSession, HashMap tmpClassIdsToRealClasses){
 	if (ioc.getSchedulingSubparts() != null) {
SchedulingSubpart ss = null;
ArrayList lst = new ArrayList();
      ArrayList subpartList = new ArrayList(ioc.getSchedulingSubparts());
      Collections.sort(subpartList, new SchedulingSubpartComparator());

      for(Iterator it = subpartList.iterator(); it.hasNext();){
      	ss = (SchedulingSubpart) it.next();
      	if (ss.getParentSubpart() == null){
      		buildClassList(ss.getClasses(), lst);
      	}
      }

      Class_ c;
      for (int i = (lst.size() - 1); i >= 0; i--){
      	c = (Class_) lst.get(i);
      	if (!frm.getClassIds().contains(c.getUniqueId().toString()) && !tmpClassIdsToRealClasses.containsValue(c)){
		if (c.getParentClass() != null){
			Class_ parent = c.getParentClass();
			parent.getChildClasses().remove(c);
			hibSession.update(parent);
		}
		c.getSchedulingSubpart().getClasses().remove(c);
		if (c.getPreferences() != null)
		    c.getPreferences().removeAll(c.getPreferences());
		
		c.deleteAllDependentObjects(hibSession, false);
		
		hibSession.delete(c);
      	}
      }
 	}
  }
 
Example 14
Project: unitimes   File: RoomFeatureTypes.java   Source Code and License Vote up 5 votes
protected void delete(RoomFeatureType type, SessionContext context, Session hibSession) {
	if (type == null) return;
	ChangeLog.addChange(hibSession,
			context,
			type,
			type.getReference(),
			Source.SIMPLE_EDIT, 
			Operation.DELETE,
			null,
			null);
	hibSession.delete(type);
}
 
Example 15
Project: djpt   File: DaoImpl.java   Source Code and License Vote up 5 votes
public void deleteEntity(Object entity) {
	Session session = hibernateTemplate.getSessionFactory().openSession();
	org.hibernate.Transaction tx = session.beginTransaction();
	session.delete(entity);
	try {
		tx.commit();
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}
	session.close();
}
 
Example 16
Project: hibernate-ogm-redis   File: RedisPerformanceTest.java   Source Code and License Vote up 4 votes
@Test
@BMRules(rules = {
		@BMRule(targetClass = "org.hibernate.ogm.datastore.redis.impl.json.JsonEntityStorageStrategy",
				targetMethod = "storeEntity(java.lang.String, org.hibernate.ogm.datastore.redis.dialect.value.Entity)",
				helper = "org.hibernate.ogm.utils.BytemanHelper",
				action = "countInvocation(\"storeEntity\")",
				name = "countStoreEntity"),
		@BMRule(targetClass = "org.hibernate.ogm.datastore.redis.impl.json.JsonEntityStorageStrategy",
				targetMethod = "getEntity(java.lang.String)",
				helper = "org.hibernate.ogm.utils.BytemanHelper",
				action = "countInvocation(\"getEntity\")",
				name = "countGetEntity")
})
public void testNumberOfCallsToDatastore() throws Exception {
	//insert entity with embedded collection
	Session session = openSession();
	Transaction tx = session.beginTransaction();
	GrandChild luke = new GrandChild();
	luke.setName( "Luke" );
	GrandChild leia = new GrandChild();
	leia.setName( "Leia" );
	GrandMother grandMother = new GrandMother();
	grandMother.getGrandChildren().add( luke );
	grandMother.getGrandChildren().add( leia );
	session.persist( grandMother );
	tx.commit();

	session.clear();

	int getEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "getEntity" );
	int storeEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "storeEntity" );
	assertThat( getEntityInvocationCount ).isEqualTo( 1 );
	assertThat( storeEntityInvocationCount ).isEqualTo( 1 );

	// Check that all the counters have been reset to 0
	getEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "getEntity" );
	storeEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "storeEntity" );
	assertThat( getEntityInvocationCount ).isEqualTo( 0 );
	assertThat( storeEntityInvocationCount ).isEqualTo( 0 );

	// Remove one of the elements
	tx = session.beginTransaction();
	grandMother = (GrandMother) session.get( GrandMother.class, grandMother.getId() );
	grandMother.getGrandChildren().remove( 0 );
	tx.commit();
	session.clear();

	getEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "getEntity" );
	storeEntityInvocationCount = BytemanHelper.getAndResetInvocationCount( "storeEntity" );
	assertThat( getEntityInvocationCount ).isEqualTo( 1 );
	assertThat( storeEntityInvocationCount ).isEqualTo( 1 );

	// Assert removal has been propagated
	tx = session.beginTransaction();
	grandMother = (GrandMother) session.get( GrandMother.class, grandMother.getId() );
	assertThat( grandMother.getGrandChildren() ).onProperty( "name" ).containsExactly( "Leia" );

	session.delete( grandMother );
	tx.commit();

	session.close();
}
 
Example 17
Project: Homework   File: PetDaoImpl.java   Source Code and License Vote up 4 votes
@Override
public void delete(Pet pet, Session session, Transaction tx)
{
    session.delete(session.get(Pet.class, pet.getId()));
    session.flush();
}
 
Example 18
Project: hibernate-ogm-ignite   File: ManyToOneTest.java   Source Code and License Vote up 4 votes
@Test
public void testBidirectionalManyToOneRegular() throws Exception {
	final Session session = openSession();
	Transaction transaction = session.beginTransaction();
	SalesForce force = new SalesForce( "sales_force" );
	force.setCorporation( "Red Hat" );
	session.save( force );
	SalesGuy eric = new SalesGuy( "eric" );
	eric.setName( "Eric" );
	eric.setSalesForce( force );
	force.getSalesGuys().add( eric );
	session.save( eric );
	SalesGuy simon = new SalesGuy( "simon" );
	simon.setName( "Simon" );
	simon.setSalesForce( force );
	force.getSalesGuys().add( simon );
	session.save( simon );
	transaction.commit();
	session.clear();

	transaction = session.beginTransaction();
	force = session.get( SalesForce.class, force.getId() );
	assertNotNull( force.getSalesGuys() );
	assertEquals( 2, force.getSalesGuys().size() );
	simon = session.get( SalesGuy.class, simon.getId() );
	// purposely faulty
	// force.getSalesGuys().remove( simon );
	session.delete( simon );
	transaction.commit();
	session.clear();

	transaction = session.beginTransaction();
	force = session.get( SalesForce.class, force.getId() );
	assertNotNull( force.getSalesGuys() );
	assertEquals( 1, force.getSalesGuys().size() );
	session.delete( force.getSalesGuys().iterator().next() );
	session.delete( force );
	transaction.commit();

	session.close();

	checkCleanCache();
}
 
Example 19
Project: hibernate-ogm-ignite   File: ManyToOneTest.java   Source Code and License Vote up 4 votes
@Test
public void testBidirectionalManyToOneRemoval() throws Exception {
	final Session session = openSession();
	Transaction transaction = session.beginTransaction();
	SalesForce force = new SalesForce( "red_hat" );
	force.setCorporation( "Red Hat" );
	session.save( force );
	SalesGuy eric = new SalesGuy( "eric" );
	eric.setName( "Eric" );
	eric.setSalesForce( force );
	force.getSalesGuys().add( eric );
	session.save( eric );
	SalesGuy simon = new SalesGuy( "simon" );
	simon.setName( "Simon" );
	simon.setSalesForce( force );
	force.getSalesGuys().add( simon );
	session.save( simon );
	transaction.commit();
	session.clear();

	// removing one sales guy, leaving the other in place
	transaction = session.beginTransaction();
	force = session.get( SalesForce.class, force.getId() );
	assertEquals( 2, force.getSalesGuys().size() );
	SalesGuy salesGuy = session.get( SalesGuy.class, eric.getId() );
	salesGuy.setSalesForce( null );
	force.getSalesGuys().remove( salesGuy );
	transaction.commit();
	session.clear();

	transaction = session.beginTransaction();
	force = session.get( SalesForce.class, force.getId() );
	assertEquals( 1, force.getSalesGuys().size() );
	salesGuy = force.getSalesGuys().iterator().next();
	assertThat( salesGuy.getName() ).isEqualTo( "Simon" );

	session.delete( session.get( SalesGuy.class, eric.getId() ) );
	session.delete( session.get( SalesGuy.class, simon.getId() ) );
	session.delete( force );
	transaction.commit();

	session.close();

	checkCleanCache();
}
 
Example 20
Project: Homework   File: PetDaoImpl.java   Source Code and License Vote up 4 votes
public void delete(Pet pet, Session session, Transaction tx)
{
    session.delete(session.get(Pet.class, pet.getId()));
    session.flush();
}