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

The following are Jave code examples for showing how to use saveOrUpdate() 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.
+ Save this method
Example 1
Project: unitimes   File: CourseCreditUnits.java   View Source Code Vote up 6 votes
protected void update(CourseCreditUnitType credit, Record record, SessionContext context, Session hibSession) {
	if (credit == null) return;
	if (ToolBox.equals(credit.getReference(), record.getField(0)) &&
			ToolBox.equals(credit.getLabel(), record.getField(1)) &&
			ToolBox.equals(credit.getAbbreviation(), record.getField(2))) return;
	credit.setReference(record.getField(0));
	credit.setLabel(record.getField(1));
	credit.setAbbreviation(record.getField(2));
	hibSession.saveOrUpdate(credit);
	ChangeLog.addChange(hibSession,
			context,
			credit,
			credit.getReference() + " " + credit.getLabel(),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			null);
}
 
Example 2
Project: Learning-Spring-5.0   File: BookDAO_SessionFactory.java   View Source Code Vote up 6 votes
@Override
public int updateBook(long ISBN, int price) {
	// TODO Auto-generated method stub

	Session session = sessionFactory.openSession();
	Transaction transaction = session.beginTransaction();
	try {
		Book book = session.get(Book.class, ISBN);
		book.setPrice(price);

		session.saveOrUpdate(book);
		transaction.commit();
		session.close();
		return 1;
	} catch (DataAccessException exception) {
		exception.printStackTrace();
	}
	return 0;

}
 
Example 3
Project: unitimes   File: AcademicClassifications.java   View Source Code Vote up 6 votes
protected void update(AcademicClassification clasf, Record record, SessionContext context, Session hibSession) {
	if (clasf == null) return;
	if (ToolBox.equals(clasf.getExternalUniqueId(), record.getField(0)) &&
			ToolBox.equals(clasf.getCode(), record.getField(1)) &&
			ToolBox.equals(clasf.getName(), record.getField(2))) return;
		clasf.setExternalUniqueId(record.getField(0));
		clasf.setCode(record.getField(1));
		clasf.setName(record.getField(2));
		hibSession.saveOrUpdate(clasf);
		ChangeLog.addChange(hibSession,
				context,
				clasf,
				clasf.getCode() + " " + clasf.getName(),
				Source.SIMPLE_EDIT, 
				Operation.UPDATE,
				null,
				null);		
}
 
Example 4
Project: Learning-Spring-5.0   File: BookDAO_SessionFactory.java   View Source Code Vote up 6 votes
@Override
public int addBook(Book book) {
	// TODO Auto-generated method stub

	Session session = sessionFactory.openSession();
	Transaction transaction = session.beginTransaction();
	try {
		session.saveOrUpdate(book);
		transaction.commit();
		session.close();
		return 1;
	} catch (DataAccessException exception) {
		exception.printStackTrace();
	}
	return 0;

}
 
Example 5
Project: unitimes   File: PositionTypes.java   View Source Code Vote up 6 votes
protected void update(PositionType position, Record record, SessionContext context, Session hibSession) {
	if (position == null) return;
	DecimalFormat df = new DecimalFormat("0000");
	if (ToolBox.equals(position.getReference(), record.getField(0)) &&
			ToolBox.equals(position.getLabel(), record.getField(1)) &&
			ToolBox.equals(df.format(position.getSortOrder()), record.getField(2))) return;
	position.setReference(record.getField(0));
	position.setLabel(record.getField(1));
	position.setSortOrder(Integer.valueOf(record.getField(2)));
	hibSession.saveOrUpdate(position);
	ChangeLog.addChange(hibSession,
			context,
			position,
			position.getReference() + " " + position.getLabel(),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			null);
}
 
Example 6
Project: unitimes   File: EventDateMappings.java   View Source Code Vote up 6 votes
protected void update(EventDateMapping mapping, Record record, SessionContext context, Session hibSession) {
	try {
		if (mapping == null) return;
		Formats.Format<Date> dateFormat = Formats.getDateFormat(Formats.Pattern.DATE_EVENT);
		if (ToolBox.equals(dateFormat.format(mapping.getClassDate()), record.getField(0)) &&
				ToolBox.equals(dateFormat.format(mapping.getEventDate()), record.getField(1)) &&
				ToolBox.equals(mapping.getNote(), record.getField(2))) return;
		mapping.setClassDate(dateFormat.parse(record.getField(0)));
		mapping.setEventDate(dateFormat.parse(record.getField(1)));
		mapping.setNote(record.getField(2));
		hibSession.saveOrUpdate(mapping);
		ChangeLog.addChange(hibSession,
				context,
				mapping,
				dateFormat.format(mapping.getClassDate()) + " &rarr; " + dateFormat.format(mapping.getEventDate()),
				Source.SIMPLE_EDIT, 
				Operation.UPDATE,
				null,
				null);
	} catch (ParseException e) {
		throw new GwtRpcException(e.getMessage(), e);
	}
}
 
Example 7
Project: SchTtableServer   File: StatusDaoImpl.java   View Source Code Vote up 5 votes
@Override
public boolean addOrUpdate(StatusBean statusBean) {
    if (statusBean == null) {
        return false;
    }
    
    Session session = sessionFactory.getCurrentSession();
    session.saveOrUpdate(statusBean);
    return true;
}
 
Example 8
Project: OSWf-OSWorkflow-fork   File: HibernatePersistentVarsDAO.java   View Source Code Vote up 5 votes
public void save(HibernatePersistentVarsItem item) {

        if( item == null)
            throw new PersistentVarsException("Could not save 'null' PropertyItem");
 
       Session session = null;
       Transaction transaction = null;

        try {
            session = this.sessionFactory.openSession();
            transaction = session.beginTransaction();
            
            session.saveOrUpdate(item);
            session.flush();
            
            transaction.commit();
            
        } catch (HibernateException hibernateException) {
            throw new PersistentVarsException("Could not save key '" + item.getKey() + "':" + hibernateException.getMessage());
        } finally {
            
            if (transaction != null && transaction.isActive())
                 transaction.rollback();

            if (session != null)
                session.close();
        }
    }
 
Example 9
Project: DWSurvey   File: QuestionDaoImpl.java   View Source Code Vote up 5 votes
/**
 * 保存排序题
 * @param entity
 * @param session
 */
private void saveQuOrderby(Question entity, Session session) {
	List<QuOrderby> quOrderbys=entity.getQuOrderbys();
	for (QuOrderby quOrderby : quOrderbys) {
		quOrderby.setQuId(entity.getId());
		session.saveOrUpdate(quOrderby);
	}
}
 
Example 10
Project: unitimes   File: StandardEventNotes.java   View Source Code Vote up 5 votes
protected void update(StandardEventNote note, Record record, SessionContext context, Session hibSession) {
	if (note == null) return;
	if (ToolBox.equals(note.getReference(), record.getField(0)) && ToolBox.equals(note.getNote(), record.getField(1))) return;
	note.setReference(record.getField(0));
	note.setNote(record.getField(1));
	hibSession.saveOrUpdate(note);
	ChangeLog.addChange(hibSession,
			context,
			note,
			note.getReference(),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			note instanceof StandardEventNoteDepartment ? ((StandardEventNoteDepartment)note).getDepartment() : null);
}
 
Example 11
Project: ByteJTA-sample   File: AccountDaoImpl.java   View Source Code Vote up 5 votes
public void update(Account account) {
	Session session = null;
	try {
		session = this.sessionFactory.openSession();
		session.saveOrUpdate(account);
		session.flush();
	} finally {
		this.closeSessionIfNecessary(session);
	}
}
 
Example 12
Project: DWSurvey   File: QuestionDaoImpl.java   View Source Code Vote up 5 votes
private void saveOptions(Question entity, Session session) {
	List<QuChenOption> options=entity.getOptions();
	String quId=entity.getId();
	for (QuChenOption quChenOption : options) {
		quChenOption.setQuId(quId);
		session.saveOrUpdate(quChenOption);
	}
}
 
Example 13
Project: uflo   File: HeartJob.java   View Source Code Vote up 5 votes
public void execute(JobExecutionContext context) throws JobExecutionException {
	HeartJobDetail detail=(HeartJobDetail)context.getJobDetail();
	String instanceName=detail.getCurrentInstanceName();
	Session session=detail.getSessionFactory().openSession();
	try{
		String hql="from "+Heartbeat.class.getName()+" b where b.instanceName=:instanceName order by b.date desc";
		Query query=session.createQuery(hql).setString("instanceName",instanceName);
		@SuppressWarnings("unchecked")
		List<Heartbeat> beats=query.list();
		Date now=new Date();
		Heartbeat beat=null;
		if(beats.size()>0){
			beat=beats.get(0);
		}else{
			beat=new Heartbeat();
			beat.setId(UUID.randomUUID().toString());
			beat.setInstanceName(instanceName);
		}
		beat.setDate(now);
		session.saveOrUpdate(beat);
	}catch(Exception ex){
		throw new JobExecutionException(ex);
	}finally{
		session.flush();
		session.close();
	}
}
 
Example 14
Project: unitimes   File: EventStatuses.java   View Source Code Vote up 5 votes
protected void update(Location location, Record record, SessionContext context, Session hibSession) {
	if (location == null) return;
	Integer status = record.getField(3) == null || record.getField(3).isEmpty() ? null : Integer.parseInt(record.getField(3));
	String note = (record.getField(4) == null || record.getField(4).isEmpty() ? null : record.getField(4));
	Integer breakTime = null;
	try {
		breakTime = (record.getField(5) == null || record.getField(5).isEmpty() ? null : Integer.parseInt(record.getField(5)));
	} catch (NumberFormatException e) {}
	if (ToolBox.equals(location.getEventStatus(), status) &&
			ToolBox.equals(location.getNote(), note) &&
			ToolBox.equals(location.getBreakTime(), breakTime)) return;
	boolean noteChanged = !ToolBox.equals(location.getNote(), note);
	location.setEventStatus(status);
	location.setNote(note);
	location.setBreakTime(breakTime);
	hibSession.saveOrUpdate(location);
	ChangeLog.addChange(hibSession,
			context,
			location,
			location.getLabel() + ": " + location.getEffectiveEventStatus() + (location.getEventStatus() == null ? " (Default)" : ""),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			location.getEventDepartment());
	if (noteChanged)
		ChangeLog.addChange(hibSession,
				context, location, (location.getNote() == null || location.getNote().isEmpty() ? "-" : location.getNote()),
				ChangeLog.Source.ROOM_EDIT, ChangeLog.Operation.NOTE, null, location.getControllingDepartment());		
}
 
Example 15
Project: DWSurvey   File: QuestionDaoImpl.java   View Source Code Vote up 5 votes
/**
 * 保存评分题
 * @param entity
 * @param session
 */
private void saveQuScore(Question entity, Session session) {
	List<QuScore> quScores=entity.getQuScores();
	for (QuScore quScore : quScores) {
		quScore.setQuId(entity.getId());
		session.saveOrUpdate(quScore);
	}
}
 
Example 16
Project: sjk   File: BigGamePackDaoImpl.java   View Source Code Vote up 4 votes
@Override
public void saveOrUpdate(Session session, BigGamePack t) {
    session.saveOrUpdate(t);

}
 
Example 17
Project: DWSurvey   File: QuestionDaoImpl.java   View Source Code Vote up 4 votes
private void saveQuestion(Question entity, Session session) {
	boolean isnew=false;
	String id=entity.getId();
	String belongId=entity.getBelongId();
	int orderById=entity.getOrderById();
	if(id==null || "".equals(id)){//如果是新增的题目,则根据已有的题来设置排序号
		isnew=true;
	}
	//保存题目的题干部分
	session.saveOrUpdate(entity);
	//判断题目类型
	QuType quType=entity.getQuType();
	if(quType==QuType.RADIO || quType==QuType.COMPRADIO){
		saveRadio(entity, session);
	}else if(quType==QuType.CHECKBOX || quType==QuType.COMPCHECKBOX){
		saveCheckbox(entity, session);
	}else if(quType==QuType.MULTIFILLBLANK){
		saveMultiFillblank(entity, session);
	}else if(quType==QuType.BIGQU){
		saveQuBig(entity, session);
	}else if(quType==QuType.SCORE){
		saveQuScore(entity,session);
	}else if(quType==QuType.ORDERQU){
		saveQuOrderby(entity,session);
	}else if(quType==QuType.CHENRADIO){//矩阵单选
		saveQuChenRadio(entity,session,isnew);
	}else if(quType==QuType.CHENCHECKBOX){//矩阵多选
		saveQuChenCheckbox(entity,session,isnew);
	}else if(quType==QuType.CHENFBK){//矩阵填空
		saveQuChenFbk(entity,session,isnew);
	}else if(quType==QuType.CHENSCORE){//矩阵评分题
		saveQuChenScore(entity,session,isnew);
	}else if(quType==QuType.COMPCHENRADIO){//复合矩阵单选题
		saveQuCompChenRadio(entity,session,isnew);
	}
	//更新排序号--如果是新增
	List<QuestionLogic> questionLogics=entity.getQuestionLogics();
	if(questionLogics!=null){
		for (QuestionLogic questionLogic : questionLogics) {
			String qulogicId=questionLogic.getId();
			if("".equals(qulogicId)){
				questionLogic.setId(null);
			}
			questionLogic.setCkQuId(entity.getId());
			session.saveOrUpdate(questionLogic);
		}
	}
	if(isnew){
		quOrderByIdAdd1(belongId, orderById);
	}
}
 
Example 18
Project: Library   File: LibraryServicesImpl.java   View Source Code Vote up 4 votes
public RestResponse addFine() {

		RestResponse response = new RestResponse();
		Session session = this.sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();

		try {
			String paramString = "from BookLoan where dateIn=null";
			//String paramString = "select * from book_loan where date_in is null";
			Query query = session.createQuery(paramString);

			List<BookLoan> bookLoans = query.list();

			Fine fine = null;
			Date date = new Date();
			for (BookLoan bookLoan : bookLoans) {

				if (bookLoan.getDueDate().before(date)) {

					
					if(bookLoan.getFine()==null){
						fine = new Fine(bookLoan);
					}else{
						fine = bookLoan.getFine();
					}
					
					long diff = date.getTime() - bookLoan.getDueDate().getTime();

					long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
					fine.setFineAmount(Double.toString(days * 0.25));

					session.saveOrUpdate(fine);
				}

			}
			transaction.commit();
			response.setSuccess(true);
			response.setResult("Fine updated successfully");

		} catch (Exception e) {
			transaction.rollback();
			response.setError("Error while updating. Try Again");
			response.setSuccess(false);
		}

		session.close();

		return response;
	}
 
Example 19
Project: sbc-qsystem   File: Spring.java   View Source Code Vote up 4 votes
public void saveOrUpdate(Object obj) {
    final Session ses = getTxManager().getSessionFactory().getCurrentSession();
    ses.saveOrUpdate(obj);
    ses.flush();
}
 
Example 20
Project: uflo   File: SaveHistoryActivityCommand.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
public HistoryActivity execute(Context context) {
	Session session=context.getSession();
	/**
	 * 首先尝试取没有结束日期的当前节点的历史节点,如果有,那么就简单的为其添加结束时间,如果没有则创建一个新的,且保持结束日期为空
	 * 如果没有未结束的历史节点,那么就尝试按结束日期倒序排取最晚结束的历史结束,然后更新其结束日期即可。
	 * */
	HistoryActivity hisActivity=(HistoryActivity)session.createCriteria(HistoryActivity.class)
			.add(Restrictions.eq("processInstanceId", processInstance.getId()))
			.add(Restrictions.isNull("endDate"))
			.add(Restrictions.eq("nodeName",node.getName())).uniqueResult();
	if(isEnd){
		if(hisActivity==null){
			List<HistoryActivity> historyActivities=session.createCriteria(HistoryActivity.class)
					.add(Restrictions.eq("processInstanceId", processInstance.getId()))
					.add(Restrictions.isNotNull("endDate"))
					.addOrder(Order.desc("createDate"))
					.add(Restrictions.eq("nodeName",node.getName())).list();
			if(historyActivities.size()>0){
				hisActivity=historyActivities.get(0);
			}
		}
		if(hisActivity==null){
			return null;
		}
		hisActivity.setEndDate(new Date());
		if(StringUtils.isNotEmpty(leaveFlowName)){
			hisActivity.setLeaveFlowName(leaveFlowName);				
		}
	}else{
		if(hisActivity==null){
			hisActivity=new HistoryActivity();
			hisActivity.setCreateDate(new Date());
			hisActivity.setHistoryProcessInstanceId(processInstance.getHistoryProcessInstanceId());
			hisActivity.setNodeName(node.getName());
			hisActivity.setId(IDGenerator.getInstance().nextId());
			hisActivity.setDescription(node.getDescription());
			hisActivity.setProcessId(node.getProcessId());
			hisActivity.setRootProcessInstanceId(processInstance.getRootId());
			hisActivity.setProcessInstanceId(processInstance.getId());
			hisActivity.setLeaveFlowName(leaveFlowName);
		}
	}
	session.saveOrUpdate(hisActivity);
	return hisActivity;
}