使用hibernate 将图片等附件保存到blob中

/**
	 * 
	 * @param tstudent
	 *            将要保存到的对象
	 * @param f
	 *            要保存的对象
	 * @return 返回操作结果
	 */
	public String testBlob(Tstudent tstudent, File f) {
		Session s = null;
		byte[] buffer = new byte[1];
		buffer[0] = 1;
		try {		
			WebApplicationContext wac = ContextLoader
					.getCurrentWebApplicationContext();
			SessionFactory sf = (SessionFactory) wac.getBean("sessionFactory");
			s = sf.openSession();
			Transaction tx = s.beginTransaction();		
			tstudent.setStuHead(Hibernate.createBlob(buffer));		
			s.save(tstudent);
			s.flush();
			s.refresh(tstudent, LockMode.UPGRADE);
			SerializableBlob proxy = (SerializableBlob) tstudent.getStuHead();			
			BLOB blob = (BLOB) proxy.getWrappedBlob();
			OutputStream out = blob.getBinaryOutputStream();			
			FileInputStream fin = new FileInputStream(f);
			int count = -1, total = 0;
			byte[] data = new byte[(int) fin.available()];
			fin.read(data);
			out.write(data);
			fin.close();
			out.close();
			s.flush();
			tx.commit();
			return "success";
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "fail";
		} finally {
			if (s != null)
				try {
					s.close();
				} catch (Exception e) {
				}

		}

	}

 大家

希望可以有帮助

posted @ 2015-09-18 17:33  场者  阅读(958)  评论(0编辑  收藏  举报