需求:从数据库表中查询数据,并且以json的格式输出
由于类中的属性太多了,不想一个一个写了,所以使用反射直接set进去,这样比较方便,也比较实用,并且加深了对反射的理解。
并且使用了jackson 将List转换成了 json格式的字符串
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
| public class test { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/book_shop?useSSL=false","root","111111");
System.out.println("连接数据库成功");
Statement statement = null; statement= connection.createStatement(); ResultSet resultSet = null; resultSet = statement.executeQuery("SELECT * FROM TB_CATEGORY"); List<category> c = new ArrayList<>(); while (resultSet.next()){ category category = new category(); category.setCategoryId(resultSet.getInt(1)); category.setCategoryName(resultSet.getString(2)); c.add(category); }
Class clazz = Class.forName(Book.class.getName()); Field[] fields = clazz.getDeclaredFields(); List<String> fs = new ArrayList<>(); for (Field f: fields) { fs.add(String.valueOf(f));
}
fs = fs.stream().map(x->x.replaceAll(x,x.split("\\.")[x.split("\\.").length-1])).collect(Collectors.toList());
String sql = "SELECT * FROM TB_BOOK"; Statement st = null; st = connection.createStatement(); ResultSet rs = null; rs = st.executeQuery(sql); ResultSetMetaData rd = rs.getMetaData(); int count = rd.getColumnCount(); List<Book> books = new ArrayList<>(); while (rs.next()){ int i = 1; Book book = new Book(); while (i<count){ String stringValue = rs.getString(i); String ColumnName = rd.getColumnName(i); setValues(ColumnName,stringValue,book,fs); if(ColumnName.equals("category_id")){ for(category category: c){ if(category.getCategoryId()==Integer.valueOf(stringValue)){ book.setCategory_name(category.getCategoryName()); } } } i++; } books.add(book);
}
ObjectMapper mapper = new ObjectMapper();
try { String json = mapper.writeValueAsString(books); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); }
}
public static void setValues(String ColumnName,String stringValue, Book book,List<String> fs) throws ClassNotFoundException {
Class clazz = book.getClass(); Field[] fields = clazz.getDeclaredFields(); Field f = null; for(Field field:fields ){ if(ColumnName.equals(field.toString().split("\\.")[field.toString().split("\\.").length-1])){ f = field; break; } } String fileName = initStr(ColumnName); try {
Method setBookValue = clazz.getDeclaredMethod("set"+fileName,f.getType());
if(f.getType().toString().equals("class java.lang.Integer")){ setBookValue.invoke(book,Integer.valueOf(stringValue));
} else if(f.getType().toString().equals("int")){ setBookValue.invoke(book,Integer.valueOf(stringValue));
} else{ setBookValue.invoke(book,stringValue); }
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); }
}
public static String initStr(String old){ String str = old.substring(0,1).toUpperCase() + old.substring(1) ; return str ; }
}
|
Book类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| public class Book {
Integer book_id; Integer category_id; String category_name; String book_name; String author; String publisher;
int price; int sale_price; int amount;
public Integer getBook_id() { return book_id; }
public void setBook_id(Integer book_id) { this.book_id = book_id; }
public Integer getCategory_id() { return category_id; }
public void setCategory_id(Integer category_id) { this.category_id = category_id; }
public String getCategory_name() { return category_name; }
public void setCategory_name(String category_name) { this.category_name = category_name; }
public String getBook_name() { return book_name; }
public void setBook_name(String book_name) { this.book_name = book_name; }
public int getSale_price() { return sale_price; }
public void setSale_price(int sale_price) { this.sale_price = sale_price; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public String getPublisher() { return publisher; }
public void setPublisher(String publisher) { this.publisher = publisher; }
public int getPrice() { return price; }
public void setPrice(int price) { this.price = price; }
public int getAmount() { return amount; }
public void setAmount(int amount) { this.amount = amount; }
@Override public String toString() { return "Book{" + "book_id=" + book_id + ", category_id=" + category_id + ", category_name='" + category_name + '\'' + ", book_name='" + book_name + '\'' + ", author='" + author + '\'' + ", publisher='" + publisher + '\'' + ", price=" + price + ", sale_price=" + sale_price + ", amount=" + amount + '}'; } }
|
categorie 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class category { Integer categoryId; String categoryName;
public Integer getCategoryId() { return categoryId; }
public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; }
public String getCategoryName() { return categoryName; }
public void setCategoryName(String categoryName) { this.categoryName = categoryName; }
@Override public String toString() { return "category{" + "categoryId=" + categoryId + ", categoryName='" + categoryName + '\'' + '}'; } }
|