定义DAO类,通过@Id,@Column,@Table注解来实现CURD方法

 1.定义注解

//定义注解
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();
}
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();
}

//修饰的属性是主键
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {
    String value();
    boolean autoincre() default false;
}

 2.定义Student类

//Student类
import java.util.Date;

public class Student {
    private String sno;
    private String sname;
    private String tel;
    private Double height;
    private int amt;
    private Date birthday;

    public String getSno() {
        return sno;
    }
    public void setSno(String sno) {
        this.sno = sno;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public Double getHeight() {
        return height;
    }
    public void setHeight(Double height) {
        this.height = height;
    }
    public int getAmt() {
        return amt;
    }
    public void setAmt(int amt) {
        this.amt = amt;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

3.定义Dao 

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BaseDao {
    Connection conn;
    PreparedStatement stmt;
    ResultSet rs;
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }
    }
    public Connection getConnection() {
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/pjt0313?characterEncoding=utf8", "root","root");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 1.获得obj的类对象
     * 2.读取obj类对象的类上修饰的@Table注解对象
     * 如果没有@Table注解对象,读取类名作为表名
     * 如果有@Table注解对象,读取@Table注解中的value属性值 作为表名
     * 3.获得所有的属性,遍历属性获得其名字 ,拼SQL语句
     * 如果属性没有@Column注解,读取属性名作为列名
     * 如果有@Column注解 或 @ Id 注解 读取注解的value属性值 作为列名
     * 如果是@ Id注解 ,这列是主键,读取autoincre属性如果为true,SQL的values中拼default
     * 4.设置预编译参数值
     * 5.执行SQL语句,返回结果。
     *
     * @param obj 如果是Student对象,就向表名是Student的表进行插入操作
     * @return
     */
    public int insert(Object obj) {
        int result = 0;
        Id idAnnotation = null;
        Column columnAnnotation = null;
        //1.获得obj的类对象
        Class cls = obj.getClass();
        //2.获得其类名
        String tableName = cls.getSimpleName();
        //读取@Table注解
        Table table = (Table)cls.getAnnotation(Table.class);
        if(table!=null) {
            tableName = table.value();
        }
        //3.获得所有的属性
        Field[] fields = cls.getDeclaredFields();
        //4.拼预编译的SQL语句
        String columnSQL = "";
        String valueSQL = "";
        List list = new ArrayList();
        conn = this.getConnection();
        try {
            for(Field field:fields) {
                field.setAccessible(true);
                /*如果属性没有@Column注解,读取属性名作为列名
                如果有@Column注解 或 @ Id 注解 读取注解的value属性值 作为列名
                如果是@ Id注解 ,这列是主键,读取autoincre属性如果为true,SQL的values中拼default		 
    		*/
                idAnnotation = (Id)field.getAnnotation(Id.class);
                columnAnnotation = (Column)field.getAnnotation(Column.class);
                if(idAnnotation!=null) {
                    if(idAnnotation.autoincre()) {
                        valueSQL+= "default,";
                    }else {
                        valueSQL+= "?,";
                        list.add(field.get(obj));
                    }
                    columnSQL+=idAnnotation.value()+",";
                }else if(columnAnnotation!=null) {
                    columnSQL+=columnAnnotation.value()+",";
                    valueSQL+= "?,";
                    list.add(field.get(obj));
                }else {
                    columnSQL+=field.getName()+",";
                    valueSQL+= "?,";
                    list.add(field.get(obj));
                }
            }
            columnSQL = columnSQL.substring(0, columnSQL.length()-1);
            valueSQL = valueSQL.substring(0, valueSQL.length()-1);
            String sql = "insert into "+tableName+"("+columnSQL+") values ("+valueSQL+")";
            //System.out.println(sql);
            stmt = conn.prepareStatement(sql);
            //5.设置预编译参数值
            for(int i = 0;i<list.size();i++) {
                stmt.setObject(i+1, list.get(i));
            }
            //6.执行SQL语句
            result = stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public int update(Object obj) {
        int result = 0;
        Id idAnnotation = null;
        Column columnAnnotation = null;
        String whereSQL = "";
        //1.获得obj的类对象
        Class cls = obj.getClass();
        //2.获得其类名
        String tableName = cls.getSimpleName();
        //读取@Table注解
        Table table = (Table)cls.getAnnotation(Table.class);
        if(table!=null) {
            tableName = table.value();
        }
        //3.获得所有的属性
        Field[] fields = cls.getDeclaredFields();
        StringBuilder sql = new StringBuilder("update "+tableName +" set ");
        List list = new ArrayList();
        Object pkValue = null;
        try {
            for(Field field:fields) {
                field.setAccessible(true);
                idAnnotation = (Id)field.getAnnotation(Id.class);
                columnAnnotation = (Column)field.getAnnotation(Column.class);
                /* * 3.获得所有的属性,遍历属性获得其名字 ,拼SQL语句
                 * 如果属性没有@Column注解,读取属性名作为列名
                 * 如果有@Column注解 或 @ Id 注解 读取注解的value属性值 作为列名
                 * 如果是@ Id注解 ,这列是主键,拼where 的条件 和 值(where 列名 = ?)*/
                if(idAnnotation!=null) {
                    //拼where 条件的SQL
                    whereSQL = " where "+idAnnotation.value()+"=?";
                    pkValue = field.get(obj);
                }else if(columnAnnotation!=null) {
                    //拼set中的 字段=?
                    sql.append(columnAnnotation.value()+"=?,");
                    list.add(field.get(obj));
                }else {
                    //拼set中的 属性名=?
                    sql.append(field.getName()+"=?,");
                    list.add(field.get(obj));
                }
            }
            String strSQL = sql.substring(0,sql.length()-1);
            strSQL += whereSQL;
            conn = this.getConnection();
            stmt = conn.prepareStatement(strSQL);
            int i = 0;
            for(i = 0;i<list.size();i++) {
                stmt.setObject(i+1,list.get(i));
            }
            stmt.setObject(i+1, pkValue);
            result = stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 1.获得obj的类对象
     * 2.读取obj类对象的类上修饰的@Table注解对象
     * 如果没有@Table注解对象,读取类名作为表名
     * 如果有@Table注解对象,读取@Table注解中的value属性值 作为表名
     * 3.获得所有的属性,遍历属性获得其名字 ,拼select与from之间的 SQL语句
     * 如果属性没有@Column 或 @ Id 注解,读取属性名作为列名
     * 如果有@Column注解 或 @ Id 注解 读取注解的value属性值 作为列名
     * 如果是@ Id注解 ,这列是主键,拼where 的条件 和 值(where 列名 = ?)
     * 并读取主键属性的值
     * @param cls : 查询返回对象的类对象
     * @param pkValue : 主键值
     * @return
     */
    public Object selectByPrimaryKey(Class cls,Object pkValue) {
        Id idAnnotation = null;
        Column columnAnnotation = null;
        String whereSQL = "";
        //2.获得其类名
        String tableName = cls.getSimpleName();
        //读取@Table注解
        Table table = (Table)cls.getAnnotation(Table.class);
        if(table!=null) {
            tableName = table.value();
        }
        Field[] fields = cls.getDeclaredFields();
        StringBuilder columnSQL = new StringBuilder();
        try {
            for(Field field:fields) {
                field.setAccessible(true);
                idAnnotation = (Id)field.getAnnotation(Id.class);
                columnAnnotation = (Column)field.getAnnotation(Column.class);
                /* * 3.获得所有的属性,遍历属性获得其名字 ,拼select与from之间的 SQL语句
                 * 如果属性没有@Column 或 @ Id 注解,读取属性名作为列名
                 * 如果有@Column注解 或 @ Id 注解 读取注解的value属性值 作为列名
                 * 如果是@ Id注解 ,这列是主键,拼where 的条件 和 值(where 列名 = ?)
                 * */
                if(idAnnotation!=null) {
                    // 拼where
                    whereSQL = " where "+idAnnotation.value()+"=?";
                    // 读取注解属性名作为列名,拼SQL
                    columnSQL.append(idAnnotation.value()).append(",");
                }else if(columnAnnotation!=null) {
                    // 读取注解属性名作为列名,拼SQL
                    columnSQL.append(columnAnnotation.value()).append(",");
                }else {
                    // 读取类属性名作为列名,拼SQL
                    columnSQL.append(field.getName()).append(",");
                }
            }
            String sql = "select " + columnSQL.substring(0,columnSQL.length()-1)+" from "+tableName+whereSQL;
            conn = this.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setObject(1, pkValue);
            rs = stmt.executeQuery();
            if(rs.next()) {
                Object returnObj = cls.newInstance();
                for(Field field:fields) {
                    field.setAccessible(true);
                    idAnnotation = (Id)field.getAnnotation(Id.class);
                    columnAnnotation = (Column)field.getAnnotation(Column.class);
                    if(idAnnotation!=null) {
                        field.set(returnObj, rs.getObject(idAnnotation.value()));
                    }else if(columnAnnotation!=null) {
                        field.set(returnObj, rs.getObject(columnAnnotation.value()));
                    }else {
                        field.set(returnObj, rs.getObject(field.getName()));
                    }
                }
                return returnObj;
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

   public static void main(String[] args) {
        BaseDao dao = new BaseDao();
        Student student = new Student();
        /*
        student.setSno("20220211");
        student.setSname("小明");
        student.setTel("15106586224");
        student.setHeight(1.75);
        student.setAmt(2000);
        student.setBirthday(new Date());
        dao.insert(student);

         */

       student.setSno("20220211");
       student.setSname("小亮");
       student.setTel("18800118811");
       student.setHeight(1.77);
       student.setAmt(2300);
       student.setBirthday(new Date());
       dao.update(student);

   }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot可以通过使用JPA实现EAV模型的CURD操作。以下是一些示例代码: 1. 定义EAV模型中的实体、属性和值: ```java @Entity @Table(name = "entity") public class Entity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // 实体型 private String type; // 实体名称 private String name; // ... } @Entity @Table(name = "attribute") public class Attribute { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // 属性名称 private String name; // ... } @Entity @Table(name = "value") public class Value { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // 属性值 private String value; // 属性型 private String type; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "entity_id") private Entity entity; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "attribute_id") private Attribute attribute; // ... } ``` 2. 定义JPA Repository: ```java public interface EntityRepository extends JpaRepository<Entity, Long> { } public interface AttributeRepository extends JpaRepository<Attribute, Long> { } public interface ValueRepository extends JpaRepository<Value, Long> { List<Value> findByEntityAndAttribute(Entity entity, Attribute attribute); } ``` 3. 实现CURD操作: ```java @Service public class EavService { @Autowired private EntityRepository entityRepository; @Autowired private AttributeRepository attributeRepository; @Autowired private ValueRepository valueRepository; public Entity createEntity(String type, String name) { Entity entity = new Entity(); entity.setType(type); entity.setName(name); return entityRepository.save(entity); } public Attribute createAttribute(String name) { Attribute attribute = new Attribute(); attribute.setName(name); return attributeRepository.save(attribute); } public Value createValue(Entity entity, Attribute attribute, String value, String type) { Value val = new Value(); val.setEntity(entity); val.setAttribute(attribute); val.setValue(value); val.setType(type); return valueRepository.save(val); } public List<Value> getValues(Entity entity, Attribute attribute) { return valueRepository.findByEntityAndAttribute(entity, attribute); } // ... } ``` 这样,我们就可以使用EAV模型来实现CURD操作了。注意,EAV模型的查询效率比较低,因此尽量避免大规模的数据查询。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aigo-2021

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值