@Test public void dateEqualityTest() throws ParseException { Book book = new Book(); book.setId(1); book.setReciever("Mario"); book.setAmountSent(2); SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy"); Date date = sdf.parse("24/11/2014"); book.setDateRecieved(date); Dao<Integer, Book> dao = dbLite.getDao(Book.class); long rowID = dao.create(book); Assert.assertEquals(book.getId(), rowID); Book book2 = new Book(); book2.setId(2); book2.setReciever("Mario"); book2.setAmountSent(2); book2.setDateRecieved(new Date()); long rowID2 = dao.create(book2); Assert.assertEquals(book2.getId(), rowID2); List<Book> books = dao.findAll(null, null, "dateRecieved > ?", date); Assert.assertTrue(books.size() > 0); }
@Test public void testNestedTransactions() throws Exception { Dao dao = handle.attach(Dao.class); Something s = dao.insertAndFetchWithNestedTransaction(1, "Ian"); assertThat(s, equalTo(new Something(1, "Ian"))); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); TextView tvTitle = (TextView) findViewById(R.id.pro_title); TextView tvWriter = (TextView) findViewById(R.id.pro_writer); TextView tvContent = (TextView) findViewById(R.id.pro_content); TextView tvWriteDate = (TextView) findViewById(R.id.pro_date); ImageView ivImage = (ImageView) findViewById(R.id.pro_img); String articleNumber = getIntent().getExtras().getString("ArticleNumber"); // dao 초기화 Dao dao = new Dao(getApplicationContext()); Article article = dao.getArticleByArticleNumber(Integer.parseInt(articleNumber)); tvTitle.setText(article.getTitle()); tvWriter.setText(article.getWriter()); tvContent.setText(article.getContent()); tvWriteDate.setText(article.getWriteDate()); try { InputStream ims = getApplicationContext().getAssets().open(article.getImgName()); Drawable d = Drawable.createFromStream(ims, null); ivImage.setImageDrawable(d); } catch (IOException e) { Log.e("test", "error: img stream"); } }
public static void main(String[] args) { try { Dao<Cliente> clienteDao = new Dao<Cliente>(Cliente.class); Cliente cliente = new Cliente("Gumga S/A"); clienteDao.salvar(cliente); List<Cliente> listClientes = clienteDao.buscaTodos(); listClientes .stream() .forEach( (c) -> { System.out.println(c); }); System.out.print("Buscando cliente com ID 1 ... "); cliente = clienteDao.buscaPorId(new Long(1)); if (cliente != null) { System.out.println("cliente encontrado " + cliente); } System.out.println("Excluindo cliente com ID = 1"); clienteDao.excluir(cliente); } catch (Exception e) { e.printStackTrace(); } finally { JpaUtil.close(); } }
/** * Create a revision. * * <p>This method doesn't check site id because ProjectControl interface is available only if * site is is valid. */ @Override public StoredWorkflowDefinition insertWorkflowDefinition( int projId, int revId, WorkflowDefinition def, ZoneId workflowTimeZone) throws ResourceConflictException { String configText = cfm.toText(def.getConfig()); String zoneId = workflowTimeZone.getId(); long configDigest = WorkflowConfig.digest(configText, zoneId); int configId; WorkflowConfig found = dao.findWorkflowConfigByDigest(projId, configDigest); if (found != null && WorkflowConfig.isEquivalent(found, configText, zoneId)) { configId = found.getId(); } else { configId = dao.insertWorkflowConfig(projId, configText, zoneId, configDigest); } long wfId = catchConflict( () -> dao.insertWorkflowDefinition(revId, def.getName(), configId), "workflow=%s in revision id=%d", def.getName(), revId); try { return requiredResource( dao.getWorkflowDefinitionById(siteId, wfId), "workflow id=%d", wfId); } catch (ResourceNotFoundException ex) { throw new IllegalStateException("Database state error", ex); } }
@Test public void findAllWithWhereClauseTest() { Date date = new Date(); @SuppressWarnings("deprecation") Date laterDate = new Date(date.getYear() + 1, 2, 4); ContentValues values = new ContentValues(); values.put("id", 1); values.put("body", "text"); values.put("date", date.getTime()); long id = db.insert("Note", null, values); Assert.assertTrue("Note instance not created", id > 0); values = new ContentValues(); values.put("id", 2); values.put("body", "text"); values.put("date", laterDate.getTime()); id = db.insert("Note", null, values); Assert.assertTrue("Note instance not created", id > 0); Dao<Integer, Note> dao = dbLite.getDao(Note.class); List<Note> notes = dao.findAll(null, null, "id=? AND body=?", "1", "text"); Assert.assertTrue("Empty List<Note> Returned", !notes.isEmpty()); Assert.assertEquals(1, notes.get(0).id); notes = dao.findAll(null, null, "date >= ?", date); Assert.assertTrue("Empty List<Note> Returned", !notes.isEmpty()); Assert.assertEquals(2, notes.size()); }
@Test public void testDoubleDbOpen() throws Exception { clearDatabases(); ConnectionSource cs = new JdbcConnectionSource( "jdbc:h2:file:" + DATABASE_DIR + "/" + DATABASE_NAME_PREFIX + ".1"); TableUtils.createTable(cs, Foo.class); Dao<Foo, Integer> dao = Instances.getDaoManager().createDao(cs, Foo.class); Foo foo1 = new Foo(); foo1.val = 12312; assertEquals(1, dao.create(foo1)); Foo result = dao.queryForId(foo1.id); assertNotNull(result); assertEquals(foo1.val, result.val); // ================================== cs = new JdbcConnectionSource( "jdbc:h2:file:" + DATABASE_DIR + "/" + DATABASE_NAME_PREFIX + ".2"); Instances.getDaoManager().clearCache(); TableUtils.createTable(cs, Foo.class); dao = Instances.getDaoManager().createDao(cs, Foo.class); Foo foo2 = new Foo(); foo2.val = 12314; assertEquals(1, dao.create(foo2)); result = dao.queryForId(foo2.id); assertNotNull(result); assertEquals(foo2.val, result.val); }
public void salvar(Setor t) { Integer id = t.getId(); if (id == null || id == 0) { dao.salvar(t); } else { dao.atualizar(t); } }
public static void main(String[] args) { Address a = new Address(); Dao.save(a); a.setZip(null); Dao.save(a); a.setZip("75001"); Dao.save(a); Dao.save(a); }
@Test public void createMethodGetterAndSetterTest() { Book book = new Book(); book.setDateRecieved(new Date()); book.setRecieved(true); book.setReciever("some"); Dao<Integer, Book> dao = dbLite.getDao(Book.class); long id = dao.create(book); Assert.assertTrue(id > 0); }
@Test public void createEntityWithStringPrimaryKeyTest() { NoteStringKey note = new NoteStringKey(); note.id = 2; note.body = "Body Text"; note.author = "John Doe"; Dao<String, NoteStringKey> dao = dbLite.getDao(NoteStringKey.class); long id = dao.create(note); Assert.assertTrue(id > 0); }
@Test public void createMethodTest() { Note note = new Note(); note.id = 2; note.body = "Body Text"; note.author = "John Doe"; Dao<Integer, Note> dao = dbLite.getDao(Note.class); long id = dao.create(note); Assert.assertTrue(id > 0); }
@Test public void testTxFail() throws Exception { Dao dao = handle.attach(Dao.class); try { dao.failed(1, "Ian"); fail("should have raised exception"); } catch (TransactionFailedException e) { assertThat(e.getCause().getMessage(), equalTo("woof")); } assertThat(dao.findById(1), nullValue()); }
@Override public <T extends Schedule> void updateSchedules( int projId, List<T> schedules, ScheduleUpdateAction<T> func) throws ResourceConflictException { Map<String, Integer> oldScheduleNames = idNameListToHashMap(dao.getScheduleNames(projId)); // Concurrent call of updateSchedules doesn't happen because having // ProjectControlStore means that the project is locked. // // However, ScheduleExecutor modifies schedules without locking the // project. Instead, ScheduleExecutor locks schedules. To avoid // concurrent update of schedules, here needs to lock schedules // before UPDATE. for (T schedule : schedules) { Integer matchedSchedId = oldScheduleNames.get(schedule.getWorkflowName()); if (matchedSchedId != null) { // found the same name. lock it and update ScheduleStatus status = dao.lockScheduleById(matchedSchedId); if (status != null) { ScheduleTime newSchedule = func.apply(status, schedule); dao.updateScheduleById( matchedSchedId, schedule.getWorkflowDefinitionId(), newSchedule.getRunTime().getEpochSecond(), newSchedule.getTime().getEpochSecond()); oldScheduleNames.remove(schedule.getWorkflowName()); } } else { // not found this name. inserting a new entry. catchConflict( () -> dao.insertSchedule( projId, schedule.getWorkflowDefinitionId(), schedule.getNextRunTime().getEpochSecond(), schedule.getNextScheduleTime().getEpochSecond()), "workflow_definition_id=%d", schedule.getWorkflowDefinitionId()); } } // delete unused schedules if (!oldScheduleNames.isEmpty()) { // those names don exist any more. handle .createStatement( "delete from schedules" + " where id " + inLargeIdListExpression(oldScheduleNames.values())) .execute(); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception { RequestDispatcher rd; try { // get db connection getConnection(); if ("initSchoolCompletion".equals(request.getParameter("report"))) { if (request.isUserInRole(Constants.Role_Admin)) { request.setAttribute("schoolList", Dao.getSchoolList(connection)); } else { request.setAttribute( "schoolList", Dao.getLimitedSchoolList(connection, getUmdPersonPk(request))); } rd = this.getServletContext().getRequestDispatcher(PRE_JSP_PARAMS + "/schoolCompletion.jsp"); rd.forward(request, response); } else if ("initRoadTester".equals(request.getParameter("report"))) { if (request.isUserInRole(Constants.Role_Admin)) { request.setAttribute("testerList", Dao.getTesterList(connection)); } else { request.setAttribute("testerList", getRoadTester(getLoggedInPerson(request))); } rd = this.getServletContext().getRequestDispatcher(PRE_JSP_PARAMS + "/roadTester.jsp"); rd.forward(request, response); } else if ("initInstructorExpiration".equals(request.getParameter("report"))) { rd = this.getServletContext() .getRequestDispatcher(PRE_JSP_PARAMS + "/instructorExpiration.jsp"); rd.forward(request, response); } else if ("initSchoolExpiration".equals(request.getParameter("report"))) { rd = this.getServletContext().getRequestDispatcher(PRE_JSP_PARAMS + "/schoolExpiration.jsp"); rd.forward(request, response); } else if (request.getParameter("showPage") != null) { rd = this.getServletContext() .getRequestDispatcher(PRE_JSP_PARAMS + "/" + request.getParameter("page") + ".jsp"); rd.forward(request, response); } else { createReport(request, response); } } catch (Exception e) { // show error page e.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); rd = this.getServletContext().getRequestDispatcher("/reportErrorPage.jsp"); rd.forward(request, response); } finally { closeConnection(); } }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); Dao dao = context.getBean("Dao", Dao.class); // User user = new User(); // user.setName("Kol"); List<User> users = dao.getAllUsers(); for (User user : users) { System.out.println(user); } }
@Test public void findAllMethodInstancesAddedToListTest() { ContentValues values = new ContentValues(); values.put("id", 1); values.put("body", "text"); long id = db.insert("Note", null, values); Assert.assertTrue(id > 0); Dao<Integer, Note> dao = dbLite.getDao(Note.class); List<Note> notes = dao.findAll(); Assert.assertTrue(notes.size() > 0); }
@Test public void testTxActuallyCommits() throws Exception { Handle h2 = dbi.open(); Dao one = handle.attach(Dao.class); Dao two = h2.attach(Dao.class); // insert in @Transaction method Something inserted = one.insertAndFetch(1, "Brian"); // fetch from another connection Something fetched = two.findById(1); assertThat(fetched, equalTo(inserted)); }
@Test public void isExistAnyRecordExistTest() { Dao<Integer, Note> dao = dbLite.getDao(Note.class); Assert.assertFalse("Note record was found", dao.isExist()); ContentValues values = new ContentValues(); values.put("id", 1); values.put("body", "text"); long id = db.insert("Note", null, values); Assert.assertTrue("Note instance not created", id > 0); Assert.assertTrue("No Note record was found", dao.isExist()); }
@Test public void isExistMethodTest() { ContentValues values = new ContentValues(); values.put("id", 1); values.put("body", "text"); long id = db.insert("Note", null, values); Assert.assertTrue("Note instance not created", id > 0); Note note = new Note(); note.id = 1; Dao<Integer, Note> dao = dbLite.getDao(Note.class); Assert.assertTrue("Note instance not found", dao.isExist(note)); }
@RequestMapping(method = RequestMethod.POST) public ModelAndView onSubmit(@ModelAttribute("command") About command, BindingResult result) { if (!StringUtils.hasText(command.getEmail())) { result.rejectValue("email", "email.required"); } if (command.getComments().length() > 32) { result.rejectValue("email", "email.length.exceeded"); } if (!StringUtils.hasText(command.getComments())) { result.rejectValue("comments", "comment.required"); } if (command.getComments().length() > 255) { result.rejectValue("comments", "comment.length.exceeded"); } if (result.hasErrors()) { return new ModelAndView("common/about", "command", command); } else { dao.insertComments(command); return new ModelAndView("common/aboutSuccess"); } }
@Test public void findByIdMethodTest() { Dao<Integer, Note> dao = dbLite.getDao(Note.class); ContentValues values = new ContentValues(); values.put("id", 4); values.put("body", "text"); values.put("author", "john doe"); values.put("date", new Date().toString()); values.put("sent", true); long id = db.insert("Note", null, values); Assert.assertTrue(id > 0); Note note = dao.findById((int) id); Assert.assertNotNull(note); }
private void updateTable(List list, final DefaultTableModel dftm) { int num = dftm.getRowCount(); for (int i = 0; i < num; i++) dftm.removeRow(0); Iterator iterator = list.iterator(); TbKhinfo khInfo; while (iterator.hasNext()) { List info = (List) iterator.next(); Item item = new Item(); item.setId((String) info.get(0)); item.setName((String) info.get(1)); khInfo = Dao.getKhInfo(item); Vector rowData = new Vector(); rowData.add(khInfo.getId().trim()); rowData.add(khInfo.getKhname().trim()); rowData.add(khInfo.getAddress().trim()); rowData.add(khInfo.getJian().trim()); rowData.add(khInfo.getBianma().trim()); rowData.add(khInfo.getTel().trim()); rowData.add(khInfo.getFax().trim()); rowData.add(khInfo.getLian().trim()); rowData.add(khInfo.getLtel().trim()); rowData.add(khInfo.getMail().trim()); rowData.add(khInfo.getXinhang().trim()); rowData.add(khInfo.getHao().trim()); dftm.addRow(rowData); } }
@Test public void deleteAll() { ContentValues values = new ContentValues(); values.put("id", 4); values.put("body", "text"); values.put("author", "john doe"); values.put("date", new Date().toString()); values.put("sent", true); long id = db.insert("Note", null, values); Assert.assertTrue("Insertion failed", id > 0); Dao<Integer, Note> dao = dbLite.getDao(Note.class); int rowsAffected = dao.deleteAll(); Assert.assertEquals(1, rowsAffected); }
/** * 解析数据关联关系 * * @param list * @param fieldName * @param keyMethod * @param table * @param refKey * @param ids * @throws NoSuchFieldException * @throws NoSuchMethodException * @throws IllegalAccessException * @throws InvocationTargetException */ private void parseReference( List<T> list, String fieldName, Method keyMethod, String table, String refKey, StringBuffer ids) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { Coupler<Entity> childCoupler = childCouplers.get(fieldName); Class<Entity> childClass = childCoupler.getClazz(); TreeDao<Entity> childDao = DaoFactory.getTreeDao(childClass); String childSql = buildChildQuerySql(table, refKey, ids, ordersMap, fieldName); if (entityClass == childClass) { int count = dao.count(childSql); if (count == 0) { return; } } List<Entity> childEntities = childDao.queryForTree(childSql); Class<?> fileType = entityClass.getDeclaredField(fieldName).getType(); if (fileType == List.class) { setListValue(list, keyMethod, fieldName, childEntities, childClass, refKey); } else { setSingleValue(list, keyMethod, fieldName, childEntities, childClass, fileType, refKey); } }
/** @see Dao#queryForAll() */ public List<T> queryForAll() { try { return dao.queryForAll(); } catch (SQLException e) { logMessage(e, "queryForAll threw exception"); throw new RuntimeException(e); } }
/** @see Dao#queryForFirst(PreparedQuery) */ public T queryForFirst(PreparedQuery<T> preparedQuery) { try { return dao.queryForFirst(preparedQuery); } catch (SQLException e) { logMessage(e, "queryForFirst threw exception on: " + preparedQuery); throw new RuntimeException(e); } }
/** @see Dao#queryForId(Object) */ public T queryForId(ID id) { try { return dao.queryForId(id); } catch (SQLException e) { logMessage(e, "queryForId threw exception on: " + id); throw new RuntimeException(e); } }
/** @see Dao#rollBack(DatabaseConnection) */ public void rollBack(DatabaseConnection connection) { try { dao.rollBack(connection); } catch (SQLException e) { logMessage(e, "rollBack(" + connection + ") threw exception"); throw new RuntimeException(e); } }
/** @see Dao#commit(DatabaseConnection) */ public void commit(DatabaseConnection connection) { try { dao.commit(connection); } catch (SQLException e) { logMessage(e, "commit(" + connection + ") threw exception"); throw new RuntimeException(e); } }