• 关于

    list()

    的搜索结果

回答

public class ExportSql { private static String path = "D:\\test\\"; public static void main(String[] args) { String sql = "select report_id, label_id, label_name from tableName order by report_id"; List<List<Object>> listListTable = getTable(sql); List<List<Object>> listList = new ArrayList<List<Object>>(); for (int i = 0; i < listListTable.size(); i++) { if (i > 1 && !listListTable.get(i).get(0).equals(listListTable.get(i - 1).get(0))) { //跟上一个id不同换个文件 exportExcel(listList, listListTable.get(i - 1).get(1).toString()); listList.clear(); listList.add(listListTable.get(i)); } else { listList.add(listListTable.get(i)); } if (i == listListTable.size() - 1) { exportExcel(listList, listListTable.get(i).get(1).toString()); } } } //根据sql获得数据 public static List<List<Object>> getTable(String sql){ List<List<Object>> listList = new ArrayList<List<Object>>(); Connection conn = getConnection(); PreparedStatement pstmt; ResultSet rs; try { pstmt = conn.prepareStatement(sql.trim()); rs = pstmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()){ List<Object> list = new ArrayList<Object>(); for (int i = 0; i < rsmd.getColumnCount(); i++){ list.add(rs.getString(rsmd.getColumnName(i+1))); } listList.add(list); } }catch (Exception e) { e.printStackTrace(); }finally{ close(conn); } return listList; } // 生成excel public static void exportExcel(List<List<Object>> listList, String tableName){ listList.remove(1); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(tableName); sheet.autoSizeColumn(1); sheet.autoSizeColumn(1, true); for (int i = 0; i < listList.size(); i++){ Row row = sheet.createRow(i + 4); List<Object> list = listList.get(i); for (int j = 0; j < list.size(); j++){ Cell cell = row.createCell(j); if (list.get(j) != null){ cell.setCellValue(list.get(j).toString()); } } } OutputStream os = null; try { os = new FileOutputStream(path + tableName + ".xls"); wb.write(os); } catch (Exception e) { e.printStackTrace(); } finally { try { wb.close(); if (os != null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static Connection getConnection(){ Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/databaseName", "root", "123456"); } catch (Exception e) { e.printStackTrace(); } return conn; } public static void close(Connection conn){ if (conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } 正巧前几天写了个类似的工具,希望能帮助你。

蛮大人123 2019-12-02 02:06:42 0 浏览量 回答数 0

回答

List list = exampleService.queryForList(); response.reset();// 清空输出流 response.setHeader("Content-disposition", "attachment; filename=project.xls");// 设定输出文件头 response.setContentType("application/msexcel");// 定义输出类型 HSSFWorkbook wbook = new HSSFWorkbook(); try { OutputStream os = response.getOutputStream();// 从响应里获取输出流 HSSFSheet sheet = wbook.createSheet("项目");// 创建工作表 sheet.setDefaultColumnWidth(20);// 设置表格默认宽度 HSSFCellStyle style = wbook.createCellStyle();// 创建表格样式 style.setVerticalAlignment(CellStyle.ALIGN_CENTER);// 设置文本居中 HSSFRow row = sheet.createRow(0);// 表格标题行 HSSFCell cell = null; for (int i = 0; i < PSHOW.PROJECT_ARRAY.length; i++) { cell = row.createCell(i);// 给这一行添加一个表格 cell.setCellStyle(style); cell.setCellValue(PSHOW.PROJECT_ARRAY[i]);// 设置表格内容 } for (int i = 0; i < list.size(); i++) { int j = 0; row = sheet.createRow(i + 1); cell = row.createCell(j++); cell.setCellValue(list.get(i).getProjectName()); cell = row.createCell(j++); cell.setCellValue(list.get(i).getProjectNo()); cell = row.createCell(j++); cell.setCellValue(list.get(i).getCompany()); cell = row.createCell(j++); cell.setCellValue(list.get(i).getContactPerson()); cell = row.createCell(j++); cell.setCellValue(list.get(i).getContact()); cell = row.createCell(j++); cell.setCellValue(list.get(i).getCreateDate()); cell = row.createCell(j++); cell.setCellValue(list.get(i).getStartDate()); cell = row.createCell(j++); cell.setCellValue(list.get(i).getEndDate()); cell = row.createCell(j++); cell.setCellValue(list.get(i).getRemarks()); } wbook.write(os);// 写入到流中 os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } return null;

蛮大人123 2019-12-02 02:13:47 0 浏览量 回答数 0

回答

用poi吧,先读取excel表格数据,然后再写入到txt里面;给你个案例你看看 public class CreateExcel { private static List getstudent() throws Exception{ List list=new ArrayList(); SimpleDateFormat df=new SimpleDateFormat("yyyy-mm-dd"); Student stu=new Student(13, "张三", 14, df.parse("2015-3-3")); Student stu1=new Student(17, "张三", 18, df.parse("2015-3-4")); Student stu2=new Student(23, "张三", 21, df.parse("2015-3-5")); list.add(stu); list.add(stu1); list.add(stu2); return list; } public static void main(String[] args) { //第一步,创建一个webbook,对应一个excel文件 HSSFWorkbook wb=new HSSFWorkbook(); //第二步,在webbook中添加一个sheet,对应excel文件中的sheet HSSFSheet sheet=wb.createSheet("学生表一"); //第三步,在sheet中添加表头第0行 HSSFRow row=sheet.createRow((int)0); //第四步,创建单元格,并设置表头 设置表头居中 HSSFCellStyle style=wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建一个居中表格 HSSFCell cell=row.createCell((short)0); cell.setCellValue("学号"); cell.setCellStyle(style); cell=row.createCell((short)1); cell.setCellValue("姓名"); cell.setCellStyle(style); cell = row.createCell((short) 2); cell.setCellValue("年龄"); cell.setCellStyle(style); cell = row.createCell((short) 3); cell.setCellValue("生日"); cell.setCellStyle(style); //第五步,写入实体数据 try { List list=CreateExcel.getstudent(); for(int i=0;i<list.size();i++){ row=sheet.createRow((int)i+1); Student str=(Student) list.get(i); //第六步创建单元格,并设置值 row.createCell(0).setCellValue(str.getId()); row.createCell(1).setCellValue(str.getName()); row.createCell(2).setCellValue(str.getAge()); row.createCell(3).setCellValue(new SimpleDateFormat("yyy-mm-dd").format(str.getBirth())); } //第七步将文件存到指定位置 FileOutputStream fout=new FileOutputStream("D:/student.txt"); wb.write(fout); fout.close(); } catch (Exception e) { e.printStackTrace(); } } }

蛮大人123 2019-12-02 01:53:04 0 浏览量 回答数 0

阿里云试用中心,为您提供0门槛上云实践机会!

0元试用32+款产品,最高免费12个月!拨打95187-1,咨询专业上云建议!

问题

在Android中使用Gson解析json

爵霸 2019-12-01 19:26:23 833 浏览量 回答数 1

问题

【新人】关于ztree,后台怎么查询可以快速形成一棵部门人员树?

杨冬芳 2019-12-01 20:17:35 3025 浏览量 回答数 1

回答

使用迭代法,求证给定集合中元素的唯一性。 public class C{ static boolean sole(List list){ if (list.getItemCount()==1) return true; if ((list.getItemCount()==2) && (list.getItem(0).compareTo(list.getItem(1))==0)) return true; if ((list.getItem(0).compareTo(list.getItem(1))!=0)) return false; list.remove(0); return sole(list); } public static void main(String args[]){ List list = new List(); list.add("earth"); list.add("earth"); list.add("earth"); list.add("earthquake"); System.out.println(sole(list)); } }

海边一只船 2020-05-25 20:56:10 0 浏览量 回答数 0

问题

Android Collections排序相关问题

爵霸 2019-12-01 19:26:39 894 浏览量 回答数 1

问题

List 存放 Map 的get的前面元素 被覆盖

蛮大人123 2019-12-01 20:18:46 1002 浏览量 回答数 1

回答

package cn.uestc.fz; class Node{ int data; Node next; public Node(int data,Node next){ this.data=data; this.next=next; } } public class LinkedList { Node head; public void add(Node node){ if(head==null) head=node; else{ Node p=head; while(p.next!=null) p=p.next; p.next=node; } } public int length(){ return this.length(head); } public int length(Node node){ if(node==null) return 0; else if(node.next==null) return 1; else return 1+this.length(node.next); } public void printList(){ Node p=head; while(p!=null){ System.out.print(p.data+"->"); p=p.next; } System.out.println(); } public static void main(String args[]){ LinkedList list = new LinkedList(); list.add(new Node(1,null)); list.add(new Node(2,null)); list.add(new Node(3,null)); list.add(new Node(4,null)); list.add(new Node(5,null)); list.add(new Node(6,null)); list.printList(); System.out.println(list.length()); } } 刚写的。

liujae 2019-12-02 01:24:39 0 浏览量 回答数 0

回答

第一种 使用自带的JsonArray 解析,代码如下: //通过自带的JsonArray public List<Person> getListPersonByArray(String jsonString){ List<Person> personList=new ArrayList<Person>(); try { JSONArray jsonArray=new JSONArray(json); Log.e("ceshi", jsonArray.length()+"长度"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject= (JSONObject) jsonArray.get(i); personList.add(new Person(jsonObject.optInt("id"), jsonObject.optString("name"), jsonObject.optInt("age"))); } return personList; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } 第二种 使用Gson解析,代码如下://通过Gson解析 public List<Person> getListPersonByGson(String jsonString) { List<Person> list = new ArrayList<Person>(); Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken<List<Person>>() { }.getType()); return list; } Activity中onCreate中的代码:@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // List list=getListPersonByGson(json); List<Person> list=getListPersonByArray(json); for (int i = 0; i < list.size(); i++) { Log.e("ceshi", list.get(i).getName()); } } ps:来源网络

元芳啊 2019-12-02 00:54:49 0 浏览量 回答数 0

回答

如果需求变化不大!mybatis也是个不错的选择######既然是SSH,那么就交给Spring来管理你的hibernate的sessionFactory, 然后通过sessionFactory来进行相应的数据操作。 Spring和Hibernate的集成,google下,应该有很多标准的配置。######可以看下springside里面的dao,封装的不错######我用ssh做一个增删改查的小案例,用的很模糊,各位朋友可否指导一下呢,小弟谢过了.###### /** 写一段给你,希望对你有帮助 * / import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.; import org.hibernate.; import org.hibernate.type.Type; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class BaseHibernateDao extends HibernateDaoSupport { public BaseHibernateDao() { } public void delete(Object entity) { getHibernateTemplate().delete(entity); } public void delete(Serializable id, Class clazz) { delete(getEntity(id, clazz)); } public void deleteAll(Collection c) { for (Iterator iter = c.iterator(); iter.hasNext(); delete(iter.next())); } public void evict(Object entity) { getHibernateTemplate().evict(entity); } public void executeSql(String sql) { Connection con; Session session = getSession(); con = session.connection(); PreparedStatement pst = null; try { pst = con.prepareStatement(sql); pst.execute(); pst.close(); } catch (Exception e) { throw new BusinessException("执行SQL语句时出错!", e); } finally { if (pst != null) try { pst.close(); } catch (SQLException e) { throw new BusinessException("执行SQL语句时出错!", e); } } } public void flush() { getHibernateTemplate().flush(); } private Query genQuery(String hql, Object conditionValues[]) { Query query = genQuery(hql); setQueryConditionValue(hql, conditionValues, query); return query; } private Query genQuery(String hql) { return getSession().createQuery(hql); } public List getEntities(String hql, Object conditionValues[]) { Query query = genQuery(hql, conditionValues); return query.list(); } public List getEntities(String hql) { Query query = genQuery(hql); return query.list(); } public List getEntities(String hql, Object conditionNames[], Object conditionValues[]) { Query query = getQuery(hql, conditionNames, conditionValues); return query.list(); } public Query getQuery(String hql, Object conditionNames[], Object conditionValues[]) { if (conditionNames.length != conditionValues.length) throw new BusinessException("参数和值的数组长度不匹配,长度必需相等!"); getHibernateTemplate().setCacheQueries(true); Query query = getSession().createQuery(hql); if (conditionValues != null) { for (int i = 0; i < conditionValues.length; i++) { Object param = conditionValues[i]; if (param == null) throw new BusinessException((new StringBuilder("执行HQL为:")).append(hql).append(" 查询的时候验证参数出错,第 ").append(i + 1).append(" 个参数值为null!").toString()); if (param instanceof Object[]) query.setParameterList((String)conditionNames[i], (Object[])param); else if (param instanceof Collection) query.setParameterList((String)conditionNames[i], (Collection)param); else query.setParameter((String)conditionNames[i], param); } } return query; } public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], Object conditionValues[]) { SQLQuery query = getSession().createSQLQuery(nativeSql); if (kids.length != clazzs.length) throw new BusinessException("参数和值的数组长度不匹配,长度必需相等!"); if (clazzs != null) { for (int i = 0; i < clazzs.length; i++) query.addEntity(kids[i], clazzs[i]); } if (conditionValues != null) { for (int i = 0; i < conditionValues.length; i++) { Object param = conditionValues[i]; if (param == null) throw new BusinessException((new StringBuilder("执行原生SQL为:")).append(nativeSql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为null!").toString()); if (param instanceof Object[]) throw new BusinessException((new StringBuilder("执行原生SQL为:")).append(nativeSql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为数组!").toString()); if (param instanceof Collection) throw new BusinessException((new StringBuilder("执行原生SQL为:")).append(nativeSql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为列表!").toString()); query.setParameter(i, param); } } return query.list(); } public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], Object conditionValues[], String scalars[], Type types[]) { SQLQuery query = getSession().createSQLQuery(nativeSql); if (clazzs != null) { for (int i = 0; i < clazzs.length; i++) query.addEntity(kids[i], clazzs[i]); } return null; } public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[]) { SQLQuery query = getSession().createSQLQuery(nativeSql); if (clazzs != null) { for (int i = 0; i < clazzs.length; i++) query.addEntity(kids[i], clazzs[i]); } return query.list(); } public List getEntitiesByNativeSql(String nativeSql, String kids[], Class clazzs[], String as[], Type atype[]) { return null; } public Object getEntity(Serializable id, Class clazz) { Object entity = getHibernateTemplate().get(clazz, id); return entity != null ? entity : BeanUtil.newInstance(clazz); } public Object insert(Object entity) { getHibernateTemplate().save(entity); return entity; } public Object loadEntity(Serializable id, Class clazz) { Object entity = getHibernateTemplate().load(clazz, id); return entity != null ? entity : BeanUtil.newInstance(clazz); } public Object save(Object entity) { if (LogUtil.getIdentify(entity) == null) getHibernateTemplate().save(entity); else getHibernateTemplate().saveOrUpdate(entity); return entity; } private void setQueryConditionValue(String hql, Object conditionValues[], Query query) { if (conditionValues != null) { for (int i = 0; i < conditionValues.length; i++) { Object param = conditionValues[i]; if (param == null) throw new BusinessException((new StringBuilder("执行HQL为:")).append(hql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为null!").toString()); if (param instanceof Object[]) throw new BusinessException((new StringBuilder("执行HQL为:")).append(hql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为数组!").toString()); if (param instanceof Collection) throw new BusinessException((new StringBuilder("执行HQL为:")).append(hql).append(" 验证参数时出错,第 ").append(i + 1).append(" 个参数值为列表!").toString()); query.setParameter(i, param); } } } public Object uniqueResult(String hql, Object conditionValues[]) { Query query = genQuery(hql, conditionValues); return query.uniqueResult(); } public Object update(Object entity) { getHibernateTemplate().update(entity); return entity; } public void updateOrDelete(String hql) { Session session = getSession(); Query query = session.createQuery(hql); query.executeUpdate(); session.flush(); session.clear(); } public void updateOrDelete(String hql, Object conditionValues[]) { Session session = getSession(); Query query = session.createQuery(hql); setQueryConditionValue(hql, conditionValues, query); query.executeUpdate(); session.flush(); session.clear(); } public void updateOrDetete(String hql, Map map) { Query query = getQuery(hql, map.keySet().toArray(), map.values().toArray()); query.executeUpdate(); getSession().flush(); getSession().clear(); } public List getAllEntitys(Class clazz, String sort[]) { StringBuffer hql = new StringBuffer("select o from "); hql.append(clazz.getName()).append(" o "); String as[]; int j = (as = sort).length; for (int i = 0; i < j; i++) { String sor = as[i]; if (sor != null && !"".equals(sor)) hql.append(" order by ").append(sor); } return getEntities(hql.toString()); } public PageInfo getEntities_Page(String hql, Object conditionNames[], Object conditionValues[], PageInfo page) { Long totalCount = getTotalCount(hql, conditionNames, conditionValues); Long totalPages = new Long((new Double(Math.ceil(totalCount.longValue() / page.getPageSize().longValue()))).intValue()); totalPages = Long.valueOf(totalCount.longValue() % page.getPageSize().longValue() != 0L ? totalPages.longValue() + (new Long(1L)).longValue() : totalPages.longValue()); PageInfo pageInfo = new PageInfo(); pageInfo.setPageSize(page.getPageSize()); pageInfo.setPage(page.getPage()); pageInfo.setTotalSize(totalCount); pageInfo.setPageCount(totalPages); Query query = getQuery(hql, conditionNames, conditionValues); query.setFirstResult((page.getPage().intValue() - 1) * page.getPageSize().intValue()); query.setMaxResults(page.getPageSize().intValue()); List list = query.list(); pageInfo.setData(list); return pageInfo; } private Long getTotalCount(String hql, Object conditionNames[], Object conditionValues[]) { Long totalCount = new Long(0L); String lowerhql = hql.toLowerCase(); String totalHql = new String(""); int fIndex = lowerhql.indexOf(" from "); if (fIndex < 0) fIndex = 0; else fIndex++; int orderLastIndex = lowerhql.lastIndexOf(" order by "); if (orderLastIndex > 0) totalHql = (new StringBuilder("select count(*) ")).append(hql.substring(fIndex, orderLastIndex)).append(" ").toString(); else totalHql = (new StringBuilder("select count(*) ")).append(hql.substring(fIndex)).append(" ").toString(); List list = getEntities(totalHql, conditionNames, conditionValues); Number num = (Number)list.get(0); totalCount = new Long(num.longValue()); return totalCount; } protected User getOper() { User oper = (User)SingleThreadImpl.getInstance().get("user_context"); return oper; } }######O(∩_∩)O谢谢,非常有用.######批量删除建议修改下,效率太慢.

kun坤 2020-06-09 11:45:32 0 浏览量 回答数 0

问题

通过hibernate 获取jdbc连接。执行批处理..数据更新不进去?报错

爱吃鱼的程序员 2020-06-22 19:26:22 0 浏览量 回答数 1

回答

思路是挨个挨个Map遍历,将结果放入一个汇总的map,希望有更漂亮的方案 public class MapMerge { public static void main(String[] args) { List<HashMap<String,Integer>> list = generate(); HashMap<String,String> result = new HashMap<>(); HashMap<String,Integer> tmpmap = new HashMap<>(); //循环遍历每个Map,合并成一个大的map for (int i = 0; i < list.size(); i++) { //遍历Map中的每一个元素 tmpmap = list.get(i); if(tmpmap==null||tmpmap.size()<1){ continue; } Iterator<String> it = tmpmap.keySet().iterator(); while(it.hasNext()){ String key = it.next(); Integer value = tmpmap.get(key); //如果在结果中已经存在key, if(result.containsKey(key)){ //该键已经统计过了 }else{ //前i个hashmap里面没有值,把剩下的hashmap的值挨个取出. StringBuilder sb = new StringBuilder(); for (int j = 0; j < i; j++) { sb.append(";-1"); } for (int j = i; j < list.size(); j++) { sb.append(";"+getValue(list.get(j),key)); } sb.deleteCharAt(0); result.put(key, sb.toString()); } } } System.out.println("map合并以后:\n" + result); } private static int getValue(HashMap<String,Integer> map,String key){ Integer result = map.get(key); return result==null?-1:result; } //随机构造n个hashmap public static List<HashMap<String,Integer>> generate(){ List<HashMap<String,Integer>> list = new ArrayList<>(); Random r = new Random(); int i=(int) (Math.round(Math.random()*3 + 3));//hashMap的数量 System.out.println("输入hashMap的数量: "+i); int tmpSize = 0; HashMap tmpmap = null; for (int j = 0; j < i; j++) { tmpmap = new HashMap<String,Integer>(); //hashMap的长度 tmpSize = (int) (Math.round(Math.random()*10 + 4)); for (int k = 0; k < tmpSize; k++) { //随机键值对 String key = String.valueOf((char)(int) (Math.round(Math.random()*25 + 97))); int value = (int) (Math.round(Math.random()*8 + 1)); tmpmap.put(key, value); } list.add(tmpmap); System.out.println(tmpmap); } return list; } }

蛮大人123 2019-12-02 02:43:15 0 浏览量 回答数 0

回答

/** * 查询分页 */ @Override public List query(final BizClaimVoucher bcv, final Integer curPage, final Integer pageSize, final SysEmployee emp) { List list = this.getHibernateTemplate().executeFind( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { String hql = "from BizClaimVoucher where 1=1"; if (emp != null) { hql += "and sysEmployeess.name='" + emp.getName() + "'"; } if (bcv != null) { if (bcv.getStatus() != null && !bcv.getStatus().equals("全部")) { hql += "and status ='" + bcv.getStatus() + "'"; } if (bcv.getCreateTime() != null && bcv.getCreateTime().equals("")) { hql += "and createTime>=to_date('" + bcv.getCreateTime() + "','YYYY-MM-DD HH24:MI:SS')"; } if (bcv.getModifyTime() != null && bcv.getModifyTime().equals("")) { hql += "and modifyTime<=to_date('" + bcv.getModifyTime() + "','YYYY-MM-DD HH24:MI:SS')"; } } Query query = null; query = session.createQuery(hql); query.setFirstResult((curPage - 1) * pageSize); query.setMaxResults(pageSize); return query.list(); } }); return list; } ** * 总记录条数 */ @Override public int selectCount(BizClaimVoucher bcv, SysEmployee emp) { int count = 0; try { String hql = "from BizClaimVoucher where 1=1"; if (emp != null) { hql += "and sysEmployeess.name='" + emp.getName() + "'"; } if (bcv != null) { if (bcv.getStatus() != null && !bcv.getStatus().equals("全部")) { hql += "and status ='" + bcv.getStatus() + "'"; } if (bcv.getCreateTime() != null && bcv.getCreateTime().equals("")) { hql += "and createTime>=to_date('" + bcv.getCreateTime() + "','YYYY-MM-DD HH24:MI:SS')"; } if (bcv.getModifyTime() != null && bcv.getModifyTime().equals("")) { hql += "and modifyTime<=to_date('" + bcv.getModifyTime() + "','YYYY-MM-DD HH24:MI:SS')"; } } List list = this.getHibernateTemplate().find(hql); if (list != null) { count = list.size(); } } catch (Exception e) { e.printStackTrace(); } return count;

云栖技术 2019-12-02 02:32:10 0 浏览量 回答数 0

问题

Springmvc中 controller如何返回不同的modelandview?

蛮大人123 2019-12-01 20:08:49 2222 浏览量 回答数 1

回答

import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class ConcurrentList { //private static List TEST_LIST = new CopyOnWriteArrayList (); private static List TEST_LIST = Collections.synchronizedList(new ArrayList ()); public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (TEST_LIST) { TEST_LIST.add("11"); } System.out.println("Thread1 running"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (TEST_LIST) { for (String at : TEST_LIST) { TEST_LIST.add("22"); } } System.out.println("Thread2 running"); } } }).start(); } }

景凌凯 2020-04-10 21:07:50 0 浏览量 回答数 0

回答

你从数据库获取数据的代码有问题,应该用List先获取到所有的数据,然后在遍历这个List,提前userId相同的账户问题信息。 我给你完整代码如下:你只需要修改queryData过程将ResultSet的数据存入list中返回即可。你可以先运行看结果,再修改。祝好。 代码如下: public class WeiboDataExtract { public List<WeiboData> queryData(){ List<WeiboData> list = new ArrayList<WeiboData>(); list.add(new WeiboData("1","hello")); list.add(new WeiboData("1","world")); list.add(new WeiboData("1","I want to change you!")); list.add(new WeiboData("2","Haha")); return list; } public void extract(List<WeiboData>datas){ Map<String,StringBuffer> map = new HashMap<String,StringBuffer>(); //遍历数据 for(WeiboData data:datas){ StringBuffer buffer = map.get(data.getUserId()); //map中没有该微博账户,新建数据并存储 if(buffer==null){ buffer= new StringBuffer(); map.put(data.getUserId(), buffer); } //将该账户的文本信息收集起来 buffer.append(data.getText()+"\r\n"); } //遍历map输出到文件 for(Entry<String, StringBuffer> entry:map.entrySet()){ String userId = entry.getKey(); StringBuffer value = entry.getValue(); writeToFile("d:/"+userId+".txt",value.toString(),true,"GB2312"); } } public void writeToFile(String fileName, String content,boolean append,String charset){ if(fileName==null||"".equals(fileName)){ return; } if(content==null||"".equals(content)){ return; } //默认编码格式为UTF-8 if(charset==null){ charset = "UTF-8"; } //将字符串写入到文件输出流中 OutputStreamWriter osw = null; try { osw = new OutputStreamWriter(new FileOutputStream(fileName, append), charset); osw.write(content + "\r\n"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(osw!=null){ try { osw.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { WeiboDataExtract d = new WeiboDataExtract(); d.extract(d.queryData()); } } 用到的一个类如下: public class WeiboData { private String userId; private String text; public WeiboData(String userId, String text) { super(); this.userId = userId; this.text = text; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getText() { return text; } public void setText(String text) { this.text = text; } }

蛮大人123 2019-12-02 01:52:49 0 浏览量 回答数 0

问题

JFinal中非web项目事务无效 :报错

kun坤 2020-06-14 16:00:51 0 浏览量 回答数 1

问题

JFinal中非web项目事务无效:配置报错 

kun坤 2020-06-02 15:31:08 0 浏览量 回答数 1

问题

Arraylist的一个问题从数据库拿到多组数据但是只能读出一组

蛮大人123 2019-12-01 20:20:55 915 浏览量 回答数 1

回答

public class Demo { public static Random ran = new Random(); public static void main(String[] args) { try { solution(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //获取50个随机数 public static List<Integer> test() { List<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < 50; i++) { arr.add(i+1); } return arr; } //逻辑处理 public static void solution() throws Exception{ List<Integer> res = new ArrayList<Integer>(); List<Integer> list = test(); for (int i = 0; i < 7; i++) { for(int j = 0; j< 7;j++){ int a = ran.nextInt(list.size()); res.add(list.get(a)); list.remove(list.get(a)); } } write2Txt(res.toString());//写到文本 System.out.println("50个数字剩余的最后一个数字="+list.get(0));//输出到控制台 } //字符串写出到文本 public static void write2Txt(String str) throws Exception{ FileWriter fw = null; String path = "C:\\Users\\db2admin\\Desktop\\txt.txt"; File f = new File(path); try { if (!f.exists()) { f.createNewFile(); } fw = new FileWriter(f); BufferedWriter out = new BufferedWriter(fw); // FileOutputStream fos = new FileOutputStream(f); // OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8"); out.write(str.toString()); out.close(); System.out.println("===========写入文本成功========"); } catch (IOException e) { e.printStackTrace(); } } }

蛮大人123 2019-12-02 02:34:05 0 浏览量 回答数 0

回答

简单的聊天室: server: import java.net.*; import java.io.*; import java.util.*; public class ServerSocketDemo { public static void main(String[] args) { ArrayList list = new ArrayList(); ServerSocket ss = null; try { ss =new ServerSocket(8189); while(true) { Socket s=ss.accept(); list.add(s); new ReverseDemo(s,list); } }catch( Exception ex ) { } try { ss.close(); }catch( Exception ex ) { } } } import java.net.*; import java.io.*; import java.util.*; public class ReverseDemo extends Thread { BufferedReader in=null; PrintWriter out=null; String str="abc"; ArrayList list; Socket s; public ReverseDemo(Socket s,ArrayList list) { this.list=list; this.s=s; this.start(); } public void run() { try { InputStream inStream = s.getInputStream(); OutputStream outStream = s.getOutputStream(); PrintWriter out = new PrintWriter(outStream, true /* autoFlush */); System.out.println(s.getInetAddress().getHostAddress()+" connected-------"); out.println("连接成功!"); byte[] buf = new byte[1024]; while(true) { int bytes_read = inStream.read( buf ); if( bytes_read < 0 ) { break; } else { broadcast( buf, 0, bytes_read ); } } } catch (Exception ex) { ex.printStackTrace(); } finally { list.remove( s ); } } void broadcast( byte[] b, int offset, int length ) { for( int i = 0, n = list.size(); i < n; i++ ) { Socket sock = (Socket) list.get( i ); if( sock != s ) { try { sock.getOutputStream().write( b, offset, length ); sock.getOutputStream().flush(); }catch( Exception ex ) { } } } } } client: import java.io.*; import java.net.*; import java.util.*; /** This program makes a socket connection to the atomic clock in Boulder, Colorado, and prints the time that the server sends. */ public class SocketTest { private Socket sock_; private byte[] name_; public SocketTest( String host, int port, byte[] name ) throws Exception { name_ = name; sock_ = new Socket( host, port ); Thread th = new Thread( createMsgRecvRunnable() ); th.start(); byte[] b = new byte[ 1024 ]; int bytes_read = readMsg( b ); while( bytes_read > 0 ) { sendMsg( b, 0, bytes_read ); bytes_read = readMsg( b ); } } private Runnable createMsgRecvRunnable() { return new Runnable() { public void run() { try { InputStream in = sock_.getInputStream(); byte[] buf = new byte[1024]; while( true ) { int bytes_read = in.read( buf ); if( bytes_read < 0 ) { break; } else { System.out.write( buf, 0, bytes_read ); } } }catch( Exception ex ) { } } }; } private int readMsg( byte[] b ) throws Exception { return System.in.read( b ); } private void sendMsg( byte[] msg, int offset, int length ) throws Exception { sock_.getOutputStream().write( name_ ); sock_.getOutputStream().write( msg, offset, length ); sock_.getOutputStream().flush(); } public static void main( String[] args ) { try { String name = null; if( args.length > 0 ) { name = args[0] + ":"; } else { name = "unknown:"; } SocketTest test = new SocketTest( "localhost", 8189, name.getBytes() ); }catch( Exception ex ) { ex.printStackTrace(); } } }

蛮大人123 2019-12-02 02:07:41 0 浏览量 回答数 0

回答

1. 查询整个映射对象所有字段 Java代码 //直接from查询出来的是一个映射对象,即:查询整个映射对象所有字段 String hql = "from Users"; Query query = session.createQuery(hql); List<Users> users = query.list(); for(Users user : users){ System.out.println(user.getName() + " : " + user.getPasswd() + " : " + user.getId()); } 输出结果为: name1 : password1 : 1 name2 : password2 : 2 name3 : password3 : 3 2.查询单个字段 Java代码 //查询单个字段 String hql = " select name from Users"; Query query = session.createQuery(hql); List<String> list = query.list(); for(String str : list){ System.out.println(str); } 输出结果为: name1 name2 name3 3.查询其中几个字段 Java代码 //查询其中几个字段 String hql = " select name,passwd from Users"; Query query = session.createQuery(hql); //默认查询出来的list里存放的是一个Object数组 List<Object[]> list = query.list(); for(Object[] object : list){ String name = (String)object[0]; String passwd = (String)object[1]; System.out.println(name + " : " + passwd); } 输出结果为: name1 : password1 name2 : password2 name3 : password3 4.修改默认查询结果(query.list())不以Object[]数组形式返回,以List形式返回 引用 //查询其中几个字段,添加new list(),注意list里的l是小写的。也不需要导入包,这样通过query.list()出来的list里存放的不再是默认的Object数组了,而是List集合了 String hql = " select new list(name,passwd) from Users"; Query query = session.createQuery(hql); //默认查询出来的list里存放的是一个Object数组,但是在这里list里存放的不再是默认的Object数组了,而是List集合了 List<List> list = query.list(); for(List user : list){ String name = (String)user.get(0); String passwd = (String)user.get(1); System.out.println(name + " : " + passwd); } /** 输出结果为: name1 : password1 name2 : password2 name3 : password3 */ 5.修改默认查询结果(query.list())不以Object[]数组形式返回,以Map形式返回 Java代码 收藏代码 //查询其中几个字段,添加new map(),注意map里的m是小写的。也不需要导入包,这样通过query.list()出来的list里存放的不再是默认的Object数组了,而是map集合了 String hql = " select new map(name,passwd) from Users"; Query query = session.createQuery(hql); //默认查询出来的list里存放的是一个Object数组,但是在这里list里存放的不再是默认的Object数组了,而是Map集合了 List<Map> list = query.list(); for(Map user : list){ //一条记录里所有的字段值都是map里的一个元素,key是字符串0,1,2,3....,value是字段值 //如果将hql改为:String hql = " select new map(name as username,passwd as password) from Users";,那么key将不是字符串0,1,2...了,而是"username","password"了 String name = (String)user.get("0");//get("0");是get(key),注意:0,1,2...是字符串,而不是整形 String passwd = (String)user.get("1"); System.out.println(name + " : " + passwd); } /** 输出结果为: name1 : password1 name2 : password2 name3 : password3 */ 6.修改默认查询结果(query.list())不以Object[]数组形式返回,以Set形式返回,但是因为Set里是不允许有重复的元素,所以:username和password的值不能相同。只需将hql改为:String hql = " select new set(name,passwd) from Users"; 7.修改默认查询结果(query.list())不以Object[]数组形式返回,以自定义类型返回 自定义类: Java代码 package com.domain; public class MyUser { private String username; private String password; //因为:String hql = " select new com.domain.MyUser(name,passwd) from Users";所以必须要有接受2个参数的构造函数 public MyUser(String username,String password){ this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } Java代码 //通过query.list()出来的list里存放的不再是默认的Object数组了,而是自定义的类MyUser,必须加包名,String hql = "from Users";中的Users类也是必须加包名的,但是因为再Users.hbm.xml里<hibernate-mapping auto-import="true"> auto-import默认值为true(所以auto-import属性也可以不写),自动导入了 String hql = " select new com.domain.MyUser(name,passwd) from Users"; Query query = session.createQuery(hql); //默认查询出来的list里存放的是一个Object数组,但是在这里list里存放的不再是默认的Object数组了,而是MyUser对象了 List<MyUser> myUsers = query.list(); for(MyUser myUser : myUsers){ String name = myUser.getUsername(); String passwd = myUser.getPassword(); System.out.println(name + " : " + passwd); } /** 输出结果为: name1 : password1 name2 : password2 name3 : password3 */ 8:条件查询 Java代码 //条件查询,参数索引值从0开始,索引位置。通过setString,setParameter设置参数 String hql = "from Users where name=? and passwd=?"; Query query = session.createQuery(hql); //第1种方式 // query.setString(0, "name1"); // query.setString(1, "password1"); //第2种方式 query.setParameter(0, "name1",Hibernate.STRING); query.setParameter(1, "password1",Hibernate.STRING); List<Users> list = query.list(); for(Users users : list){ System.out.println(users.getId()); } Java代码 //条件查询,自定义索引名(参数名):username,:password.通过setString,setParameter设置参数 String hql = "from Users where name=:username and passwd=:password"; Query query = session.createQuery(hql); //第1种方式 // query.setString("username", "name1"); // query.setString("password", "password1"); //第2种方式,第3个参数确定类型 query.setParameter("username", "name1",Hibernate.STRING); query.setParameter("password", "password1",Hibernate.STRING); List<Users> list = query.list(); for(Users users : list){ System.out.println(users.getId()); } Java代码 //条件查询,通过setProperties设置参数 String hql = "from Users where name=:username and passwd=:password"; Query query = session.createQuery(hql); //MyUser类的2个属性必须和:username和:password对应 MyUser myUser = new MyUser("name1","password1"); query.setProperties(myUser); List<Users> list = query.list(); for(Users users : list){ System.out.println(users.getId()); } [java] view plaincopy package com.hp.ts.bca.user.bo; import com.hp.ts.bca.common.BaseObject; public class StationUser extends BaseObject { private static final long serialVersionUID = -1175811459644997844L; private int id; private String username; private String officePhone; private String mobilePhone1; private String officeEmail; private Integer ifDefault; public StationUser(int id, String username, String officePhone, String mobilePhone1, String officeEmail, Integer ifDefault) { super(); this.id = id; this.username = username; this.officePhone = officePhone; this.mobilePhone1 = mobilePhone1; this.officeEmail = officeEmail; this.ifDefault = ifDefault; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getOfficePhone() { return officePhone; } public void setOfficePhone(String officePhone) { this.officePhone = officePhone; } public String getMobilePhone1() { return mobilePhone1; } public void setMobilePhone1(String mobilePhone1) { this.mobilePhone1 = mobilePhone1; } public String getOfficeEmail() { return officeEmail; } public void setOfficeEmail(String officeEmail) { this.officeEmail = officeEmail; } public Integer getIfDefault() { return ifDefault; } public void setIfDefault(Integer ifDefault) { if(ifDefault==null) ifDefault=0; else this.ifDefault = ifDefault; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((ifDefault == null) ? 0 : ifDefault.hashCode()); result = prime * result + ((mobilePhone1 == null) ? 0 : mobilePhone1.hashCode()); result = prime * result + ((officeEmail == null) ? 0 : officeEmail.hashCode()); result = prime * result + ((officePhone == null) ? 0 : officePhone.hashCode()); result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StationUser other = (StationUser) obj; if (id != other.id) return false; if (ifDefault == null) { if (other.ifDefault != null) return false; } else if (!ifDefault.equals(other.ifDefault)) return false; if (mobilePhone1 == null) { if (other.mobilePhone1 != null) return false; } else if (!mobilePhone1.equals(other.mobilePhone1)) return false; if (officeEmail == null) { if (other.officeEmail != null) return false; } else if (!officeEmail.equals(other.officeEmail)) return false; if (officePhone == null) { if (other.officePhone != null) return false; } else if (!officePhone.equals(other.officePhone)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } @Override public String toString() { return "StationUser [id=" + id + ", username=" + username + ", officePhone=" + officePhone + ", mobilePhone1=" + mobilePhone1 + ", officeEmail=" + officeEmail + ", ifDefault=" + ifDefault + "]"; } } [java] view plaincopy @Override public PageResponse<User> getUserListByStationId(int currentPage, int rowsPerPage, String sidx, String sord, Integer stationId) { StringBuilder hql = new StringBuilder(); hql.append("select new com.hp.ts.bca.user.bo.StationUser(a.id,a.username,a.officePhone,a.mobilePhone1,a.officeEmail,ug.ifDefault) FROM User a, UserGroup ug WHERE a.id=ug.userId and ug.groupId="); hql.append(stationId); //hql.append("FROM User AS user, UserGroup AS ug WHERE user.id=ug.userId"); PageResponse<User> userList = this.groupDao.excutePage(hql.toString(), currentPage, rowsPerPage, sidx, sord); return userList; }

小旋风柴进 2019-12-02 02:11:27 0 浏览量 回答数 0

问题

Java中能否利用函数参数来返回值 报错

因为相信,所以看见。 2020-05-27 10:04:03 8 浏览量 回答数 1

问题

ArrayLIst集合遍历中CPU暴增问题

蛮大人123 2019-12-01 20:15:36 991 浏览量 回答数 1

问题

java 递归输入一个ID 怎么把这个ID下所有的子ID 放入一个list里面

蛮大人123 2019-12-01 20:25:06 2303 浏览量 回答数 1

回答

public List getObject(String sql, Object[] object) { //sql执行语句,object是你sql语句里面的参数 List list = new ArrayList(); Connection con = null; PreparedStatement pre = null; ResultSet rs = null; try{ con = C3P0Util.getInstance().getConnection(); //这是你获得数据库连接,你把这里改成调用你自己写的jdbc方法 pre = con.prepareStatement(sql); //执行sql语句 if(object!=null){ for(int i=0;i<object.length;i++){ pre.setObject(i+1, object[i]); //给sql里面的参数进行赋值 } } rs = pre.executeQuery(); while(rs.next()){ Users u = new User(); u.setUserName(rs.getString("UserName")); u.setUserPas(rs.getString("UserPas")); list.add(u); } }catch(Exception e){ e.printStackTrace(); return null; }finally{ C3P0Util.close(con, pre, rs); //关闭数据库资源 } return list; //返回list集合 } 注意:list里面保存的是User对象的信息 你要获得User对象的信息,那么就要遍历list for(int i=0;i<list.size;i++){ User u = (User)list.get(i); System.out.println("UserName:"+u.getUserName()); System.out.println("UserPas:"+u.getUserPas()); } 上面是针对list里面有很多个User对象,当然list里面只有一个User对象,也是可以的。如果你的list里面只有一个User,那么可以直接:User u = (User)list.get(0);System.out.println("UserName:"+u.getUserName());System.out.println("UserPas:"+u.getUserPas());希望对你有帮助!

蛮大人123 2019-12-02 01:56:59 0 浏览量 回答数 0

问题

【android】如何定位listview中的某一项item呢

爵霸 2019-12-01 19:33:58 896 浏览量 回答数 1

问题

【android】怎么定位listview中的某一项item呢

爵霸 2019-12-01 19:41:33 734 浏览量 回答数 1

回答

import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public class SearchFile { private List<String> resultLsit = new ArrayList<String>(); private String fileName = null; public SearchFile(){ } public SearchFile(String basePaht,String regex,String suffix){ this.SearchFlieList(basePaht, regex, suffix); } public void SearchFlieList(String basePaht,String matchStr,String suffix){ File root = new File(basePaht); if(root!=null&&root.listFiles()!=null) for(File file:root.listFiles()){ if(file.isDirectory()) SearchFlieList(file.getAbsolutePath(),matchStr,suffix); else if(file.isFile()&&file.getName().endsWith(suffix)){ fileName = file.getName().contains(".")?file.getName().substring(0,file.getName().lastIndexOf(".")):file.getName(); if(matching(matchStr,fileName)) resultLsit.add(file.getAbsolutePath()); } } } private boolean matching(String matchStr,String targerStr){ matchStr = matchStr.replaceAll("\\*", ".*").replaceAll("\\?", "\\."); try { if(Pattern.compile(matchStr).matcher(targerStr).matches()) return true; } catch (Exception e) { return false; } return false; } public List<String> getResultLsit() { return resultLsit; } public void setResultLsit(List<String> resultLsit) { this.resultLsit = resultLsit; } public static void main(String[] args) { Long start = System.currentTimeMillis(); SearchFile searchFile = new SearchFile("d:/", "*ant*", ".jar"); for (String string : searchFile.getResultLsit()) { System.out.println(string); } System.out.println("耗时:"+(System.currentTimeMillis()-start)); } }

蛮大人123 2019-12-02 02:52:48 0 浏览量 回答数 0
阿里云大学 云服务器ECS com域名 网站域名whois查询 开发者平台 小程序定制 小程序开发 国内短信套餐包 开发者技术与产品 云数据库 图像识别 开发者问答 阿里云建站 阿里云备案 云市场 万网 阿里云帮助文档 免费套餐 开发者工具 企业信息查询 小程序开发制作 视频内容分析 企业网站制作 视频集锦 代理记账服务 2020阿里巴巴研发效能峰会 企业建站模板 云效成长地图 高端建站