public List<Topic> getRecentReplyTopics(int userId, Pager pager) { Map<Integer, UserProfile> authors = new HashMap<Integer, UserProfile>(); Cnd cnd = Cnd.where("userId", "=", userId); cnd.desc("createTime"); Sql sql = Sqls.queryString("select DISTINCT topicId from t_topic_reply $cnd") .setEntity(dao.getEntity(TopicReply.class)) .setVar("cnd", cnd); pager.setRecordCount( dao.execute( Sqls.fetchInt("select count(DISTINCT topicId) from t_topic_reply $cnd") .setEntity(dao.getEntity(TopicReply.class)) .setVar("cnd", cnd)) .getInt()); sql.setPager(pager); String[] replies_topic_ids = dao.execute(sql).getObject(String[].class); List<Topic> recent_replies = new ArrayList<Topic>(); for (String topic_id : replies_topic_ids) { Topic _topic = dao.fetch(Topic.class, topic_id); if (_topic == null) continue; recent_replies.add(_topic); } if (!recent_replies.isEmpty()) { for (Topic topic : recent_replies) { fillTopic(topic, authors); } } return recent_replies; }
public void addComment(Dao dao, Entity<?> en, String commentTable, String commentColumn) { if (!en.hasTableComment() && !en.hasColumnComment()) { return; } List<Sql> sqls = new ArrayList<Sql>(); // 表注释 if (en.hasTableComment()) { Sql tableCommentSQL = Sqls.create(Strings.isBlank(commentTable) ? DEFAULT_COMMENT_TABLE : commentTable); tableCommentSQL .vars() .set("table", en.getTableName()) .set("tableComment", en.getTableComment()); sqls.add(tableCommentSQL); } // 字段注释 if (en.hasColumnComment()) { for (MappingField mf : en.getMappingFields()) { if (mf.hasColumnComment()) { Sql columnCommentSQL = Sqls.create(Strings.isBlank(commentColumn) ? DEFAULT_COMMENT_COLUMN : commentColumn); columnCommentSQL .vars() .set("table", en.getTableName()) .set("column", mf.getColumnName()) .set("columnComment", mf.getColumnComment()); sqls.add(columnCommentSQL); } } } // 执行创建语句 dao.execute(sqls.toArray(new Sql[sqls.size()])); }
@At @Ok("raw") public boolean del(@Param("id") String id) { boolean res; Sql sql = Sqls.create("delete from sys_unit where id like @id"); sql.params().set("id", id + "%"); res = daoCtl.exeUpdateBySql(dao, sql); if (res) { daoCtl.exeUpdateBySql( dao, Sqls.create( "delete from sys_role_resource where roleid in(" + "select id from sys_role where unitid like '" + id + "%')")); daoCtl.exeUpdateBySql( dao, Sqls.create( "delete from sys_user_role where userid in(" + "select userid from sys_user where unitid like '" + id + "%')")); daoCtl.exeUpdateBySql( dao, Sqls.create("delete from sys_user where unitid like '" + id + "%'")); daoCtl.exeUpdateBySql( dao, Sqls.create("delete from sys_role where unitid like '" + id + "%'")); } return res; }
@Override public Sql makeDropSql(DTable td) { ComboSql sql = new ComboSql(); sql.add(Sqls.create("DROP TABLE " + td.getName())); for (DField df : td.getAutoIncreaments()) { sql.add(Sqls.create(gSQL(DSEQ, td.getName(), df.getName()))); // sql.addSQL(new ExecutableSql(gSQL(DTRI, td.getName(), // df.getName()))); } return sql; }
// TODO not tested!! public boolean createEntity(Dao dao, Entity<?> en) { StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "("); // 创建字段 for (MappingField mf : en.getMappingFields()) { sb.append('\n').append(mf.getColumnName()); sb.append(' ').append(evalFieldType(mf)); // 非主键的 @Name,应该加入唯一性约束 if (mf.isName() && en.getPkType() != PkType.NAME) { sb.append(" UNIQUE NOT NULL"); } // 普通字段 else { if (mf.isNotNull() || mf.isPk()) sb.append(" NOT NULL"); if (mf.hasDefaultValue()) sb.append(" DEFAULT '").append(getDefaultValue(mf)).append('\''); if (mf.isAutoIncreasement()) sb.append(" generated by default as identity "); if (mf.isPk() && en.getPks().size() == 1) { sb.append(" primary key "); } } sb.append(','); } // 结束表字段设置 sb.setCharAt(sb.length() - 1, ')'); // 执行创建语句 dao.execute(Sqls.create(sb.toString())); // 创建联合主键 if (en.getPks().size() > 1) { sb = new StringBuilder(); sb.append("ALTER TABLE ").append(en.getTableName()).append(" ADD CONSTRAINT PK_"); sb.append(makePksName(en)); sb.append(" PRIMARY KEY ("); for (MappingField mf : en.getPks()) { sb.append(mf.getColumnName()).append(","); } sb.setCharAt(sb.length() - 1, ')'); dao.execute(Sqls.create(sb.toString())); } // 创建关联表 createRelation(dao, en); // 创建索引 dao.execute(createIndexs(en).toArray(new Sql[0])); // 添加注释(表注释与字段注释) addComment(dao, en); return true; }
public boolean dropEntity(Dao dao, Entity<?> en) { String tableName = en.getTableName(); String viewName = en.getViewName(); try { dropRelation(dao, en); if (!tableName.equals(viewName) && dao.exists(viewName)) { dao.execute(Sqls.create("DROP VIEW " + viewName)); } dao.execute(Sqls.create("DROP TABLE " + tableName)); } catch (Exception e) { return false; } return true; }
/** 查询某sql的结果条数 */ public static long queryCount(Dao dao, String sql) { Sql sql2 = Sqls.fetchInt( "select count(1) from (" + sql + ") as _nutz_tmp_" + System.currentTimeMillis()); dao.execute(sql2); return sql2.getInt(); }
/** * 根据用户ID查询出服务时数 * * @return */ public double findTime(int uid) { Sql sql = Sqls.create( "select sum(services_number) as w from t_personservices where uid=" + uid + " and queren=1"); sql.setCallback( new SqlCallback() { public Object invoke(Connection arg0, ResultSet rs, Sql sql) throws SQLException { Object o = new Object(); if (rs.next()) { o = rs.getObject("w"); } rs.close(); return o; } }); dao.execute(sql); Object o = sql.getResult(); if (o != null) { return Double.parseDouble(o.toString()); } return 0; }
@Override public List<Item> listWithSkuByOrder(long orderId) { String exp = "select i.id as 'i.id', i.sku_id as 'i.sku_id', i.sku_more_id as 'i.sku_more_id'\n" + " , i.dprice as 'i.dprice', i.dcount as 'i.dcount', i.payment as 'i.payment'\n" + " , i.return_time as 'i.return_time', i.return_reason as 'i.return_reason'" + " , i.return_desc as 'i.return_desc'\n" + " , i.state as 'i.state', i.order_id as 'i.order_id'\n" + " , g.cate_code as 's.cate_code', g.gname as 's.gname', sku.img as 's.img'\n" + " , sku.model as 's.model', sku.sprice as 's.sprice', sm.size as 's.size'\n" + "from t_item i\n" + "inner join t_sku sku on sku.id = i.sku_id\n" + "inner join t_sku_more sm on sm.id = i.sku_more_id\n" + "inner join t_goods g on g.id = sku.goods_id\n" + "where i.order_id = @orderId"; Sql sql = Sqls.queryRecord(exp); sql.params().set("orderId", orderId); dao.execute(sql); List<Record> list = sql.getList(Record.class); List<Item> itemList = new ArrayList<Item>(); for (Record re : list) { Item item = re.toEntity(dao.getEntity(Item.class), "i."); Sku4Item skuInfo = re.toEntity(dao.getEntity(Sku4Item.class), "s."); item.setSku(skuInfo); itemList.add(item); } return itemList; }
public static int getRecordSize(Dao dao, String s) { Sql _s = Sqls.create("select count(*) nums from ( " + s + " )"); _s.setCallback(Sqls.callback.entity()); _s.setEntity(dao.getEntity(Record.class)); dao.execute(_s); return ((Record) _s.getResult()).getInt("nums"); }
public static List getRecords(Dao dao, String sql, Class t) { Sql s = Sqls.create(sql); s.setCallback(Sqls.callback.entities()); s.setEntity(dao.getEntity(t)); dao.execute(s); return s.getList(Record.class); }
private void resourceRelationFull(Resource resource) { List<Tag> tags; Sql sql_resource = Sqls.create( "select * from tag as t, resource_tag as rt where rt.resource_id = " + resource.getId() + " and rt.tag_id = t.id"); sql_resource.setCallback(Sqls.callback.entities()); sql_resource.setEntity(dao.getEntity(Tag.class)); dao.execute(sql_resource); tags = sql_resource.getList(Tag.class); List<UserInfo> user = dao.query(UserInfo.class, Cnd.where("id", "=", resource.getAuthor())); if (user.size() > 0) { resource.setUserInfo(user.get(0)); } else { System.out.print("resourceservice:用户id无效"); } String tagString = ""; // 资源tag回填 for (int i = 0; i < tags.size(); i++) { if (i < (tags.size() - 1)) { tagString = tagString + tags.get(i).getName() + ","; } else { tagString = tagString + tags.get(i).getName(); } } resource.setTags(tagString); resource.setTagEntityList(tags); }
protected List<Sql> createIndexs(Entity<?> en) { List<Sql> sqls = new ArrayList<Sql>(); StringBuilder sb = new StringBuilder(); List<EntityIndex> indexs = en.getIndexes(); for (EntityIndex index : indexs) { sb.setLength(0); if (index.isUnique()) sb.append("Create UNIQUE Index "); else sb.append("Create Index "); if (index.getName().contains("$")) sb.append(TableName.render(new CharSegment(index.getName()))); else sb.append(index.getName()); sb.append(" ON ").append(en.getTableName()).append("("); for (EntityField field : index.getFields()) { if (field instanceof MappingField) { MappingField mf = (MappingField) field; sb.append(mf.getColumnNameInSql()).append(','); } else { throw Lang.makeThrow( DaoException.class, "%s %s is NOT a mapping field, can't use as index field!!", en.getClass(), field.getName()); } } sb.setCharAt(sb.length() - 1, ')'); sqls.add(Sqls.create(sb.toString())); } return sqls; }
/** * 无and关系的tag查询 * * @param tagIds 标签ids * @param order * @param pager * @return */ public List<Resource> resourceTagSearch(Integer tagId, String order, Pager pager) { List<Resource> query = null; if (tagId != null) { Sql sql_resource = Sqls.create( "select * from resource as r, resource_tag as rt where rt.resource_id = r.id and rt.tag_id = " + tagId); sql_resource.setCallback(Sqls.callback.entities()); sql_resource.setEntity(dao.getEntity(Resource.class)); dao.execute(sql_resource); query = sql_resource.getList(Resource.class); if (pager != null) { pager.setRecordCount(query.size()); } } else { System.out.print("resourceservice: tagid无效"); } for (Resource resource : query) { resourceRelationFull(resource); } return query; }
public static Record getRecord(Dao dao, String sql) { Sql s = Sqls.create(sql); s.setCallback(Sqls.callback.entity()); s.setEntity(dao.getEntity(Record.class)); dao.execute(s); return (Record) s.getResult(); }
public static Object getRecort(Dao dao, String sql, Class t) { Sql s = Sqls.create(sql); s.setCallback(Sqls.callback.entity()); s.setEntity(dao.getEntity(t)); dao.execute(s); return s.getResult(); }
public static List<Record> getRecords(Dao dao, String sql, int page, int size) { Sql s = Sqls.create(sql); s.setCallback(Sqls.callback.entities()); s.setPager(dao.createPager(page, size)); s.setEntity(dao.getEntity(Record.class)); dao.execute(s); return (List<Record>) s.getList(Record.class); }
public boolean createEntity(Dao dao, Entity<?> en) { StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "("); // 创建字段 for (MappingField mf : en.getMappingFields()) { if (mf.isReadonly()) continue; sb.append('\n').append(mf.getColumnName()); // 自增主键特殊形式关键字 if (mf.isId() && mf.isAutoIncreasement()) { sb.append(" SERIAL"); } else { sb.append(' ').append(evalFieldType(mf)); // 非主键的 @Name,应该加入唯一性约束 if (mf.isName() && en.getPkType() != PkType.NAME) { sb.append(" UNIQUE NOT NULL"); } // 普通字段 else { if (mf.isUnsigned()) sb.append(" UNSIGNED"); if (mf.isNotNull()) sb.append(" NOT NULL"); if (mf.isAutoIncreasement()) throw Lang.noImplement(); if (mf.hasDefaultValue()) sb.append(" DEFAULT '").append(getDefaultValue(mf)).append('\''); } } sb.append(','); } // 创建主键 List<MappingField> pks = en.getPks(); if (!pks.isEmpty()) { sb.append('\n'); sb.append( String.format( "CONSTRAINT %s_pkey PRIMARY KEY (", en.getTableName().replace('.', '_').replace('"', '_'))); for (MappingField pk : pks) { sb.append(pk.getColumnName()).append(','); } sb.setCharAt(sb.length() - 1, ')'); sb.append("\n "); } // 结束表字段设置 sb.setCharAt(sb.length() - 1, ')'); // 执行创建语句 dao.execute(Sqls.create(sb.toString())); // 创建索引 dao.execute(createIndexs(en).toArray(new Sql[0])); // 创建关联表 createRelation(dao, en); // 添加注释(表注释与字段注释) addComment(dao, en); return true; }
/** 查询sql并把结果放入传入的class组成的List中 */ public static <T> List<T> query( Dao dao, Class<T> classOfT, String sql, Condition cnd, Pager pager) { Sql sql2 = Sqls.queryEntity(sql); sql2.setEntity(dao.getEntity(classOfT)); sql2.setCondition(cnd); sql2.setPager(pager); dao.execute(sql2); return sql2.getList(classOfT); }
protected void dropRelation(Dao dao, Entity<?> en) { final List<Sql> sqls = new ArrayList<Sql>(5); for (LinkField lf : en.visitManyMany(null, null, null)) { ManyManyLinkField mm = (ManyManyLinkField) lf; if (!dao.exists(mm.getRelationName())) continue; sqls.add(Sqls.create("DROP TABLE " + mm.getRelationName())); } dao.execute(sqls.toArray(new Sql[sqls.size()])); }
@At @Ok("raw") public String addSave(@Param("..") Sys_unit unit) { String id = daoCtl.getSubMenuId(dao, "sys_unit", "id", Strings.sNull(unit.getId())); unit.setId(id); int location = daoCtl.getIntRowValue(dao, Sqls.create("select max(location) from sys_unit")); unit.setLocation(location); if (!daoCtl.add(dao, unit)) return ""; return id; }
/** * 查询某一次考试的科目名称 * * @param testid * @return 对应考试id的科目信息 */ public List<Subject> querysubject(int testid) { Sql sql = Sqls.create( "SELECT ts.* FROM t_subject ts JOIN t_test_subject tts ON tts.subject_id=ts.id where tts.test_id=@tid "); sql.params().set("tid", testid); sql.setCallback(Sqls.callback.entities()); sql.setEntity(dao().getEntity(Subject.class)); dao().execute(sql); List<Subject> list = sql.getList(Subject.class); return list; }
// @RequiresPermissions("topic:index:rebuild") public void rebuild() throws IOException { Sql sql = Sqls.queryString("select id from t_topic where tp='ask'"); dao.execute(sql); luceneIndex.writer.deleteAll(); String[] topicIds = sql.getObject(String[].class); for (String topicId : topicIds) { Topic topic = dao.fetch(Topic.class, topicId); bigContentService.fill(topic); _add(topic); } luceneIndex.writer.commit(); }
/** * 根据多个id删除数据 * * @param <T> * @param c 要操作的表信息 * @param ids 要删除的id,多个用","(逗号)分隔 * @return true 成功,false 失败 */ public <T> void deleteByIds(Class<T> c, String ids) { Entity<T> entity = dao.getEntity(c); String table = entity.getTableName(); String id = entity.getIdField().getColumnName(); Sql sql = Sqls.create("delete from " + table + " where " + id + " in(" + ids + ")"); dao.execute(sql); }
public void createRelation(Dao dao, Entity<?> en) { final List<Sql> sqls = new ArrayList<Sql>(5); for (LinkField lf : en.visitManyMany(null, null, null)) { ManyManyLinkField mm = (ManyManyLinkField) lf; if (dao.exists(mm.getRelationName())) continue; String sql = "CREATE TABLE " + mm.getRelationName() + "("; sql += mm.getFromColumnName() + " " + evalFieldType(mm.getHostField()) + ","; sql += mm.getToColumnName() + " " + evalFieldType(mm.getLinkedField()); sql += ")"; sqls.add(Sqls.create(sql)); } dao.execute(sqls.toArray(new Sql[sqls.size()])); }
@Override public Sql makeCreateSql(DTable td) { ComboSql sql = new ComboSql(); // Make create table SQL StringBuilder sb = new StringBuilder("CREATE TABLE ").append(td.getName()).append('('); appendAllFields(td, sb); // Append PK Iterator<DField> dfIt = td.getPks().iterator(); if (dfIt.hasNext()) { String names = dfIt.next().getName(); while (dfIt.hasNext()) names += "," + dfIt.next(); sb.append(',').append(gSQL(CPK, td.getName(), names)); } sb.append(')'); sql.add(Sqls.create(sb.toString())); // For all auto increaments fields, create the sequance and trigger for (DField df : td.getAutoIncreaments()) { // create sequance; sql.add(Sqls.create(gSQL(CSEQ, td.getName(), df.getName()))); // create trigger; sql.add(Sqls.create(gSQL(CTRI, td.getName(), df.getName()))); } return sql; }
/** * 通过特定的sql查询出用户按服务时间大小倒叙排序的总条数 * * @param str * @return */ public int findSqlCount(String str, String table) { Sql sql = Sqls.create("select count(*) from " + table + " where id in (" + str + ")"); sql.setCallback( new SqlCallback() { public Object invoke(Connection arg0, ResultSet rs, Sql sql) throws SQLException { while (rs.next()) { return rs.getInt(1); } return null; } }); dao.execute(sql); return sql.getInt(); }
/** * 按照tag分页查找 resource * * @param tagId 标签id * @param order * @param pager * @return */ public List<Resource> resourceTagSearchAnd(String tagIds, String order, Pager pager) { List<Resource> query = null; // 将tagids字符串拆分成id数组进行and查询 String[] ids = tagIds.split(","); if (ids.length > 0) { String sqlTagsResource = "select * from resource as r, resource_tag as rt where (rt.resource_id = r.id and rt.tag_id = " + Integer.parseInt(ids[0]) + ")"; for (int j = 1; j < ids.length; j++) { sqlTagsResource = sqlTagsResource + " and (r.id in (select r" + j + ".id from resource as r" + j + ", resource_tag as rt" + j + " where (rt" + j + ".resource_id = r" + j + ".id and rt" + j + ".tag_id = " + Integer.parseInt(ids[j]) + ")))"; } Sql sql_resource = Sqls.create(sqlTagsResource); sql_resource.setCallback(Sqls.callback.entities()); sql_resource.setEntity(dao.getEntity(Resource.class)); dao.execute(sql_resource); query = sql_resource.getList(Resource.class); if (pager != null) { pager.setRecordCount(query.size()); } for (Resource resource : query) { resourceRelationFull(resource); } } else { System.out.print("resourservice: tagids无效"); } return query; }
@At @Ok("raw") public boolean sortSave(@Param("checkids") String checkids, HttpSession session) { Sys_user user = (Sys_user) session.getAttribute("userSession"); String[] ids = StringUtils.split(checkids, ","); int initvalue = 0; if (!user.getSysrole()) // 判断是否为系统管理员角色 { initvalue = daoCtl.getIntRowValue( dao, Sqls.create( "select min(location) from sys_unit where id in " + StringUtils.split(checkids, ","))); } return daoCtl.updateSortRow(dao, "sys_unit", ids, "location", initvalue); }
/** * 获取tagNames * * @param tagIds 标签ids * @return */ public ArrayList<Tag> getTagNames(String tagIds) { ArrayList<Tag> tagNames = new ArrayList<Tag>(); String[] ids = tagIds.split(","); for (String id : ids) { String sqlTags = "select * from tag as t where t.id=" + id; Sql sql_resource = Sqls.create(sqlTags); sql_resource.setCallback(Sqls.callback.entities()); sql_resource.setEntity(dao.getEntity(Tag.class)); dao.execute(sql_resource); List<Tag> tags = sql_resource.getList(Tag.class); if (tags.size() > 0) { tags.get(0).setQuery(tagIds); tagNames.add(tags.get(0)); } else { System.out.print("resourceservice: tagid无效"); } } return tagNames; }