需求:从数据库表中查询数据,并且以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);
}

/**
* 利用反射,读取book里面的属性
*/

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));
// System.out.println(f);
}
/**
* 使用流,将 属性名前面的去掉,留下简化的属性名
*/
fs = fs.stream().map(x->x.replaceAll(x,x.split("\\.")[x.split("\\.").length-1])).collect(Collectors.toList());
// System.out.println(fs);

/**
* 查询图书
*/
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){
//循环将数据库中的值set 到book类中
String stringValue = rs.getString(i);
String ColumnName = rd.getColumnName(i);
setValues(ColumnName,stringValue,book,fs);
//book中category代表数的种类,但是是用数字表示的,因此要转换成为name并且赋值
if(ColumnName.equals("category_id")){
for(category category: c){
if(category.getCategoryId()==Integer.valueOf(stringValue)){
book.setCategory_name(category.getCategoryName());
}
}
}
i++;
}
books.add(book);
// System.out.println();
}
// for(Book b:books){
// System.out.println(b);
// }
/**
* 利用jackson实现序列化
*/
//创建映射对象
ObjectMapper mapper = new ObjectMapper();

try {
String json = mapper.writeValueAsString(books);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}


}

/**
* 利用反射,调用 set方法
* @param ColumnName
* @param stringValue
* @param book
* @param fs
* @throws ClassNotFoundException
*/

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;
//我们这里要获得与之对应的属性,因为要调用set,必须得传参数进去,因此我们需要得到属性的类型
for(Field field:fields ){
if(ColumnName.equals(field.toString().split("\\.")[field.toString().split("\\.").length-1])){
f = field;
break;
}
}
//准备拼接set方法,将属性名称前面改为大写
String fileName = initStr(ColumnName);
try {

//拼接方法
Method setBookValue = clazz.getDeclaredMethod("set"+fileName,f.getType());
// System.out.println(f.getType());
//book属性中有integer类型,因此需要判断并且转换类型
if(f.getType().toString().equals("class java.lang.Integer")){
setBookValue.invoke(book,Integer.valueOf(stringValue));

}
//同理,有int类型
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();
}

}

/**
* 将首个字母大小写
* @param old
* @return
*/
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 + '\'' +
'}';
}
}