Annotation 简单实现 JAVABEAN到数据库的映射(THINK IN JAVA 4 TH)

本文介绍了一种使用Java注解实现ORM框架的方法,通过自定义注解将实体类映射到数据库表,并通过反射机制生成创建表的SQL语句。具体包括自定义注解SQLString、SQLInt等用于描述字段类型,以及Constraints注解用于设置字段约束。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * 数据库表注释
 */
package net.jian.annotation;

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 DBTable {
    public String name() default "";
}

 

package net.jian.annotation;

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 SQLString {
    public int value() default 0;
    public String name() default "";
    public Constraints constraints() default @Constraints;
}

 

package net.jian.annotation;

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 SQLInt {
    public String name() default "";
    public Constraints constraints() default @Constraints;
}

 

/*
 * 字段到Bean的域的映射约束
 */
package net.jian.annotation;

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 Constraints {
    public boolean primaryKey() default false;
    public boolean allowNull() default true;
    public boolean unique() default false;
}

package net.jian.pojo;

import net.jian.annotation.Constraints;
import net.jian.annotation.DBTable;
import net.jian.annotation.SQLInt;
import net.jian.annotation.SQLString;

@DBTable()
public class User {

    @SQLString(value = 32, name = "u_id",
            constraints = @Constraints(
                    primaryKey = true, unique = true, allowNull = false))
    private String id;
   
    @SQLString(value = 10, name = "u_name")
    private String name;
   
    @SQLString(value = 30, name = "u_password")
    private String password;
   
    @SQLInt(name = "u_age")
    private int age;
   
    public void setId(String id) {
        this.id = id;
    }
   
    public String getId() {
        return this.id;
    }
   
    public void setName(String name) {
        this.name = name;
    }
   
    public String getName() {
        return this.name;
    }
   
    public void setPassword(String password) {
        this.password = password;
    }
   
    public String getPassword() {
        return this.password;
    }
   
    public void setAge(int age) {
        this.age = age;
    }
   
    public int getAge() {
        return this.age;
    }
}

package net.jian.test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.jian.annotation.Constraints;
import net.jian.annotation.DBTable;
import net.jian.annotation.SQLInt;
import net.jian.annotation.SQLString;
import net.jian.pojo.User;

public class TestFrame {

    public static void main(String[] args) {
       
        Class userClass = User.class;
        DBTable dbTable = (DBTable) userClass.getAnnotation(DBTable.class);
        String dbTableName = userClass.getSimpleName();
        if(dbTable == null) {
            return;
        }
        if(dbTable.name().length() > 0) {
            dbTableName = dbTable.name().toUpperCase();
        }
        StringBuffer createSql = new StringBuffer("CREATE TABLE " + dbTableName + "(");
        Field[] fields = userClass.getDeclaredFields();
        List<String> colDef = new ArrayList<String>();
        for(Field field : fields) {
            Annotation[] annotions = field.getAnnotations();
            if(annotions.length < 1) {
                continue;
            }
            for(Annotation anno : annotions) {
                String colName = field.getName().toUpperCase();
                if(anno instanceof SQLString) {
                    SQLString sqlStr = (SQLString)anno;
                    if(sqlStr.name().length() > 0) {
                        colName = sqlStr.name().toUpperCase();
                    }
                    int len = sqlStr.value();
                    colDef.add(colName + " " + "varchar(" + len + ")" + getConstraints(sqlStr.constraints()));
                } else if(anno instanceof SQLInt) {
                    SQLInt sqlInt = (SQLInt)anno;
                    if(sqlInt.name().length() > 0) {
                        colName = sqlInt.name().toUpperCase();
                    }
                    colDef.add(colName + " " + " int " + getConstraints(sqlInt.constraints()));
                }
            }
        }
        Iterator<String> it = colDef.iterator();
        while(it.hasNext()) {
            createSql.append("/n " + it.next() + ",");
        }
        String cmd = createSql.substring(0, createSql.length() - 1);
        cmd += ");";
        System.out.println(cmd);
    }
   
    private static String getConstraints(Constraints constraints) {
        String cons = "";
        if(!constraints.allowNull()) {
            cons += " not null ";
        }
        if(constraints.primaryKey()) {
            cons += " primary key ";
        }
        if(constraints.unique()) {
            cons += " unique ";
        }
        return cons;
    }
}

输出结果:

CREATE TABLE User(
 U_ID varchar(32) not null  primary key  unique ,
 U_NAME varchar(10),
 U_PASSWORD varchar(30),
 U_AGE  int );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值