当前位置:网站首页>注解式编程小记
注解式编程小记
2022-08-11 05:13:00 【SunForYou】
自定义注解@Column
package com.hzcominfo.hermes_study;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String value();
}
自定义注解@Table
package com.hzcominfo.hermes_study;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();
}
测试用实体类
package com.hzcominfo.hermes_study;
@Table(value = "student")
public class Student {
@Column(value = "name")
private String name;
@Column(value = "age")
private int age;
@Column(value = "xh")
private String xh;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
}
测试用main方法
public static void main(String[] args) {
Student s = new Student();
s.setAge(18);
s.setName("xx");
System.out.println(querySql(s));
}
public static String querySql(Object o) {
StringBuffer sb = new StringBuffer();
Class<? extends Object> clazz = o.getClass();
if(clazz.isAnnotationPresent(Table.class)) {
Table t = clazz.getAnnotation(Table.class);
sb.append("select * from " +t.value() +" where 1=1 ");
for (Field field : clazz.getDeclaredFields()) {
if(field.isAnnotationPresent(Column.class)) {
Column c = field.getAnnotation(Column.class);
String fieldName = c.value();
String method = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
try {
Method m = clazz.getDeclaredMethod(method);
Object fieldValue = m.invoke(o);
if(fieldValue == null) continue;
sb.append(" and "+fieldName+" = ");
if(fieldValue instanceof String) {
sb.append("'"+fieldValue+"'");
}else {
sb.append(fieldValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return sb == null ? null : sb.toString();
}
总结 1注解式编程方便且b格高
2 可代替文件配置,可以参考https://www.cnblogs.com/everxs/p/4575131.html(侵权即删)
边栏推荐
猜你喜欢
随机推荐
分库分表ShardingSphere-JDBC笔记整理
Redis中RDB和AOF的区别
Day38 LeetCode
MFC 进程间通信(共享内存)
MySQL存储引擎概念
Delphi7学习记录-demo实例
网络协议1
2.2 user manual] [QNX Hypervisor 10.15 vdev timer8254
Development Tools Lecture 7: Alibaba Cloud Log Query and Analysis
Decryption of BitLocker
oracle tablespace and user creation
Difference between @Resource and @Autowired
Zabbix builds enterprise-level monitoring and alarm platform
Let's talk programming languages together
How IP-Guard prohibits running U disk programs
MFC Interprocess Communication (Shared Memory)
Switch and Router Technology - 32 - Named ACL
Switch and Router Technology-31-Extended ACL
@Resource和@Autowired的区别
面试宝典二:nlp常见知识点