目录
自定义注解
package com.jxy.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 TableField {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableId {
String value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
String name();
}
实体
package com.jxy.entity;
import com.jxy.annotation.TableField;
import com.jxy.annotation.TableId;
import com.jxy.annotation.TableName;
@TableName(name = "tab_stu")
public class Student {
@TableId(value = "id")
private Integer id;
private String sno;
private String sname;
private String sex;
private String phone1;
private String privince;
public Student() {
}
public Student(Integer id,String sno, String sname, String sex, String phone1, String privince) {
this.id = id;
this.sno = sno;
this.sname = sname;
this.sex = sex;
this.phone1 = phone1;
this.privince = privince;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", sno='" + sno + ''' +
", sname='" + sname + ''' +
", sex='" + sex + ''' +
", phone1='" + phone1 + ''' +
", privince='" + privince + ''' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
public String getPrivince() {
return privince;
}
public void setPrivince(String privince) {
this.privince = privince;
}
}
DButil
package com.jxy.utils;
import java.sql.*;
public class DBUtil {
public static Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3307/lesdb?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true";
String driverName = "com.mysql.cj.jdbc.Driver";
String username = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url,username,password);
return connection;
}
public static void closeAll(ResultSet rs, PreparedStatement ps,Connection con){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
BaseDao(主写增删改查操作)
package com.jxy.utils; import com.jxy.annotation.TableField; import com.jxy.annotation.TableId; import com.jxy.annotation.TableName; import com.jxy.dao.StudentDao; import com.jxy.entity.Student; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BaseDao{ ResultSet rs = null; Connection connection = null; PreparedStatement ps = null; //BaseDao泛型T的反射类 private Class cla; public BaseDao() { //此时反射类就是BaseDao的子类 Class extends BaseDao> studentClass = this.getClass(); //获取子类继承父类的反射对象 并得到父类的泛型 Type type = studentClass.getGenericSuperclass(); ParameterizedType pt = (ParameterizedType) type; Type[] actualType = pt.getActualTypeArguments(); //得到父类BaseDao的泛型 cla = (Class) actualType[0]; } public List selectAll(){ StringBuffer sql = new StringBuffer("select * from "); TableName tableName = (TableName) cla.getAnnotation(TableName.class); if(tableName == null){ throw new RuntimeException("未使用表名注解"); } String name = tableName.name(); sql.append(name); System.out.println(sql); return selectCondition(sql.toString()); } public List selectCondition(String sql){ List list = new ArrayList<>(); try { connection = DBUtil.getConnection(); ps = connection.prepareStatement(sql); rs = ps.executeQuery(); //每循环一次找到一条记录 //记录装到实体 实体交给集合 while (rs.next()){ T t = (T) cla.newInstance(); Field[] declaredFields = cla.getDeclaredFields(); for(Field field:declaredFields){ field.setAccessible(true); TableId tableId = field.getAnnotation(TableId.class); if(tableId!=null){ field.set(t,rs.getObject(tableId.value())); }else{ TableField tableField = field.getAnnotation(TableField.class); if(tableField!=null){ //列名与属性不一致 //set()将指定对象变量上此属性对象表示的字段设置为指定的新值 //通过set(Object obj,value)重新设置新的属性值 //getObject()获取此 ResultSet 对象的当前列中指定列的值 field.set(t,rs.getObject(tableField.value())); }else{ //列名与属性一致 field.set(t,rs.getObject(field.getName())); } } } list.add(t); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); }finally { DBUtil.closeAll(rs,ps,connection); } return list; } public T selectById(Object id){ StringBuffer sql = new StringBuffer("select * from "); TableName tableName = (TableName) cla.getAnnotation(TableName.class); if(tableName == null){ throw new RuntimeException("未使用表名注解"); } String name = tableName.name(); sql.append(name+" where "); Field[] declaredFields = cla.getDeclaredFields(); for(Field field:declaredFields){ TableId tableId = field.getAnnotation(TableId.class); if(tableId!=null){ sql.append(tableId.value()+"="+id); break; } } System.out.println(sql); List list = selectCondition(sql.toString()); if(list!=null&&list.size()>0){ return list.get(0); }else{ return null; } } public int delete(Object id){ StringBuffer sql = new StringBuffer("delete from "); TableName tableName = (TableName) cla.getAnnotation(TableName.class); if(tableName == null){ throw new RuntimeException("未使用表名注解"); } String name = tableName.name(); sql.append(name+" where "); Field[] declaredFields = cla.getDeclaredFields(); for(Field field:declaredFields){ TableId tableId = field.getAnnotation(TableId.class); if(tableId!=null){ sql.append(tableId.value()+"="+id); System.out.println(sql); } } try { connection = DBUtil.getConnection(); ps = connection.prepareStatement(sql.toString()); int i = ps.executeUpdate(); return i; } catch (SQLException throwables) { throwables.printStackTrace(); }finally { DBUtil.closeAll(rs,ps,connection); } return 0; } public int update(T t){ StringBuffer sq = new StringBuffer("update "); Class> tClass = t.getClass(); TableName tableName = tClass.getAnnotation(TableName.class); if(tableName==null){ throw new RuntimeException("未使用TableName注解标记表名"); } String name = tableName.name(); sq.append(name+" set "); Field[] fields = tClass.getDeclaredFields(); String where = " where "; for(Field f:fields){ f.setAccessible(true); //主键列 TableId id = f.getAnnotation(TableId.class); if(id!=null){ try { where += id.value() + "=" +f.get(t); } catch (IllegalAccessException e) { e.printStackTrace(); } }else{ //不是主键列 TableField field = f.getAnnotation(TableField.class); if(field!=null){ try { //针对列名属性名不一样的情况 sq.append(field.value() + "='" + f.get(t) + "',"); } catch (IllegalAccessException e) { e.printStackTrace(); } }else{ try { //针对列名属性名一样的情况 sq.append(f.getName() + "='" + f.get(t) +"',"); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } String str = sq.substring(0, sq.lastIndexOf(",")); String sql = str + where; try{ System.out.println(sql); connection = DBUtil.getConnection(); ps = connection.prepareStatement(sql); int i = ps.executeUpdate(); return i; } catch (SQLException throwables) { throwables.printStackTrace(); }finally { DBUtil.closeAll(rs,ps,connection); } return 0; } public int insert(T t){ StringBuffer sql = new StringBuffer("insert into "); Class> tClass = t.getClass(); TableName tableName = tClass.getAnnotation(TableName.class); if(tableName==null){ throw new RuntimeException("没有使用TableName注解标记表名"); } String name = tableName.name(); sql.append(name+" values "); //集合封装值 ArrayList
查询所有
查询单个
插入
修改
删除



