Java Code Examples for org.hibernate.Transaction

The following are top voted examples for showing how to use org.hibernate.Transaction. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ImageClassify   File: ConstantService.java   View source code 8 votes vote down vote up
@Override
public boolean updateValueOfKey(Constant constant) { 
		Session session = HibernateUtils.getSession();
		 Transaction tx = session.beginTransaction();
		 boolean isUpdate = false;
		 try {
			Query query = session.createQuery("update Constant c set c.value =? where c.id = ?");  
		    query.setString(0,constant.getValue());
		    query.setInteger(1, constant.getId()); 
			int temp = query.executeUpdate();  
			tx.commit();
			if (temp>0) {
				isUpdate = true;
			}
		} catch (Exception e) {
			 e.printStackTrace();
			 tx.rollback();
		}finally {
			HibernateUtils.closeSession();
		}   
		 return isUpdate;
}
 
Example 2
Project: FlashBoard   File: AdminDaoImpl.java   View source code 7 votes vote down vote up
@Override
public boolean approveUser(String username) {
	Boolean bool = false;
	Session session = HibernateUtil.getSession();
	Transaction tx = null;
	User myUser = udi.getUserByUsername(username);
	try {
		tx = session.beginTransaction();
		myUser.setApproved(true);
		session.update(myUser);
		tx.commit();
		bool = true;
		System.out.println("User: '" + username + "' successfully approved.");
	} catch (HibernateException he) {
		if (tx != null) {
			tx.rollback();
		}
	} finally {
		session.close();
	}
	return bool;
}
 
Example 3
Project: ImageClassify   File: MarkService.java   View source code 6 votes vote down vote up
@Override
public boolean updateMarkAll(Mark mark) {
	 Session session = HibernateUtils.getSession();
	 Transaction tx = session.beginTransaction();
	 boolean b = false;
	 try {
		Query query = session.createQuery("update Mark m set m.mark_accuracy =?,m.mark_time =?,m.option_mark_name =?,"
				+ "m.manual_mark_name=? where m.user_id = ? and m.img_id = ?");  
	    query.setString(0, mark.getMark_accuracy());
	    query.setTimestamp(1, mark.getMark_time());
	    query.setString(2,mark.getOption_mark_name());
	    query.setString(3, mark.getManual_mark_name()); 
	    query.setInteger(4, mark.getUser_id());
	    query.setInteger(5, mark.getImg_id()); 
		query.executeUpdate();  
		tx.commit();
		b = true;
	} catch (Exception e) {
		 e.printStackTrace();
		 tx.rollback(); 
	}finally {
		HibernateUtils.closeSession();
	} 
	 return b;
}
 
Example 4
Project: Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update   File: delete_HQL.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	Configuration cfg=null;
	SessionFactory factory=null;
	Session ses=null;
	 Transaction tx=null;
			cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
			factory=cfg.buildSessionFactory();
		ses=factory.openSession();
	
		tx=ses.beginTransaction();
		 String hql="delete from bigbazarModel where bazarid=:id";
		 Query q=ses.createQuery(hql);
		 		q.setParameter("id", 1003);
		 			int c=q.executeUpdate();
		 			//int count=Integer.parseUnsignedInt(c);
		 			tx.commit();
		 			System.out.println("\t\t"+c+" rows Deleted");
		 		
		 			factory.close();

}
 
Example 5
Project: Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update   File: copy_HQL.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	Configuration cfg=null;
	SessionFactory factory=null;
	Session ses=null;
	 Transaction tx=null;
			cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
			factory=cfg.buildSessionFactory();
		ses=factory.openSession();
	
		tx=ses.beginTransaction();
		 String hql="insert into newMall(mallid,item_name,item_price,item_quantity) "
		 			+ "select bazarid,item_name,item_price,item_quantity from bigbazarModel ";
		 Query q=ses.createQuery(hql);
		 			int c=q.executeUpdate();
		 			//int count=Integer.parseUnsignedInt(c);
		 			tx.commit();
		 			System.out.println("\t\t"+c+" rows Copied Successfully...");
		 		
		 			factory.close();

}
 
Example 6
Project: Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update   File: update_HQL.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	Configuration cfg=null;
	SessionFactory factory=null;
	Session ses=null;
	 Transaction tx=null;
			cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
			factory=cfg.buildSessionFactory();
		ses=factory.openSession();
	
		tx=ses.beginTransaction();
		 String hql="update bigbazarModel set item_price=:price where bazarid=:id";
		 Query q=ses.createQuery(hql);
		 		q.setParameter("id", 1002);
		 		q.setParameter("price", 60.0f);
		 			int c=q.executeUpdate();
		 			//int count=Integer.parseUnsignedInt(c);
		 			tx.commit();
		 			System.out.println("\t\t"+c+" rows Updated");
		 		
		 			factory.close();

}
 
Example 7
Project: ImageClassify   File: CategoryService.java   View source code 6 votes vote down vote up
/**
 * 持久化category对象
 */
@Override
public boolean saveCatogory(Category category) {
	Session session = HibernateUtils.getSession(); // 生成session实例
	Transaction tx = session.beginTransaction(); // 创建transaction实例
	try {
		session.save(category); // 使用session的sava方法将持久化对象保存到数据库中
		tx.commit(); // 提交事务
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback(); // 回滚事务
		return false;
	} finally {
		HibernateUtils.closeSession(); // 关闭Session实例
	}
}
 
Example 8
Project: OSWf-OSWorkflow-fork   File: HibernateStore.java   View source code 6 votes vote down vote up
protected void save(final Session session, final Object entity) throws HibernateException {

       Transaction transaction = null;

       try {
           transaction = session.beginTransaction();
           session.save(entity);
           transaction.commit();
       } catch (HibernateException hibernateException) {
           
           if (transaction != null)
               transaction.rollback();
               
           logger.error(fatal, hibernateException.toString());
           throw hibernateException;
       } 
       
   }
 
Example 9
Project: unitimes   File: LogCleaner.java   View source code 6 votes vote down vote up
public static void cleanupOnlineSectioningLog(int days) {
	if (days < 0) return;
	org.hibernate.Session hibSession = new _RootDAO().createNewSession();
	Transaction tx = null;
	try {
		tx = hibSession.beginTransaction();
		int rows = hibSession.createQuery(
				"delete from OnlineSectioningLog where timeStamp < " + HibernateUtil.addDate("current_date()", ":days")
				).setInteger("days", - days).executeUpdate();
		if (rows > 0)
			sLog.info("All records older than " + days + " days deleted from the online sectioning log (" + rows + " records).");
		tx.commit();
	} catch (Throwable t) {
		sLog.warn("Failed to cleanup query log: " + t.getMessage(), t);
		if (tx != null) tx.rollback();
	} finally {
		hibSession.close();
	}
}
 
Example 10
Project: ImageClassify   File: ImageService.java   View source code 6 votes vote down vote up
@Override
public boolean saveImageCategory(Image_Category image_Category) {
	Session session = HibernateUtils.getSession(); //生成session实例
    Transaction tx = session.beginTransaction();  //创建transaction实例
     
    try {   
        session.save(image_Category); 
        tx.commit();            //提交事务 
        return true;
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();          //回滚事务 
		return false;
	}finally {
	  HibernateUtils.closeSession();  //关闭Session实例
	} 
}
 
Example 11
Project: FlashBoard   File: Driver2.java   View source code 6 votes vote down vote up
public static void testUserCreation() {
	Session session = HibernateUtil.getSession();
	Transaction tx = null;
	
	User newUser = new User("jef", "jeff", "jeff", "jeff", "jeff");
	//SQLIntegrityConstraintViolationException
	try {
		tx = session.beginTransaction();
		session.save(newUser);
		tx.commit();
		System.out.println("User: '" + newUser.getUsername() + "' has been successfully created!");
	} catch (HibernateException he) {
		if (tx != null) {
			tx.rollback();
		}
		System.out.println("User creation failed!");
		he.printStackTrace();
		
	} finally {
		session.close();
	}
}
 
Example 12
Project: unitimes   File: UniTimeClusterDiscovery.java   View source code 6 votes vote down vote up
protected void remove(Address addr) {
  	if (!ClusterDiscoveryDAO.isConfigured()) return;
  	org.hibernate.Session hibSession = ClusterDiscoveryDAO.getInstance().createNewSession();
String own_address = addressAsString(addr);
Transaction tx = null;
      try {
      	tx = hibSession.beginTransaction();
      	ClusterDiscovery cluster = ClusterDiscoveryDAO.getInstance().get(new ClusterDiscovery(own_address, cluster_name), hibSession);
      	if (cluster != null)
      		hibSession.delete(cluster);
      	hibSession.flush();
          if (tx != null) tx.commit();
      } catch (Exception e) {
	if (tx != null) tx.rollback();
	log.info("Failed to delete data for cluster " + cluster_name + ": " + e.getMessage());
} finally {
	hibSession.close();
}
  }
 
Example 13
Project: FlashBoard   File: QuizDaoImpl.java   View source code 6 votes vote down vote up
public Integer insertQuiz(Quiz quiz) {
	Session session = HibernateUtil.getSession();
	Transaction tx = null;
	Integer quizId = null;
	
	try {
		// Attemps to add and get quiz Id back
		tx = session.beginTransaction();
		quizId = (Integer) session.save(quiz);
		System.out.println(quizId);
		tx.commit();
	} catch (HibernateException e) {
		if (tx != null) {
			// Roll back IF transaction fails
			tx.rollback();
		}
		e.printStackTrace();
	} finally {
		session.close();
	}
	
	return quizId;
}
 
Example 14
Project: FlashBoard   File: AdminDaoImpl.java   View source code 6 votes vote down vote up
@Override
public boolean promoteUserToWriter(String username) {
	Boolean bool = false;
	Session session = HibernateUtil.getSession();
	Transaction tx = null;
	User myUser = udi.getUserByUsername(username);
	try {
		tx = session.beginTransaction();
		myUser.setRoleFlag(2);
		session.save(myUser);
		tx.commit();
		bool = true;
		System.out.println("User: '" + username + "' successfully approved.");
	} catch (HibernateException he) {
		if (tx != null) {
			tx.rollback();
		}
	} finally {
		session.close();
	}
	return bool;
}
 
Example 15
Project: FlashBoard   File: AdminDaoImpl.java   View source code 6 votes vote down vote up
@Override
public boolean deleteUserAccount(String username) {
	Boolean bool = false;
	Session session = HibernateUtil.getSession();
	Transaction tx = null;
	User myUser = udi.getUserByUsername(username);
	try {
		tx = session.beginTransaction();
		myUser.setBlacklisted(true);
		session.delete(myUser);
		tx.commit();
		bool = true;
		System.out.println("User: '" + username + "' successfully deleted.");
	} catch (HibernateException he) {
		if (tx != null) {
			tx.rollback();
		}
	} finally {
		session.close();
	}
	return bool;
}
 
Example 16
Project: Learning-Spring-5.0   File: BookDAO_SessionFactory.java   View source code 6 votes vote down vote up
@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 17
Project: unitimes   File: LogCleaner.java   View source code 6 votes vote down vote up
public static void cleanupQueryLog(int days) {
	if (days < 0) return;
	org.hibernate.Session hibSession = new _RootDAO().createNewSession();
	Transaction tx = null;
	try {
		tx = hibSession.beginTransaction();
		int rows = hibSession.createQuery(
				"delete from QueryLog where timeStamp < " + HibernateUtil.addDate("current_date()", ":days")
				).setInteger("days", - days).executeUpdate();
		if (rows > 0)
			sLog.info("All records older than " + days + " days deleted from the query log (" + rows + " records).");
		tx.commit();
	} catch (Throwable t) {
		sLog.warn("Failed to cleanup query log: " + t.getMessage(), t);
		if (tx != null) tx.rollback();
	} finally {
		hibSession.close();
	}
}
 
Example 18
Project: unitimes   File: InstructorSchedulingDatabaseLoader.java   View source code 6 votes vote down vote up
public void load() throws Exception {
	ApplicationProperties.setSessionId(iSessionId);
	org.hibernate.Session hibSession = null;
	Transaction tx = null;
	try {
		hibSession = TimetableManagerDAO.getInstance().createNewSession();
		hibSession.setCacheMode(CacheMode.IGNORE);
		hibSession.setFlushMode(FlushMode.COMMIT);
		
		tx = hibSession.beginTransaction(); 
		
		load(hibSession);
		
		tx.commit();
	} catch (Exception e) {
		iProgress.fatal("Unable to load input data, reason: " + e.getMessage(), e);
		tx.rollback();
	} finally {
		// here we need to close the session since this code may run in a separate thread
		if (hibSession != null && hibSession.isOpen()) hibSession.close();
	}
}
 
Example 19
Project: ImageClassify   File: ConstantService.java   View source code 6 votes vote down vote up
@Override
public List<Constant> getConstantByKey() {
	
	 Session session = HibernateUtils.getSession();
	 Transaction tx = session.beginTransaction(); 
	 List<Constant> constants = new ArrayList<Constant>();
	 try {
		 constants.add((Constant) session.createCriteria(Constant.class).add(Restrictions.eq("key", cn.codekong.config.Constant.IDENTITY_TIME)).uniqueResult());
		 constants.add((Constant) session.createCriteria(Constant.class).add(Restrictions.eq("key", cn.codekong.config.Constant.IDENTIFY_FREQUENCY_MARKS)).uniqueResult());
		 tx.commit();
	 } catch (Exception e) {
		 e.printStackTrace();
		 tx.rollback();
	}finally {
		HibernateUtils.closeSession();
	}   
	 return constants;
}
 
Example 20
Project: ImageClassify   File: UserService.java   View source code 6 votes vote down vote up
/**
 * @param id
 * 根据用户的标识id找到该用户并返回
 */
@Override
public User findUserById(int user_id) {
	 User user = null;
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例
	 try {
	     user =  (User) session.get(User.class, user_id);
	     //调用session的get()方法,找到此用户到内存中
	    tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}
	 return user;
}
 
Example 21
Project: ImageClassify   File: ImageService.java   View source code 6 votes vote down vote up
@Override
public List<Image> getFinishedImages() {
	List<Image> images = new ArrayList<Image>();
       Session session = HibernateUtils.getSession();//生成Session实例
	Transaction tx = session.beginTransaction();//生成事务实例 
	 
	 try {
		 images = session.createQuery("select new Image(img_id,img_label_name) from Image where img_is_finish = 1").list();
		 tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}finally {
		HibernateUtils.closeSession();//关闭session实例
	}
	 return images; 
}
 
Example 22
Project: ImageClassify   File: OauthService.java   View source code 6 votes vote down vote up
@Override
 /**
  * 更新token对象
  * @param oauth
  * @return
  */
public boolean updateOauth(Oauth oauth) {
	 Session session = HibernateUtils.getSession();
	 Transaction tx = session.beginTransaction();
	 
	 try { 
		session.update(oauth); //调用session的update方法更新oauth对象
		tx.commit(); 
		return true;
	} catch (Exception e) {
		 e.printStackTrace();
		 tx.rollback(); 
		 return false;
	}finally {
		HibernateUtils.closeSession();
	}  
}
 
Example 23
Project: ImageClassify   File: TaskService.java   View source code 6 votes vote down vote up
/**
 * 获取user_id对应的已提交的Task
 */
@Override
public List<Task> geTasksOfUnconfirmed(int user_id,int start,int num) {
	List<Task> tasks = new ArrayList<Task>();  
	Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例
	 try {
		 
		 Query query =  session.createQuery("SELECT  new Task( task_id,task_img_amount,task_start_time,user_id) FROM Task WHERE task_iscommit = 1 AND user_id = "+user_id);
		 query.setFirstResult(start-1);
		 query.setMaxResults(num);
		 tasks = query.list(); 
	     tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}
	 return tasks; 
}
 
Example 24
Project: unitimes   File: TimetableDatabaseLoader.java   View source code 6 votes vote down vote up
public void load() {
	ApplicationProperties.setSessionId(iSessionId);
	org.hibernate.Session hibSession = null;
	Transaction tx = null;
	try {
		hibSession = TimetableManagerDAO.getInstance().getSession();
		hibSession.setCacheMode(CacheMode.IGNORE);
		hibSession.setFlushMode(FlushMode.COMMIT);
		
		tx = hibSession.beginTransaction(); 
		
		load(hibSession);
		
		tx.commit();
	} catch (Exception e) {
		iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load input data, reason:"+e.getMessage(),e);
		tx.rollback();
	} finally {
		// here we need to close the session since this code may run in a separate thread
		if (hibSession!=null && hibSession.isOpen()) hibSession.close();
	}
}
 
Example 25
Project: Learning-Spring-5.0   File: BookDAO_SessionFactory.java   View source code 6 votes vote down vote up
@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 26
Project: ImageClassify   File: OauthService.java   View source code 6 votes vote down vote up
/**
 * 依据oauth_token找到oauth实体对象
 */
@Override
public Oauth findOauthByOauthToken(String oauth_token) {
	 Oauth oauth = null;
	 Session session = HibernateUtils.getSession();
	 Transaction tx = session.beginTransaction(); //开启事务
	 try {
		 //使用criteria查询oauth对象
		  oauth = (Oauth) session.createCriteria(Oauth.class).add(Restrictions.eq("oauth_token", oauth_token)).uniqueResult();
		  tx.commit();
	} catch (Exception e) {
	  e.printStackTrace();
	  tx.rollback();
	}finally{
		HibernateUtils.closeSession();
	}
	 return oauth; //返回oauth对象
}
 
Example 27
Project: ImageClassify   File: TaskService.java   View source code 6 votes vote down vote up
@Override
public String getAmountTaskOfCommit(int user_id) {
	String sql = "SELECT COUNT(*) FROM task WHERE task_iscommit=1 AND user_id =" + user_id;
	Session session = HibernateUtils.getSession();
	Transaction tx = session.beginTransaction(); //开启事务
	int num = 0;
	try {
		num = Integer.parseInt(session.createSQLQuery(sql).list().get(0).toString());
		tx.commit();//提交事务 
	} catch (Exception e) {
	  e.printStackTrace();
	  tx.rollback();
	}finally{
		HibernateUtils.closeSession();
	} 
	return num+"";
}
 
Example 28
Project: unitimes   File: RoomSharingBackend.java   View source code 5 votes vote down vote up
public RoomSharingModel saveEventAvailability(RoomSharingRequest request, SessionContext context) {
	context.checkPermission(request.getLocationId(), "Location", Right.RoomEditEventAvailability);
	
	String availability = "";
	for (int d = 0; d < 7; d++)
		for (int s = 0; s < 288; s ++) {
			RoomSharingOption option = request.getModel().getOption(d, s);
			availability += (option.getId() == -1l ? '0' : '1');
		}
	
	org.hibernate.Session hibSession = LocationDAO.getInstance().getSession();
	Transaction tx = hibSession.beginTransaction();
	try {
	
		Location location = LocationDAO.getInstance().get(request.getLocationId(), hibSession);
		location.setEventAvailability(availability);
		hibSession.save(location);
		
		ChangeLog.addChange(hibSession, context, location, ChangeLog.Source.ROOM_DEPT_EDIT, ChangeLog.Operation.UPDATE, null, location.getControllingDepartment());
		
		tx.commit();
		
		return null;
		
	} catch (Exception ex) {
		tx.rollback();
		if (ex instanceof GwtRpcException) throw (GwtRpcException)ex;
		throw new GwtRpcException(ex.getMessage(), ex);
	}
}
 
Example 29
Project: ctsms   File: OpsSystDaoImpl.java   View source code 5 votes vote down vote up
@Override
public void handleRemoveTxn(Long opsSystId) throws Exception {
	Transaction transaction = this.getSession(true).beginTransaction();
	try {
		removeOpsSyst(opsSystId);
		transaction.commit();
	} catch (Exception e) {
		transaction.rollback();
		throw e;
	}
}
 
Example 30
Project: hibernate-ogm-redis   File: MapMappingTest.java   View source code 5 votes vote down vote up
@Test
public void testMapOfComponent() {
	OgmSession session = openSession();
	Transaction tx = session.beginTransaction();

	Map<String, Department> departments = new HashMap<>();
	departments.put( "sawing", new Department( "Sawing", 7 ) );
	departments.put( "sale", new Department( "Sale", 2 ) );
	Enterprise timberTradingInc = new Enterprise( "enterprise-1", departments );

	session.persist( timberTradingInc );
	tx.commit();
	session.clear();

	tx = session.beginTransaction();

	// assert
	assertDbObject(
			session.getSessionFactory(),
			// collection
			"Enterprise",
			// query
			"enterprise-1",
			// expected
			"{ " +
				"'departments' : {" +
					"'sawing' : { 'name' : 'Sawing', 'headCount'  : 7 }," +
					"'sale' : { 'name' : 'Sale', 'headCount'  : 2 }," +
				"}" +
			"}"
	);

	// clean up
	session.delete( timberTradingInc );

	tx.commit();
	session.close();
	checkCleanCache();
}
 
Example 31
Project: ImageClassify   File: CompositionService.java   View source code 5 votes vote down vote up
/**
 * 获取指定task_id对应的任务所有图片
 */
@Override
public List<Image> getTaskOfImages(int task_id) {
	
	 List<Image> images = new ArrayList<Image>();
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例 
	 try { 
	    Query query = session.createSQLQuery("SELECT  image.img_id,img_name,img_path FROM composition,image WHERE composition.img_id = image.img_id AND composition.task_id = "+task_id).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); 
		    query.setFirstResult(0);
		    query.setMaxResults(5);
	    images = query.list();
	     //调用session的get()方法,找到此用户到内存中
	    tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}    
	 List<Image> images2 = new ArrayList<Image>(); 
	 
	 for (int i = 0; i < images.size(); i++) { 
		  Image image = new Image();
		  Map map = (Map) images.get(i); 
		  image.setImg_id(Integer.parseInt(map.get("img_id")+"")); 
		  image.setImg_name(map.get("img_name")+"");
		  image.setImg_path(map.get("img_path")+"");
		  images2.add(image);
	 }  
	 return images2;
}
 
Example 32
Project: otus_java_2017_04   File: DBServiceImpl.java   View source code 5 votes vote down vote up
private <R> R runInSession(Function<Session, R> function) {
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        R result = function.apply(session);
        transaction.commit();
        return result;
    }
}
 
Example 33
Project: LibrarySystem   File: TestAdmin.java   View source code 5 votes vote down vote up
@Test
public void testSaveAdmin3(){
	SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
	Session session = sessionFactory.openSession();
	Transaction transaction = session.beginTransaction();
	Authorization authorization = new Authorization();
	
	authorization.setAid(2);
	session.save(authorization);
	
	transaction.commit();
	session.close();
}
 
Example 34
Project: ImageClassify   File: MarkService.java   View source code 5 votes vote down vote up
@Override
public List<Image_Mark> getImageMark(int img_id) {
	List<Image_Mark> image_Marks = new ArrayList<Image_Mark>();
	Session session = HibernateUtils.getSession(); //生成session实例
    Transaction tx = session.beginTransaction();  //创建transaction实例
    try {  
    	 
    	Query query = session.createSQLQuery("SELECT option_mark_name,manual_mark_name FROM image_mark where img_id = "+img_id)
	    		.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP) ; 
    	image_Marks = query.list();
    	tx.commit();            //提交事务 
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();          //回滚事务 
	}finally {
	  HibernateUtils.closeSession();  //关闭Session实例
	}
    
	 List<Image_Mark> marks = new ArrayList<Image_Mark>();
	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	 for (int i = 0; i < image_Marks.size(); i++) { 
		 Image_Mark image_Mark = new Image_Mark();
		  Map map = (Map) image_Marks.get(i);
		  //img_machine_tag_label,img_path,img_name,user_id,img_id 
		  image_Mark.setManual_mark_name(map.get("manual_mark_name")+"");
		  image_Mark.setOption_mark_name(map.get("option_mark_name")+"");
		  marks.add(image_Mark);
	 }  
	 return marks; 
}
 
Example 35
Project: otus_java_2017_06   File: DBServiceImpl.java   View source code 5 votes vote down vote up
private <R> R runInSession(Function<Session, R> function) {
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        R result = function.apply(session);
        transaction.commit();
        return result;
    }
}
 
Example 36
Project: OSWf-OSWorkflow-fork   File: HibernatePersistentVarsDAO.java   View source code 5 votes vote down vote up
public HibernatePersistentVarsItem findByKey(Long piid, String key) {

        if( piid == null)
            throw new PersistentVarsException("Could not find property for 'null' piid");

        if( key == null)
            throw new PersistentVarsException("Could not find property for 'null' key");
        
        Session session = null;
        Transaction transaction = null;
        HibernatePersistentVarsItem item = null;

        try {

            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            item = getItem(session, piid, key);
            session.flush();

            transaction.commit();

        } catch (HibernateException hibernateException) {
            throw new PersistentVarsException("Could not find key '" + key + "': " + hibernateException.getMessage());
        } finally {
            if (transaction != null && transaction.isActive())
                 transaction.rollback();

            if (session != null)
                session.close();
        }

        return item;
    }
 
Example 37
Project: unitimes   File: Exam.java   View source code 5 votes vote down vote up
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 38
Project: OSWf-OSWorkflow-fork   File: HibernateStore.java   View source code 5 votes vote down vote up
public List<Step> findCurrentSteps(final long entryId) throws WorkflowStoreException {

        Session session = null;
        Transaction transaction = null;
        List<Step> steps = null;

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

            steps = loadEntry(session, entryId).getCurrentSteps();

            transaction.commit();

         } catch (HibernateException hibernateException) {
            throw new WorkflowStoreException(hibernateException);
        } finally {

            if (transaction != null && transaction.isActive())
                 transaction.rollback();

            if (session != null)
                session.close();
        }
               
        return steps;
    }
 
Example 39
Project: OSWf-OSWorkflow-fork   File: HibernateStore.java   View source code 5 votes vote down vote up
public ProcessInstance findProcessInstance(long entryId) throws WorkflowStoreException {

       Session session = null;
       Transaction transaction = null;
       ProcessInstance workflowEntry = null;
       
       try {
           session = sessionFactory.openSession();
           transaction = session.beginTransaction();

           workflowEntry = loadEntry(session, entryId);

           transaction.commit();

       } catch (HibernateException hibernateException) {
           throw new WorkflowStoreException(hibernateException);
       } finally {

           if (transaction != null && transaction.isActive())
                transaction.rollback();

           if (session != null)
               session.close();
       }
       
       return workflowEntry;
   }
 
Example 40
Project: OSWf-OSWorkflow-fork   File: HibernateStore.java   View source code 5 votes vote down vote up
public List<Step> findHistorySteps(final long entryId) throws WorkflowStoreException {

        Session session = null;
        Transaction transaction = null;
        List<Step> steps = null;

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

            steps = loadEntry(session, entryId).getHistorySteps();

            transaction.commit();

         } catch (HibernateException hibernateException) {
            throw new WorkflowStoreException(hibernateException);
        } finally {

            if (transaction != null && transaction.isActive())
                 transaction.rollback();
            
            if (session != null)
                session.close();
        }
               
        return steps;
    }