1.创建一个maven的java工程
2.引入依赖jar
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>
3.创建数据源的属性文件
#配置数据源信息
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username=root
password=数据库密码
4.创建DbUtil工具类
package com.ykq.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DbUtil {
//数据源对象
private static DataSource dataSource;
//静态代码块中---只会加载一次
static {
try {
//创建一个属性对象
Properties properties = new Properties();
//加载属性文件
InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(inputStream);
//获取连接池对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取链接对象
public static Connection getConnection() throws Exception{
Connection conn=dataSource.getConnection();
return conn;
}
//释放资源
public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs) {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
5.1通用的添加
public int insert(T t) throws Exception{
//1.创建一个sql字符串
StringBuffer sql=new StringBuffer("insert into ");
//2. 获取实体类的反射类.
Class<?> aClass = t.getClass();
//3.获取表名
String tableName=aClass.getSimpleName();//实体类的名称
TableName annotation = aClass.getAnnotation(TableName.class);
if(annotation!=null){
tableName = annotation.value();
}
sql.append(tableName);
//4.获取所有的列名--对于属性名
List<String> columnNames = new ArrayList<>();
List<Object> values=new ArrayList<>();
//5. 获取所有的属性对象
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field:declaredFields){
//获取属性名
String name = field.getName();
//获取属性上的注解
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
TableField fieldAnnotation = field.getAnnotation(TableField.class);
if(tableIdAnnotation!=null){
continue;
}
if(fieldAnnotation!=null){
name = fieldAnnotation.value();
}
field.setAccessible(true);
//对象属性的值
Object value = field.get(t);
values.add("'"+value+"'");
columnNames.add(name);
}
String replace = columnNames.toString().replace("[", "(").replace("]", ")");
String replace1 = values.toString().replace("[", "(").replace("]", ")");
sql.append(replace+" values "+replace1);
//执行sql语句
Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
}
5.2通用的修改
public int update(T t) throws Exception{
StringBuffer sql=new StringBuffer("update ");
//获取表名
Class<?> aClass = t.getClass();
String tableName=aClass.getSimpleName();
TableName annotation = aClass.getAnnotation(TableName.class);
if (annotation!=null){
tableName = annotation.value();
}
sql.append(tableName+" set ");
String where=" where ";
//2.获取所有列对象
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field:declaredFields){
//属性名
String name = field.getName();
TableField fieldAnnotation = field.getAnnotation(TableField.class);
TableId tableId = field.getAnnotation(TableId.class);
field.setAccessible(true);
Object value = field.get(t);
//如果为主键注解
if(tableId!=null){
String tableIdName=tableId.value();
where+=tableIdName+"='"+value+"'";
continue;
}
if(fieldAnnotation!=null){
name = fieldAnnotation.value();
}
sql.append(name+"='"+value+"',");
}
sql.deleteCharAt(sql.length()-1).append(where);
//执行sql语句
Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
}
5.3通用的删除操作
delete from 表名 where 主键 = 值;
private Class<T> clazz;
public BaseDao(){
//this表示子类Dao对象
Class<? extends BaseDao> aClass = this.getClass();
//获取当前子类的父类的反射类
ParameterizedType genericSuperclass = (ParameterizedType) aClass.getGenericSuperclass();
//获取该反射类中的泛型类型
Type actualTypeArgument = genericSuperclass.getActualTypeArguments()[0];
clazz= (Class) actualTypeArgument;
}
//delete from 表名 where 主键列名=id
public int deleteByid(Object id) throws Exception{
StringBuffer sql=new StringBuffer("delete from ");
String tableName=clazz.getSimpleName();//实体类的名称
TableName annotation = clazz.getAnnotation(TableName.class);
if(annotation!=null){
tableName = annotation.value();
}
sql.append(tableName+" where ");
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field:declaredFields){
TableId tableId = field.getAnnotation(TableId.class);
if(tableId!=null){
sql.append(tableId.value()+"="+id);
break;
}
}
//执行sql语句
Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
}
5.4 ORM完成查询功能
public T selectById(Object id) throws Exception{
StringBuffer sql=new StringBuffer("select * from ");
//获取表名
String tableName=clazz.getSimpleName();
TableName annotation = clazz.getAnnotation(TableName.class);
if(annotation!=null){
tableName=annotation.value();
}
sql.append(tableName+" where ");
//获取主键列名
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field:declaredFields){
TableId tableId = field.getAnnotation(TableId.class);
if(tableId!=null){
sql.append(tableId.value()+"="+id);
break;
}
}
//执行sql语句
Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql.toString());
ResultSet rs = ps.executeQuery();
//封装数据到实体类
while(rs.next()){
T t=clazz.newInstance();
for (Field field:declaredFields){
field.setAccessible(true);
TableField tableField = field.getAnnotation(TableField.class);
TableId tableId = field.getAnnotation(TableId.class);
//获取属性名
String name = field.getName();
if(tableId!=null){
name=tableId.value();
}
if(tableField!=null){
name=tableField.value();
}
//获取数据库中指定列的值
Object v = rs.getObject(name);
//为指定对象的属性赋值
field.set(t,v);
}
return t;
}
return null;
}
public List<T> selectAll()throws Exception{
List<T> list=new ArrayList<>();
StringBuffer sql=new StringBuffer("select * from ");
//获取表名
String tableName=clazz.getSimpleName();
TableName annotation = clazz.getAnnotation(TableName.class);
if(annotation!=null){
tableName=annotation.value();
}
sql.append(tableName);
//执行sql语句
Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql.toString());
ResultSet rs = ps.executeQuery();
Field[] declaredFields = clazz.getDeclaredFields();
//封装数据
while (rs.next()){
T t=clazz.newInstance();
//为实体类的属性赋值
for (Field field:declaredFields){
field.setAccessible(true);
TableField tableField = field.getAnnotation(TableField.class);
TableId tableId = field.getAnnotation(TableId.class);
//获取属性名
String name = field.getName();
if(tableId!=null){
name=tableId.value();
}
if(tableField!=null){
name=tableField.value();
}
//获取数据库中指定列的值
Object v = rs.getObject(name);
//为指定对象的属性赋值
field.set(t,v);
}
list.add(t);
}
return list;
}