自定義註解簡單實戰

經過自定義註解映射數據庫,利用jdbcTemple查詢時反射獲取數據實現簡單的查詢功能

  • 首先經過idea自動生成springboot項目,插件依賴我都不選
  • pom.xml,commons-beanutils用來測試時map和javabean互轉
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.zhujie</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.3</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
複製代碼

yml配置java

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test
    username: root
    password: 123456
複製代碼
  • 首先自定義兩個註解類X_Table和X_Column來映射表和字段
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface X_Column {
    String x_value();
}
@Target({ElementType.TYPE})//設置做用域於接口或類
@Retention(RetentionPolicy.RUNTIME)//生命週期爲運行時
public @interface X_Table {
    String x_value();
}
複製代碼
  • 自定義實體類city,使用自定義註解映射實體類,這樣在執行本身封裝的方法時能夠經過反射獲取信息
@X_Table(x_value = "t_city")
public class City {
    //定義字段屬性
     @X_Column(x_value = "id")
     private Integer id;
     @X_Column(x_value = "username")
     private String username;
     @X_Column(x_value = "nickName")
     private String nickName;
     @X_Column(x_value = "age")
     private String age;
     @X_Column(x_value = "city")
     private String city;
     ...getter,setter和toString方法,記得補上
     }
複製代碼
  • 自定義查詢方法
package com.zhujie.untils;

import anotationDemo.X_Column;
import anotationDemo.X_Table;
import com.sun.corba.se.spi.logging.CORBALogDomains;
import org.apache.logging.log4j.util.Strings;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;

/**
 * @author xulicong on 2019/4/18.
 */
public class queryUtil {
    public static String x_query(Object o) throws ClassNotFoundException, SQLException {
        //定義準備查詢的sql語句
        StringBuilder sql = new StringBuilder();
        Class<?> oClass = o.getClass();
        //判斷是否存在這個註解
        if(!oClass.isAnnotationPresent(X_Table.class)){
            return null;
        }
        //獲取表名
        X_Table x_table = oClass.getAnnotation(X_Table.class);
        String tableName = x_table.x_value();

        sql.append("select * from ").append(tableName).append(" where 1=1");

        //遍歷對象的全部屬性看是否有註解
        Field[] fields = oClass.getDeclaredFields();
        for(Field f : fields){
            boolean Fexists = f.isAnnotationPresent(X_Column.class);
            if(!Fexists) {
                continue;
            }
            //獲取註解上的字段值
            X_Column xColumn = f.getAnnotation(X_Column.class);
            String x_Column = xColumn.x_value();
            //獲取字段屬性名
            String columuName = f.getName();
            //拼接字段屬性名的get方法名
            String getMethodName = "get" + columuName.substring(0, 1).toUpperCase() + columuName.substring(1);
            Method method = null;
            Object columuValue = null;
            try {
                method = oClass.getMethod(getMethodName);
                //獲取傳進來的對象的對應屬性值
                columuValue = method.invoke(o);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (columuValue instanceof Integer){
                sql.append(" and " +columuName+ "=" + columuValue);
            }else if (columuValue instanceof String){
                //若是有,則拼接in
                if( ((String) columuValue).contains(",") ){
                    String[] split = ((String) columuValue).split(",");
                    sql.append(" and " +columuName+ " in (");
                    for(String s:split){
                        sql.append("'"+s+"',");
                    }
                    sql.deleteCharAt(sql.length()-1);
                    sql.append(")");
                }else {
                    sql.append(" and " +columuName+ "= '" +columuValue+ "'");
                }
            }
        }
        return sql.toString();
    }
}

複製代碼
  • 測試
package com.zhujie;

import com.alibaba.fastjson.JSON;
import com.zhujie.pojo.City;
import com.zhujie.untils.queryUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Autowired
     private JdbcTemplate jdbcTemplate;

    @Test
    public void contextLoads() throws Exception{
        City city = new City();
        city.setCity("潮州,廣州,南京");
        String s = queryUtil.x_query(city);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(s);
        ArrayList<City> cityList = new ArrayList<>();
        for (Map m:list){
            City c = new City();
            BeanUtils.populate(c,m);
            cityList.add(c);
        }
        for (City c:cityList){
            System.out.println(c.toString());
        }
    }
}
複製代碼
  • mysql數據庫和成功結果

相關文章
相關標籤/搜索