最近嫌弃手写SQL了,效率低下,又经常复制错误字段,写错漏写`,’; 以及字段名称写错。总感觉很烦人,又重复,故花了丢丢时间写了个SQL注解以及注解工具类用以解析。
本早就该写了,但是,太懒了,又太懒嫌弃写SQL了。。。唉,内心挣扎过一段时间之后还是花了丢度时间弄好了。。。
直接贴代码了,直接运行AnnotationUtil 的main方法就可以看到效果了。
如果有遇到什么bug,记得在下面的评论留言或者右下角私信我,谢谢!
有空再写个bean封装。。。
不想用beanutils。。。顺便手写复习一下姿势了。
效果如下:1
2
3
4
5----------- init end ------------
SELECT * FROM 666 WHERE `date`='null';
INSERT INTO 666(`name`,`age`,`date`) VALUES('king','年年十八','null');
UPDATE 666 SET`id`='10',`name`='king',`age`='年年十八' WHERE `date`='null';
----------- init end ------------
注解解析工具类
AnnotationUtil.java1
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332import exception.NotInitException;
import exception.RepeatInitException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class AnnotationUtil <T>{
private String selectSql ="SELECT *";
private String inserSql = "INSERT INTO";
private String updateSql = "UPDATE";
private String setSql = "SET";
private String FromSql = "FROM";
private String whereSql = "WHERE";
private String valuesSql = "VALUES";
private String andSql = "AND";
private String nowSql = "NOW()";
private String leftParentheses = "(";
private String rightParentheses = ")";
private String fieldStringType = "'";
private String fieldProtect = "`";
private String comma = ",";
private String semicolon = ";";
private String blankSpace = " ";
private String equal = "=";
private int length = 0;
private int whereLength = 0;
private int updateLength = 0;
private List<String> keyList = new ArrayList();
private List<String> valueList = new ArrayList();
private List<String> whereKeyList = new ArrayList();
private List<String> whereValueList = new ArrayList();
private List<String> updateKeyList = new ArrayList();
private List<String> updateValueList = new ArrayList();
private String table = null;
private String mySelectSql;
private String myInsertSql;
private String myUpdateSql;
private T t = null;
public AnnotationUtil(T t){
this.t = t;
}
private boolean initFlag = false;
public void init() throws RepeatInitException, IllegalAccessException {
if(initFlag){
throw new RepeatInitException("请勿重复初始化");
}
this.initFlag = true;
Class<?> clazz = t.getClass();
//获取注解在类上的注解
SqlAnnotation fieldUtil = clazz.getDeclaredAnnotation(SqlAnnotation.class);
String tableName = fieldUtil.tableName();
if(tableName == null || "".equals(tableName)){
table = clazz.getSimpleName();
} else {
table = tableName;
}
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
SqlAnnotation annotation = field.getAnnotation(SqlAnnotation.class);
//如果没有注解的字段自动忽略
if(annotation == null){
continue;
}
field.setAccessible(true);//强制获取私有字段数据
String name = field.getName();
String value = String.valueOf(field.get(t));
if(annotation.parm()){
length += 1;
keyList.add(name);
valueList.add(value);
/* if(!annotation.date()){
valueList.add(value);
} else {
valueList.add(nowSql);
}*/
}
if (annotation.where()){
whereLength +=1;
whereKeyList.add(name);
whereValueList.add(value);
/* if(!annotation.date()){
whereValueList.add(value);
} else {
whereValueList.add(nowSql);
}*/
} else { //用作于where的字段都不能被更新
if(annotation.notUpdate()){
continue;
}
updateLength += 1;
updateKeyList.add(name);
updateValueList.add(value);
/* if(!annotation.date()){
updateValueList.add(value);
} else {
updateValueList.add(nowSql);
}*/
}
}
//是否生成该语句
boolean select = fieldUtil.select();
boolean insert = fieldUtil.insert();
boolean update = fieldUtil.update();
if(select){
String sql = null;
StringBuffer sb = new StringBuffer();
sb.append(selectSql);
sb.append(blankSpace);//添加空格
sb.append(FromSql);
sb.append(blankSpace);//添加空格
sb.append(table);//添加表名
//添加条件
if(whereLength > 0){
sb.append(blankSpace);//添加空格
sb.append(whereSql);
sb.append(blankSpace);//添加空格
for (int i = 0; i < whereLength; i++) {
//添加字段名称
sb.append(fieldProtect);//添加`
sb.append(whereKeyList.get(i));
sb.append(fieldProtect);//添加`
sb.append(equal);//添加=
//添加值
sb.append(fieldStringType);//添加'
sb.append(whereValueList.get(i));
sb.append(fieldStringType);//添加'
if (i != whereLength -1){
sb.append(andSql);//添加AND
}
}
}
sb.append(semicolon);//添加结尾
sql = sb.toString();
//System.err.println(sql);
mySelectSql = sql;
}
if(insert){
String sql = null;
StringBuffer sb = new StringBuffer();
sb.append(inserSql);//添加开始
sb.append(blankSpace);//添加空格
sb.append(table);//添加表名
sb.append(leftParentheses);//添加左括号
//添加开头
for (int i = 0; i < length; i++) {
sb.append(fieldProtect);//添加`
sb.append(keyList.get(i));
sb.append(fieldProtect);//添加`
if (i != length -1){
sb.append(comma);//添加逗号
}
}
sb.append(rightParentheses);//添加右括号
sb.append(blankSpace);//添加空格
sb.append(valuesSql);
//添加值
sb.append(leftParentheses);//添加左括号
for (int i = 0; i < length; i++) {
sb.append(fieldStringType);//添加单引号
sb.append(valueList.get(i));
sb.append(fieldStringType);//添加单引号
if (i != length -1){
sb.append(comma);//添加逗号
}
}
sb.append(rightParentheses);//添加右括号
sb.append(semicolon);//添加结尾
sql = sb.toString();
//System.err.println(sql);
myInsertSql = sql;
}
if(update){
String sql = null;
StringBuffer sb = new StringBuffer();
sb.append(updateSql);//添加开始
sb.append(blankSpace);//添加空格
sb.append(table);//添加表名
sb.append(blankSpace);//添加空格
sb.append(setSql);
//更新
for (int i = 0; i < updateLength; i++) {
sb.append(fieldProtect);//添加`
sb.append(updateKeyList.get(i));
sb.append(fieldProtect);//添加`
sb.append(equal);//添加=
sb.append(fieldStringType);//添加单引号
sb.append(updateValueList.get(i));
sb.append(fieldStringType);//添加单引号
if (i != updateLength -1){
sb.append(comma);//添加逗号
}
}
//添加条件
if(whereLength > 0){
sb.append(blankSpace);//添加空格
sb.append(whereSql);
sb.append(blankSpace);//添加空格
for (int i = 0; i < whereLength; i++) {
//添加字段名称
sb.append(fieldProtect);//添加`
sb.append(whereKeyList.get(i));
sb.append(fieldProtect);//添加`
sb.append(equal);//添加=
//添加值
sb.append(fieldStringType);//添加'
sb.append(whereValueList.get(i));
sb.append(fieldStringType);//添加'
if (i != whereLength -1){
sb.append(andSql);//添加AND
}
}
}
sb.append(semicolon);//添加结尾
sql = sb.toString();
//System.err.println(sql);
myUpdateSql = sql;
}
System.err.println("----------- init end ------------");
System.err.println(mySelectSql);
System.err.println(myInsertSql);
System.err.println(myUpdateSql);
System.err.println("----------- init end ------------");
/* MysqlUtils declaredAnnotation = t.getClass().getDeclaredAnnotation(MysqlUtils.class);
boolean flag1 = declaredAnnotation.flag();
System.err.println(flag1);*/
/* Field[] declaredFields = t.getClass().getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
Field field = declaredFields[i];
Annotation[] declaredAnnotations = field.getDeclaredAnnotations();//获取所有的注解
for (int j = 0; j < declaredAnnotations.length; j++) {
Annotation annotation = declaredAnnotations[j];
if (annotation.annotationType().equals(FieldUtil.class)) {
boolean flag = ((FieldUtil) annotation).flag();
System.err.println(flag);
}
}
System.err.println(field.get(t));
}*/
}
public static void main(String[] args) throws Exception {
test t = new test();
t.id = 10;
t.name = "king";
t.age = "年年十八";
AnnotationUtil util = new AnnotationUtil(t);
util.init();
//util.init();
System.err.println(util.getSelectSql());
System.err.println(util.getInsertSql());
System.err.println(util.getUpdateSql());
}
public String getSelectSql() throws NotInitException {
check();
return this.mySelectSql;
}
public String getInsertSql() throws NotInitException {
check();
return this.myInsertSql;
}
public String getUpdateSql() throws NotInitException {
check();
return this.myUpdateSql;
}
public boolean check () throws NotInitException {
if (!this.initFlag){
throw new NotInitException("请初始化之后在进行操作!");
} else {
//System.err.println("已经初始化成功!");
return true;
}
}
public static void getVersion(){
System.err.println("v1.0");
}
}
注解类
SqlAnnotation.java1
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
72import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description
* @auther Gouzai
* @create 2019-06-12 23:56
*/
/**
* SQL 注解类,用于标记类信息
*/
({ElementType.FIELD,ElementType.TYPE})
(RetentionPolicy.RUNTIME)
public SqlAnnotation {
/**
* test
* @return
*/
public boolean flag() default false;
/**
*
* @return
*/
public String tableName() default "";
/**
* 是否生成查询语句
* @return
*/
public boolean select() default false;
/**
* 是否生成insert语句
* @return
*/
public boolean insert() default false;
/**
* 是否生成update语句
* @return
*/
public boolean update() default false;
/**
* 参数是否为时间字段
* @return
*/
public boolean date() default false;
/**
* 是否参与生成SQL
* @return
*/
public boolean parm() default false;
/**
* where 条件参数,更新的条件不能做where的参数
* @return
*/
public boolean where() default false;
/**
* 不要更新字段
* @return
*/
public boolean notUpdate() default false;
}
需要生成的sql的bean
test.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17/**
* @Description
* @auther Gouzai
* @create 2019-06-12 23:59
*/
"666",update = true,insert = true,select = true) (tableName =
public class test {
false) (flag =
public int id;
true) (parm =
public String name;
true,update = true) (parm =
public String age;
true ,date = true,where = true) (parm =
public String date;
}
自定义的两个异常,一个是重复初始化异常,一个是未初始化异常
NotInitException.java1
2
3
4
5
6
7
8
9
10import java.sql.SQLException;
/**
* 没有初始化异常
*/
public class NotInitException extends SQLException {
public NotInitException(String message){
super(message);
}
}
RepeatInitException.java1
2
3
4
5
6
7
8
9
10import java.sql.SQLException;
/**
* 重复初始化异常
*/
public class RepeatInitException extends SQLException {
public RepeatInitException(String message){
super(message);
}
}