List of usage examples for org.hibernate Session doWork
void doWork(Work work) throws HibernateException;
From source file:edu.psu.iam.cpr.core.database.tables.MatchingTable.java
License:Apache License
/** * The purpose of this function is to interface with the database and determine which data sets match a particular user. * @param db contains a database object//from w ww .ja va2s.c om * @param namesTable contains a names table object * @param addressesTable contains an addresses table object. * @param dateOfBirthTable contains a date of birth object. */ public void findMatches(final Database db, final NamesTable namesTable, final AddressesTable addressesTable, final DateOfBirthTable dateOfBirthTable) { final Session session = db.getSession(); session.doWork(new Work() { public void execute(Connection conn) throws SQLException { CallableStatement stmt = null; try { stmt = conn.prepareCall(FIND_MATCH_SET_SQL); // Set up output and input parameters. // Pass in the names match code if available. if (namesTable != null) { stmt.setString(NAME_MATCH_CODE, namesTable.getNamesBean().getNameMatchCode()); } else { stmt.setNull(NAME_MATCH_CODE, Types.VARCHAR); } // Pass in the addresses and city match code, state and postal code if available. if (addressesTable != null) { stmt.setString(ADDRESS_MATCH_CODE, addressesTable.getAddressesBean().getAddressMatchCode()); stmt.setString(CITY_MATCH_CODE, addressesTable.getAddressesBean().getCityMatchCode()); stmt.setString(STATE, addressesTable.getAddressesBean().getState()); stmt.setString(POSTAL_CODE, addressesTable.getAddressesBean().getPostalCode()); } else { stmt.setNull(ADDRESS_MATCH_CODE, Types.VARCHAR); stmt.setNull(CITY_MATCH_CODE, Types.VARCHAR); stmt.setNull(STATE, Types.VARCHAR); stmt.setNull(POSTAL_CODE, Types.VARCHAR); } // Pass in the date of birth if available. if (dateOfBirthTable != null) { stmt.setString(DATE_OF_BIRTH, dateOfBirthTable.getDateOfBirthBean().getDobChar()); } else { stmt.setNull(DATE_OF_BIRTH, Types.VARCHAR); } stmt.registerOutParameter(MATCH_SET_KEY, Types.INTEGER); // Execute the stored function. stmt.execute(); // Get the status from the database. setMatchSetKey(stmt.getLong(MATCH_SET_KEY)); } finally { try { stmt.close(); } catch (Exception e) { } } } }); }
From source file:es.indaba.jdbc.annotations.impl.AnnotationInterfaceObjectFactory.java
License:Open Source License
public Class buildClass(Class<T> type) { ProxyFactory factory = new ProxyFactory(); factory.setInterfaces(new Class[] { type }); factory.setHandler(new MethodHandler() { public Object invoke(Object arg0, Method method, Method arg2, Object[] parameters) throws Throwable { BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager(); Annotation[] annotations = method.getAnnotations(); DatabaseCall dbCall = AnnotationUtils.findAnnotation(beanManager, annotations, DatabaseCall.class); if (dbCall == null) return null; GenericWork callWork = AnnotationProcessor.buildWork(method, parameters); if (callWork == null) return null; // Get EM based on provided qualifier EntityManager manager = BeanProvider.getContextualReference(EntityManager.class, false, AnnotationInstanceProvider.of(dbCall.qualifier())); Session delegate = (Session) manager.getDelegate(); delegate.doWork(callWork); return callWork.getResultObject(); }/*from w w w. j ava2 s. c o m*/ }); Class c = factory.createClass(); return c; }
From source file:es.indaba.jdbc.annotations.impl.StoredProcedureInterceptor.java
License:Open Source License
@AroundInvoke public Object callProcedure(InvocationContext invocationContext) throws Exception { BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager(); Annotation[] annotations = invocationContext.getMethod().getAnnotations(); DatabaseCall dbCall = AnnotationUtils.findAnnotation(beanManager, annotations, DatabaseCall.class); if (dbCall == null) return null; GenericWork callWork = AnnotationProcessor.buildWork(invocationContext.getMethod(), invocationContext.getParameters()); // Get EM based on provided qualifier EntityManager manager = BeanProvider.getContextualReference(EntityManager.class, false, AnnotationInstanceProvider.of(dbCall.qualifier())); Session delegate = (Session) manager.getDelegate(); delegate.doWork(callWork); invocationContext.proceed();/*from w w w . j av a 2 s .com*/ return callWork.getResultObject(); }
From source file:guipratica.Initialize.java
private static void criaIndices() { /*SELECT 'CREATE INDEX fk_' || conname || '_idx ON ' || relname || ' ' || //from w ww .j a v a2 s . c o m regexp_replace( regexp_replace(pg_get_constraintdef(pg_constraint.oid, true), ' REFERENCES.*$','',''), 'FOREIGN KEY ','','') || ';' FROM pg_constraint JOIN pg_class ON (conrelid = pg_class.oid) JOIN pg_namespace ON (relnamespace = pg_namespace.oid) WHERE contype = 'f' AND nspname = 'public' AND NOT EXISTS ( SELECT * FROM pg_class pgc JOIN pg_namespace pgn ON (pgc.relnamespace = pgn.oid) WHERE relkind='i' AND pgc.relname = ('fk_' || conname || '_idx') );*/ Session s = null; //Cria os indices automaticamente try { s = HibernateUtil.getSessionFactory().openSession(); List<String> l = s .createSQLQuery("SELECT 'CREATE INDEX fk_' || conname || '_idx ON ' \n" + " || relname || ' ' || \n" + " regexp_replace(\n" + " regexp_replace(pg_get_constraintdef(pg_constraint.oid, true), \n" + " ' REFERENCES.*$','',''), 'FOREIGN KEY ','','') || ';'\n" + "FROM pg_constraint \n" + "JOIN pg_class \n" + " ON (conrelid = pg_class.oid)\n" + "JOIN pg_namespace\n" + " ON (relnamespace = pg_namespace.oid)\n" + "WHERE contype = 'f'\n" + " AND nspname = 'public'\n" + " AND NOT EXISTS (\n" + " SELECT pgc.relnamespace FROM pg_class pgc\n" + " JOIN pg_namespace pgn ON (pgc.relnamespace = pgn.oid)\n" + " WHERE relkind='i'\n" + " AND pgc.relname = ('fk_' || conname || '_idx') )") .list(); s.beginTransaction(); for (String l1 : l) { s.doWork((c) -> { c.createStatement().execute(l1); }); } } finally { if (s != null) { s.close(); } } }
From source file:hibernate.AllInOneTablesTest.java
License:Open Source License
public void testTables() { Session session = sessionFactory.openSession(); session.beginTransaction();// www .j a va 2 s. co m // final Category category = new Category(); category.setCatName(""); category.setCreateDate(new Date()); session.save(category);// ?sql insert??? assertNotNull("??Category???", category.getCatId()); // Article article = new Article(); // ? // hibernate??? article.setCategory(category); article.setTitle(""); article.setContent(""); article.setCreateDate(new Date()); article.setModifyDate(new Date()); article.setSummary("?"); article.setVisitCount(0); article.setIsPublished(Boolean.TRUE); article.setType("post"); article.setCommentStatus("open"); article.setArticleStatus("public"); article.setLink("http://localhost:8080/newblog/post/abce"); session.save(article); assertNotNull("??Article???", article.getArticleId()); // Tag tag0 = new Tag(); tag0.setTagName(""); tag0.setCreateDate(new Date()); session.save(tag0); assertNotNull("??Tag???", tag0.getTagId()); Tag tag1 = new Tag(); tag1.setTagName(""); tag1.setCreateDate(new Date()); session.save(tag1); assertNotNull("??Tag???", tag1.getTagId()); Tag tag2 = new Tag(); tag2.setTagName("?"); tag2.setCreateDate(new Date()); session.save(tag2); assertNotNull("??Tag???", tag2.getTagId()); Tag tag3 = new Tag(); tag3.setTagName(""); tag3.setCreateDate(new Date()); session.save(tag3); assertNotNull("??Tag???", tag3.getTagId()); // Set<Tag> ts = article.getTags(); ts.add(tag0); ts.add(tag1); ts.add(tag2); ts.add(tag3); // Comment comment0 = new Comment(); comment0.setCommentContent("1"); comment0.setCommentName("lichhao"); comment0.setCommentEmail("lichhaosysu@gmail.com"); comment0.setCommentUrl("http://lichhao.com/blog"); comment0.setCreateDate(new Date()); comment0.setArticle(article); session.save(comment0); Comment comment2 = new Comment(); comment2.setCommentContent("2"); comment2.setCommentName("lichhao"); comment2.setCommentEmail("lichhaosysu@gmail.com"); comment2.setCommentUrl("http://lichhao.com/blog"); comment2.setCreateDate(new Date()); session.save(comment2); Comment comment3 = new Comment(); comment3.setCommentContent("3"); comment3.setCommentName("lichhao3"); comment3.setCommentEmail("lichhaosysu@gmail.com"); comment3.setCommentUrl("http://lichhao.com/blog"); comment3.setCreateDate(new Date()); comment3.setArticle(article); session.save(comment3); Comment comment4 = new Comment(); comment4.setCommentContent("4"); comment4.setCommentName("lichhao"); comment4.setCommentEmail("lichhaosysu@gmail.com"); comment4.setCommentUrl("http://lichhao.com/blog"); comment4.setCreateDate(new Date()); session.save(comment4); Set<Comment> subComments = comment0.getSubComments(); subComments.add(comment2); subComments.add(comment4); session.getTransaction().commit(); session.close(); // ?? logger.info("??"); session = sessionFactory.openSession(); session.beginTransaction(); Article obj = (Article) session.load(Article.class, article.getArticleId()); session.delete(obj); session.flush(); Iterator<?> iterate = session.createQuery("from Tag").iterate(); Tag t = null; while (iterate.hasNext()) { t = (Tag) iterate.next(); session.delete(t); session.flush(); session.evict(t); } // hibernatesql?doReturningWork session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); stmt.executeUpdate("delete from category where cat_id = '" + category.getCatId() + "'"); stmt.close(); } }); session.getTransaction().commit(); session.close(); logger.info("???"); }
From source file:hibernate.TagAndArticleTest.java
License:Open Source License
public void testTagAndArticle() { Session session = sessionFactory.openSession(); session.beginTransaction();// w w w. j ava 2s . c om Tag tag = new Tag(); tag.setTagName(""); tag.setCreateDate(new Date()); session.save(tag); assertNotNull("??Tag???", tag.getTagId()); Tag tag1 = new Tag(); tag1.setTagName(""); tag1.setCreateDate(new Date()); session.save(tag1); assertNotNull("??Tag???", tag1.getTagId()); Tag tag2 = new Tag(); tag2.setTagName("?"); tag2.setCreateDate(new Date()); session.save(tag2); assertNotNull("??Tag???", tag2.getTagId()); Tag tag3 = new Tag(); tag3.setTagName(""); tag3.setCreateDate(new Date()); session.save(tag3); assertNotNull("??Tag???", tag3.getTagId()); Article article = new Article(); article.setTitle(""); article.setContent(""); article.setCreateDate(new Date()); article.setModifyDate(new Date()); article.setSummary("?"); article.setVisitCount(0); article.setIsPublished(Boolean.TRUE); article.setType("post"); article.setCommentStatus("open"); article.setArticleStatus("public"); article.setLink("http://localhost:8080/newblog/post/abce"); Set<Tag> ts = article.getTags(); ts.add(tag); ts.add(tag1); ts.add(tag2); ts.add(tag3); session.save(article); assertNotNull("??Article???", article.getArticleId()); article = new Article(); article.setTitle("2"); article.setContent("2"); article.setCreateDate(new Date()); article.setModifyDate(new Date()); article.setSummary("?2"); article.setVisitCount(0); article.setIsPublished(Boolean.TRUE); article.setType("post"); article.setCommentStatus("open"); article.setArticleStatus("public"); article.setLink("http://localhost:8080/newblog/post/abce2"); ts = article.getTags(); ts.add(tag); ts.add(tag1); ts.add(tag2); ts.add(tag3); session.save(article); assertNotNull("??Article???", article.getArticleId()); session.getTransaction().commit(); session.close(); session = sessionFactory.openSession(); session.beginTransaction(); List<Article> articles = session.createQuery( "select p from Article p left join fetch p.tags t where t.tagName = :tagName order by p.createDate desc") .setParameter("tagName", tag.getTagName()).list(); logger.debug("'" + tag.getTagName() + "'?:"); for (Article bean : articles) { session.refresh(bean); logger.debug("------------------------"); logger.debug("" + bean.getArticleId()); logger.debug("" + bean.getTitle()); logger.debug(""); for (Tag t : bean.getTags()) { logger.debug(t.getTagName()); } logger.debug("------------------------"); } // hibernatesql?doReturningWork session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); stmt.executeUpdate("delete from tag_article"); stmt.executeUpdate("delete from article"); stmt.executeUpdate("delete from tag"); stmt.close(); } }); session.getTransaction().commit(); session.close(); }
From source file:io.github.jonestimd.finance.dao.HibernateDaoContext.java
License:Open Source License
@Override public void generateSchema(List<String> postCreateScript) throws SQLException { String[] script = schemaCreationScript(); Session session = sessionFactory.openSession(); try {/*from ww w .j a v a 2 s . c o m*/ session.doWork(connection -> { executeSchemaScript(connection, Arrays.asList(script)); if (!postCreateScript.isEmpty()) executeSchemaScript(connection, postCreateScript); connection.commit(); }); } finally { session.close(); } }
From source file:it.scoppelletti.sdk.schemaupdate.JPALiquibase.java
License:Apache License
/** * Esegue l’aggiornamento del database. *//* www. j a v a 2s . c om*/ public void run() { org.hibernate.Session session; session = (org.hibernate.Session) myEntityMgr.getDelegate(); session.doWork(new JPALiquibase.LiquibaseWork()); }
From source file:kiwi.service.jdbc.HibernateJDBCServiceImpl.java
License:Open Source License
@Override public void execute(Work work) { // Mihai : This way to handle the JPA bounds this // implementation to Hibernate. Other ORM/JPA // implementations will cause here a ClassCastException final Session session = (Session) entityManager.getDelegate(); session.doWork(work); }
From source file:kp.dao.data.AttDao.java
public int saveAtt(MocWfAtt bean) { final Session session = HibernateUtil.getSessionFactory().openSession(); logger.log(Level.SEVERE, "SAVE ATTACHMENT HAS BEEN CALLED "); gm = new GeneralMethods(); try {/*w w w . j a v a 2 s.c om*/ final Transaction transaction = session.beginTransaction(); try { bean.setActDate(gm.getSysDate(session)); if (bean.getAttType().equalsIgnoreCase("RPT")) { //Generate Report session.doWork(new Work() { @Override public void execute(Connection cnctn) throws SQLException { try { String abslute_path = bean.getFPath() + "report"; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); Map parameters = new HashMap(); parameters.put("cid", bean.getCaseId()); JasperDesign jasperDesign = JRXmlLoader .load(abslute_path + "\\Jrxml\\MocReport.jrxml"); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, cnctn); JasperExportManager.exportReportToPdfStream(jasperPrint, outStream); bean.setFName("MOC_" + bean.getCaseId() + "_REPORT.pdf"); logger.log(Level.SEVERE, "Report Created :{0}", abslute_path + "\\" + bean.getFName()); JasperExportManager.exportReportToPdfFile(jasperPrint, abslute_path + "\\" + bean.getFName()); bean.setFPath("report\\" + bean.getFName()); } catch (JRException ex) { Logger.getLogger(AttDao.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { Logger.getLogger(AttDao.class.getName()).log(Level.SEVERE, "ATTACHMENT :" + bean.getCaseId()); } Logger.getLogger(AttDao.class.getName()).log(Level.SEVERE, "SAVING IT :" + bean.getCaseId()); session.save(bean); transaction.commit(); } catch (Exception ex) { // Log the exception here transaction.rollback(); Logger.getLogger(TsDao.class.getName()).log(Level.SEVERE, "Exception : "); throw ex; } } finally { session.close(); } Logger.getLogger(TsDao.class.getName()).log(Level.SEVERE, "CID : " + bean.getCaseId()); return bean.getCaseId(); }