public AggregateOp(String sql, TryEffect1<PreparedStatement, SQLException> binder) { this.selectOp = new SelectOp.List<>(sql, binder, x -> x.getLong(1)); }
@Override public Long run(Connection c) throws SQLException { return selectOp.map(xs -> { Iterator<Long> resultIterator = xs.iterator(); if (!resultIterator.hasNext()) { throw new IllegalStateException("result is empty"); } Long result = resultIterator.next(); if (resultIterator.hasNext()) { throw new IllegalStateException("result has more than one row"); } return result; }).run(c); }
public static DB<List<Employee>> selectByIds(Iterable<Integer> ids) { return new SelectOp.List<>( format("SELECT ID, NAME, DEPARTMENT_ID FROM EMPLOYEES WHERE ID IN ({0}) ORDER BY ID", SqlStringUtils.placeholders(size(ids)) ), iterableBinder((idx, ps, id) -> { ps.setInt(idx++, id); return idx; }, ids), rs -> new Employee(rs.getInt(1), rs.getString(2), rs.getInt(3)) ); }
@Test public void insertGenKeys() { Integer id = DB.transact(new InsertGenKeysOp.Int( "INSERT INTO MySqlTest_IDS(DUMMY) VALUES (?)", ps -> ps.setString(1, "a"))); assertThat(id, is(notNullValue())); String str = DB.submit(DbOps .unique(new SelectOp.List<>("SELECT DUMMY FROM MySqlTest_IDS WHERE ID=?", ps -> ps.setInt(1, id), rs -> rs.getString(1)))).some(); assertThat(str, is("a")); }