利用jdbc,泛型,注解,反射设计sql单表,简单的增、删、改框架

1.完成DbUtils工具类

1.1pom文件 添加一个mysql驱动依赖

<!--    mysql 驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.31</version>
    </dependency>

1.2resourcess包下创建一个jdbc.properties文件 

用于添加mysql配置信息

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test1?serverTimezone=Asia/Shanghai
username=root
password=123456

 1.3创建DbUtils工具类

public class DbUtils {
    private  static  String driver;
    private  static  String url;
    private  static  String username;
    private  static  String password;

    //静态代码块  真能读取一次
    static {
        //1.使用property类 读取文件
        Properties properties = new Properties();

        //2.加载属性文件
        InputStream systemResourceAsStream = ClassLoader.getSystemResourceAsStream("jdbc.properties");

        try {
            //读取对应文件属性
            properties.load(systemResourceAsStream);
            driver=properties.getProperty("driver");
            url=properties.getProperty("url");
            username=properties.getProperty("username");
            password=properties.getProperty("password");
        } catch (IOException e) {
            throw new RuntimeException("jdbc.properties没找到");
        }

    }

    public static Connection connection() throws  Exception{
        //加载驱动类
        Class.forName(driver);
        //获取连接对象
        Connection roo = DriverManager.getConnection(url,username,password);
        return roo;
    }
    //关闭资源
    public static  void closeAll(ResultSet rs, PreparedStatement ps,Connection conn){
        try {
            if(rs !=null){
                rs.close();
            }
            if(ps !=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

2.创建注解

分别作用在 类上 获取类名 、属性上获取属性名、id上获取主键  

@Target(value = ElementType.TYPE)//在类型上
@Retention(RetentionPolicy.RUNTIME)//启动时生效
public @interface Kind {
    String value();
}

@Target(value= ElementType.FIELD)//在属性上
@Retention(value= RetentionPolicy.RUNTIME)//运行时生效
public @interface Nature {
    String value();
}

@Target(value = ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mid {
    String value() ;
}

3.实体类

@Data
@Kind(value = "emp")
public class Empe {
    private int eid;
    private String ename;
    private String gender;

    private double salary;

    @Nature(value="dept_name")
     private String deptName;
}


@Data
@Kind("emp3")
public class Emp3 {
    @Mid("id")
    private int id;
    private String username;

    @Nature("password")
    private String password;

    public Emp3(){

    }

    public Emp3(int id) {
        this.id = id;
    }
}

4.通用的的BaseDao类

public class BaseDao<T> {
    /*删除*/

    public int delete(T t) throws Exception{
        //DELETE FROM 表名 WHERE 条件;";
        StringBuffer delete= new StringBuffer("delete from ");
        //用反射 获取类对象
        Class<?> aClass = t.getClass();

        //获取属性名     只获取类名
        String simpleName = aClass.getSimpleName();
        //获取类名 上的注解
        Kind annotation = aClass.getAnnotation(Kind.class);
        if(annotation != null){
            simpleName= annotation.value();
        }
        delete.append(simpleName);


        String where=" where ";
        //获取属性名
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field:declaredFields){
            field.setAccessible(true);
            //得到属性名
            String name = field.getName();

            //获取属性上的 id 注解

            Mid annotation1 = field.getAnnotation(Mid.class);
            if(annotation1 !=null){
                //得到id
                String value = annotation1.value();
                Object o = field.get(t);
                where =where + value +"="+o;
                continue;
            }
        }
        delete.append(where);

        //连接数据库
        Connection connection = DbUtils.connection();
        PreparedStatement statement = connection.prepareStatement(delete.toString());
        int i = statement.executeUpdate();

        //获取
        return i;

    }


    /*添加*/
    public int insert(T t) throws Exception {
        //sql语句: insert into 表名(列名,列名) values(值1,值2....)
        StringBuffer insert = new StringBuffer("insert into ");
        //通过反射获取类对象
        Class<?> aClass = t.getClass();
        // 获取类名
        String simpleName = aClass.getSimpleName();


        //获取 类上的注解值
        Kind annotation = aClass.getAnnotation(Kind.class);
        if(annotation !=null){
            simpleName=annotation.value();
        }
        insert.append(simpleName);

        ArrayList<String> crosswise = new ArrayList<>();//获取列名
        ArrayList<Object> endlong = new ArrayList<>();//获取列 值

        //获取属性对象
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field:declaredFields){
            field.setAccessible(true);
            //获取属性名
            String name = field.getName();

            //获取  属性上的 Field注解
            Nature annotation1 = field.getAnnotation(Nature.class);
            if(annotation1 !=null){
                name= annotation1.value();
            }
            crosswise.add(name);
            Object o = field.get(t);

            endlong.add(" '"+o+"' ");

        }
        //sql 需要有()这里把[]转换成()
        String s=crosswise.toString().replace("[","(").replace("]",")");
        String s1=endlong.toString().replace("[","(").replace("]",")");
        insert.append(s);
        insert.append(" values ");
        insert.append(s1);
        System.out.println(insert);


        Connection connection = DbUtils.connection();
        PreparedStatement statement = connection.prepareStatement(insert.toString());
        int i = statement.executeUpdate();
        return i;

    }

    /*修改*/
    public int update(T t) throws Exception{
        //sql语句: update 表名 set 列名=值.....where 主键=值
        StringBuffer update = new StringBuffer("update ");
        //用反射获取类对象
        Class<?> aClass = t.getClass();

        //获取类名
        String simpleName = aClass.getSimpleName();

        //获取类上 注解值
        Kind annotation = aClass.getAnnotation(Kind.class);
        if(annotation !=null){
            simpleName=annotation.value();
        }
        update.append(simpleName);
        update.append(" set ");

        //获取属性名
        String where=" where ";
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field:declaredFields){
             field.setAccessible(true);
                //本类属性名
                String name = field.getName();
            Mid annotation1 = field.getAnnotation(Mid.class);
            if (annotation1 !=null){
                String value = annotation1.value();
                Object o = field.get(t);//要输入的属性值
                where= where + value+"="+o;
                continue;
            }

            //获取 注解属性值
            Nature annotation2 = field.getAnnotation(Nature.class);
            if(annotation2 !=null){
                name= annotation2.value();
            }
            Object o = field.get(t);//要输入的属性值


            update.append(name);
            update.append("=");
            update.append("'"+o+"' ");
            update.append(",");

        }
        String up=update.substring(0,update.lastIndexOf(","));

        up=up+where;
        System.out.println(up);

        Connection connection = DbUtils.connection();
        PreparedStatement statement = connection.prepareStatement(up);

        int i = statement.executeUpdate();

        return i;
    }
}

5.测试

5.1创建两个dao类 

继承 BasDao   用到哪个表 泛型就写 对应的实体类

public class Emp3Dao extends BaseDao<Emp3>{
}


public class EmpeDao extends BaseDao<Empe> {
}

5.2测试类

      创建对应的对象  对应属性输入值 ,再用继承BsaeDao的子类 调用对应方法就可以了

public class Test1 {
    public static void main(String[] args) throws Exception {
        /*添加*/
        EmpeDao empDao = new EmpeDao();
        Empe empe = new Empe();
        empe.setEid(12);

        empDao.insert(empe);

    }
}


public class Test1 {
    public static void main(String[] args) throws Exception {
        /*添加*/
        EmpeDao empDao = new EmpeDao();
        Empe empe = new Empe();
        empe.setEid(12);

        empDao.insert(empe);

    }
}


public class Test3 {
    public static void main(String[] args) throws Exception {
        /*删除*/
        Emp3Dao emp3Dao = new Emp3Dao();
        Emp3 emp3 = new Emp3(3);

        emp3Dao.delete(emp3);

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 实体类中属性写法可以使用 Java 的反射机制来实现。具体实现步骤如下: 1. 定义一个通用的 DAO 接口,包含的方法: ```java public interface BaseDao<T> { boolean insert(T entity); boolean delete(T entity); boolean update(T entity); T findById(Serializable id); List<T> findAll(); } ``` 2. 实现这个接口,并使用反射机制实现的方法: ```java public class BaseDaoImpl<T> implements BaseDao<T> { private Class<T> entityClass; private String tableName; public BaseDaoImpl(Class<T> entityClass) { this.entityClass = entityClass; this.tableName = entityClass.getSimpleName(); } @Override public boolean insert(T entity) { // 使用反射机制获取实体类的属性列 Field[] fields = entityClass.getDeclaredFields(); StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO ").append(tableName).append("("); // 构建 SQL 语句 for (Field field : fields) { sb.append(field.getName()).append(","); } sb.deleteCharAt(sb.length() - 1); sb.append(") VALUES ("); for (int i = 0; i < fields.length; i++) { sb.append("?,"); } sb.deleteCharAt(sb.length() - 1); sb.append(")"); // 执行 SQL 语句 try (Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(sb.toString())) { for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); ps.setObject(i + 1, fields[i].get(entity)); } return ps.executeUpdate() > 0; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public boolean delete(T entity) { // 使用反射机制获取实体类的主键属性 Field idField = getIdField(); StringBuilder sb = new StringBuilder(); sb.append("DELETE FROM ").append(tableName).append(" WHERE ") .append(idField.getName()).append(" = ?"); // 执行 SQL 语句 try (Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(sb.toString())) { idField.setAccessible(true); ps.setObject(1, idField.get(entity)); return ps.executeUpdate() > 0; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public boolean update(T entity) { // 使用反射机制获取实体类的属性列和主键属性 Field[] fields = entityClass.getDeclaredFields(); Field idField = getIdField(); StringBuilder sb = new StringBuilder(); sb.append("UPDATE ").append(tableName).append(" SET "); // 构建 SQL 语句 for (Field field : fields) { if (!field.equals(idField)) { sb.append(field.getName()).append(" = ?,"); } } sb.deleteCharAt(sb.length() - 1); sb.append(" WHERE ").append(idField.getName()).append(" = ?"); // 执行 SQL 语句 try (Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(sb.toString())) { int paramIndex = 1; for (Field field : fields) { if (!field.equals(idField)) { field.setAccessible(true); ps.setObject(paramIndex++, field.get(entity)); } } idField.setAccessible(true); ps.setObject(paramIndex, idField.get(entity)); return ps.executeUpdate() > 0; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public T findById(Serializable id) { // 使用反射机制获取实体类的主键属性 Field idField = getIdField(); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM ").append(tableName) .append(" WHERE ").append(idField.getName()).append(" = ?"); // 执行 SQL 语句 try (Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(sb.toString())) { ps.setObject(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { // 创建实体类对象 T entity = entityClass.newInstance(); // 给实体类对象的属性赋值 for (Field field : entityClass.getDeclaredFields()) { field.setAccessible(true); field.set(entity, rs.getObject(field.getName())); } return entity; } else { return null; } } } catch (Exception e) { e.printStackTrace(); return null; } } @Override public List<T> findAll() { StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM ").append(tableName); // 执行 SQL 语句 try (Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(sb.toString())) { try (ResultSet rs = ps.executeQuery()) { List<T> list = new ArrayList<>(); while (rs.next()) { // 创建实体类对象 T entity = entityClass.newInstance(); // 给实体类对象的属性赋值 for (Field field : entityClass.getDeclaredFields()) { field.setAccessible(true); field.set(entity, rs.getObject(field.getName())); } list.add(entity); } return list; } } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取实体类的主键属性 */ private Field getIdField() { for (Field field : entityClass.getDeclaredFields()) { if (field.isAnnotationPresent(Id.class)) { return field; } } throw new RuntimeException("No @Id field found in " + entityClass.getName()); } /** * 获取数据库连接 */ private Connection getConnection() throws SQLException { return DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); } } ``` 3. 在实体类中使用注解来标识主键属性: ```java public class User { @Id private Long id; private String name; private Integer age; // 省略 getter 和 setter 方法 } ``` 这样,我们就可以通过一个通用的 DAO 接口来实现实体类属性的,而不需要针对每个实体类都实现一遍 CRUD 操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值