Java annotations and implementation of database operations through custom Java annotations

By annotations in Java programs, you can make programming more concise code more clear. Therefore Java framework code, embedded in a large number of notes.

Speaking notes, first of all talk about the concept notes: Java provides one element of the original program associated with the ways and means any information and any metadata.

First, annotation classification


1, in accordance with the operating mechanism into the source code comment to the compiler and runtime comment

(1) Source notes: Notes only exist in the source code, compiled into .class file does not exist

(2) compile notes: notes are present in the source and .class files, such as the three notes of JDK

(3) Note Runtime: further functions during the operating phase, and even affect the operation of the logic annotation, such as annotation in Spring @Autowired

2, divided by source JDK annotations, third-party comments, annotations, and metadata custom annotation


(1) JDK comes with notes

        @Override: When subclass covers methods of the parent class, the keyword will appear in front of the method;

        @Deprecated: it represents a way out of date, but can still be used, that is, plus @Suppvisewarning ( "deprecation") before the method call to add the annotation;

        @Suppvisewarning: @Depricated appreciated binding;

(2) third-party comments

        As in Spring @ Autowired, @ Service @Repository and the like;

        As the Mybatis @ InsertProvider, @ UpdateProvider @Options and the like;

(3) meta-annotation: annotation notes known as a meta-annotation

(4) custom annotation --- This section explains


 Second, the custom annotation

1, custom annotation syntax requirements:

@Target({ElementType.METHOD,                //方法声明
               ElementType.TYPE,            //类、接口
               ElementType.FIELD,           //字段声明

               ElementType.CONSTRUCTOR,     //构造方法声明

               ElementType.LOCAL_VARIABLE,  //局部变量
               ElementType.PACKAGE,         //包声明
               ElementType.PARAMETER})      //参数声明
@Retention(RetentionPolicy.RUNTIME)    //生命周期,有SOURCE(源码)、CLASS(编译)、RUNTIME(运行时)   
@Inherited                          //允许子类继承
@Documented                         //生成JavaDoc的时候包含的信息
public @interface Description{      //@interface定义注解
    
    String desc();                  //方法以无参数、无异常的方式声明
    
    String author();
    
    int age() default 20;           //使用default为其指定默认值
}

(1) bearing in mind the type of membership is restricted legal types: basic types, String, Class, Annotation, Enumeration.

(2) If a comment is only one member, member name must be named value (), can be ignored when using the members name and copy number (=);

(3) If the class is not a member of annotation, the annotation is called identifier;

2, the use of annotations


@<注解名>(<成员名1>=<成员值1>,<成员名2>=<成员值2>,……)
@Description(desc="Hello", author="Jack", age=18)
public String Demo(){
    return "test";
}

Third, custom annotation database operations

Database table as shown:

The first step : establishing a database table corresponding to the entity classes and custom annotations are inserted in the classes and methods

Notes on the class

Notes on the way

Step Two : Write test function

public class Main {
    public static void main(String[] args) {
        WsUser wsUser = new WsUser();
        wsUser.setRemark("sdasdasd");//按个性签名查询学生
        String sql1 = query(wsUser);
        System.out.println("sql1 = " + sql1);
        exeQuery(sql1);

        WsUser wsUser1 = new WsUser();
        //wsUser1.setUserId(3);
        wsUser1.setUserName("小小文");
        String sql = query(wsUser1);
        System.out.println("sql = " + sql);
        exeQuery(sql);

        WsUser wsUser2 = new WsUser();
        wsUser2.setUserName("小小文,上司,小智,lisi");
        String sql2 = query(wsUser2);
        System.out.println("sql2 = " + sql2);
        exeQuery(sql2);
    }
    private static String query(Object stu) {
        StringBuilder sb = new StringBuilder();
        //解析注解:
        //1、获取到class
        Class clazz = stu.getClass();

        //2、获取到table的名字
        boolean exists = clazz.isAnnotationPresent(Table.class);
        if(!exists)
            return null;
        Table table = (Table) clazz.getAnnotation(Table.class);
        String tableName = table.value();
        sb.append("select * from ").append(tableName).append(" where 1=1");

        //3、遍历所有字段
        Field[] fArray = clazz.getDeclaredFields();
        for(Field field : fArray) {
            //4、处理每个字段对应的sql
            //4.1拿到字段名
            boolean fieldExist = field.isAnnotationPresent(Column.class);
            if (!fieldExist){
                continue;
            }
            Column column = field.getAnnotation(Column.class);
            String columnName = column.value();

            //4.2拿到字段名
            String filename = field.getName();
            String  getMethodName = "get" + filename.substring(0,1).toUpperCase() + filename.substring(1);
            //取到所设置的值
            Object filevalue = null;
            try {
                Method getMethod = clazz.getMethod(getMethodName);
                filevalue = getMethod.invoke(stu, null);//stu.getUserId
            } catch (Exception e) {
                e.printStackTrace();
            }
            //4.3拼装sql
            if(filevalue == null || ((filevalue instanceof Integer) && ((Integer)filevalue==0)))
                continue;
            sb.append(" and ").append(columnName);
            if(filevalue instanceof String) {
                //判断是否String有, 有就分割
                if(((String)filevalue).contains(",")){
                    String[] values = ((String) filevalue).split(",");
                    sb.append(" in(");
                    for(String value : values){
                        sb.append("'").append(value).append("'").append(",");
                    }
                    sb.deleteCharAt(sb.length()-1);
                    sb.append(")");
                }else {
                    sb.append(" = ").append("'").append(filevalue).append("'");
                }
            }else if(filevalue instanceof Integer)
                sb.append(" = ").append(filevalue);
        }

        return sb.toString();
    }
    private static void exeQuery(String sql){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/chatroom?useUnicode=true&characterEncoding=UTF-8","root", "123");
            PreparedStatement statement = conn.prepareStatement(sql);
            ResultSet rs = statement.executeQuery();
            System.out.println("user_id" + "\t" + "user_name" + "\t" + "user_account" + "\t" + "user_password" + "\t" + "remark");
            while(rs.next()){
                System.out.println(rs.getString("user_id") + "\t\t" + rs.getString("user_name") + "\t\t" + rs.getString("user_account")+ "\t\t" + rs.getString("user_password")+ "\t\t" + rs.getString("remark"));
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Run the test program the following results:

 

Released seven original articles · won praise 0 · Views 119

Guess you like

Origin blog.csdn.net/winwinwin99/article/details/105156626