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);
}
}