当前位置:网站首页>手写orm框架
手写orm框架
2022-07-24 05:15:00 【x0757】
目录
大致框架
1.建立框架
首先创建一个Maven项目, 在引用第三方依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
</dependencies>2.新增一个类
@Data
//注解
@TableName(value = "tb_dept")
public class Dept {
//注解
@TableId(value = "id")
public Integer id;
//注解
@TableFiled(value = "deptname")
public String name;
public String address;
}
3.添加一个dao包
//继承BaseDao
public class DeptDao extends BaseDao<Dept> {
}4.添加注解
//作用在属性上
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableFiled {
String value();
}
//作用在类上
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
String value();
}
//作用在属性上
@Target(value = ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableId {
String value() default "id";
}5.连接数据库
5.1创建一个db.properties文件
jdbc.driverName=com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/数据库名?serverTimezone=Asia/Shanghai
jdbc.username =root
jdbc.password = 数据库密码5.2创建DBUtils类
public class DBUtils {
private static String driverName;
private static String url;
private static String username;
private static String password;
//建立连接
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("db.properties"));
driverName = properties.getProperty("jdbc.driverName");
url = properties.getProperty("jdbc.url");
username = properties.getProperty("jdbc.username");
password = properties.getProperty("jdbc.password");
}catch (Exception e){
e.printStackTrace();
}
}
public static Connection getConn() throws Exception{
Class.forName(driverName);
Connection connection = DriverManager.getConnection(url,username,password);
return connection;
}
//关闭资源
public static void closeAll(ResultSet rs, PreparedStatement ps,Connection connection){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(ps!=null){
ps.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if(connection!=null){
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
6.创建BaseDao类实现增删改查(CRUD)
package com.xzj.util;
import com.xzj.annotation.TableId;
import com.xzj.annotation.TableFiled;
import com.xzj.annotation.TableName;
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.util.ArrayList;
import java.util.List;
public class BaseDao<T>{
private PreparedStatement ps;
private ResultSet rs;
private Connection connection;
private Class<?> clazz;
public BaseDao(){
//this对应子类对象 获取当前类反射类对象
Class<? extends BaseDao> aClass = this.getClass();
//获取当前反射类的父类---包含父类的泛型
ParameterizedType genericSuperclass = (ParameterizedType) aClass.getGenericSuperclass();
//获取泛型的反射类
Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
clazz= (Class<?>) actualTypeArguments[0];
}
//根据id查询
public Object findId(Object id){
try{
StringBuffer sb= new StringBuffer();
sb.append("select * from ");
TableName tableNameAnnotation = clazz.getAnnotation(TableName.class);
String tableName="";
if(tableNameAnnotation!=null){
tableName=tableNameAnnotation.value();
}else{
tableName= clazz.getSimpleName();
}
sb.append(tableName+" where ");
Field[] declaredFields = clazz.getDeclaredFields();
boolean flag = false;
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
TableId annotation = declaredField.getAnnotation(TableId.class);
if (annotation != null) {
sb.append(annotation.value() + "='" + id + "'");
flag = true;
break;
}
}
if (flag == false) {
throw new RuntimeException("No primary key annotation added");
}
System.out.println(sb);
Connection conn = DBUtils.getConn();
PreparedStatement ps = conn.prepareStatement(sb.toString());
ResultSet rs = ps.executeQuery();
while (rs.next()){
Object o = clazz.newInstance();
Field[] declaredFields1 = clazz.getDeclaredFields();
for (Field field : declaredFields1) {
field.setAccessible(true);
TableFiled annotation = field.getAnnotation(TableFiled.class);
if(annotation!=null){
field.set(o,rs.getObject(annotation.value()));
}else{
field.set(o,rs.getObject(field.getName()));
}
}
return o;
}
}catch (Exception e){
e.printStackTrace();
}finally {
DBUtils.closeAll(rs,ps,connection);
}
return null;
}
//查询所有
public List<T> fandAll(){
List<T> list = new ArrayList<T>();
try {
StringBuffer sb = new StringBuffer();
sb.append("select * from ");
//获取表名
TableName tableNameAnnotation = clazz.getAnnotation(TableName.class);
String tableName = "";
if (tableNameAnnotation != null) {
tableName = tableNameAnnotation.value();
} else {
tableName = clazz.getSimpleName();
}
sb.append(tableName);
Connection conn =DBUtils.getConn();
PreparedStatement ps = conn.prepareStatement(sb.toString());
ResultSet rs = ps.executeQuery();
while (rs.next()){
Object o = clazz.newInstance();
Field[] declaredFields = clazz.getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
TableFiled tableFiled = declaredField.getAnnotation(TableFiled.class);
if(tableFiled!=null){
declaredField.set(o,rs.getObject(tableFiled.value()));
}else {
declaredField.set(o,rs.getObject(declaredField.getName()));
}
}
list.add((T) o);
}
}catch (Exception e){
e.printStackTrace();
}
return list;
}
//删除
public int delete(Object id){
try {
StringBuffer sb = new StringBuffer();
sb.append("delete from ");
// 获取表名
TableName tableNameannotation = clazz.getAnnotation(TableName.class);
String tableName = "";
//获取类上的注解
if (tableNameannotation != null) {
tableName = tableNameannotation.value();
} else {
tableName = clazz.getSimpleName();
}
Field[] declaredFields = clazz.getDeclaredFields();
boolean flag = false;
sb.append(tableName+" where ");
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
TableId annotation = declaredField.getAnnotation(TableId.class);
if (annotation != null) {
sb.append(annotation.value() + "='" + id + "'");
flag = true;
break;
}
}
if (flag == false) {
throw new RuntimeException("No primary key annotation added");
}
System.out.println(sb);
Connection conn = DBUtils.getConn();
PreparedStatement ps = conn.prepareStatement(sb.toString());
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
DBUtils.closeAll(rs,ps,connection);
}
return 0;
}
//根据主键修改
public int update(T t){
try {
StringBuffer sb = new StringBuffer();
sb.append("update ");
//得到T的反射类
Class<?> aClass = t.getClass();
//获取类上的注解
TableName tableNameannotation = aClass.getAnnotation(TableName.class);
String tableName ="";
if (tableNameannotation != null) {
tableName = tableNameannotation.value();
} else {
tableName = aClass.getSimpleName();
}
sb.append(tableName+" set ");
boolean flag=false;
Field[] declaredFields = aClass.getDeclaredFields();
String where = "where";
for (Field field : declaredFields) {
TableId annotation = field.getAnnotation(TableId.class);
if (annotation != null) {
flag=true;
where += " "+annotation.value() + "=" + field.get(t);
}else {
TableFiled tableField = field.getAnnotation(TableFiled.class);
if(tableField!=null){
sb.append(tableField.value()+"='"+field.get(t)+"',");
}else{
sb.append(field.getName()+"='"+field.get(t)+"',");
}
}
}
if(flag==false){
throw new Exception("No primary key annotation added");
}
String str = sb.substring(0, sb.lastIndexOf(","));
String sql = str+where;
System.out.println(sql);
Connection conn = DBUtils.getConn();
PreparedStatement ps = conn.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
DBUtils.closeAll(rs,ps,connection);
}
return 0;
}
//添加
public int insert(T t){
try{
StringBuffer sb = new StringBuffer("insert into ");
Class<?> aClass = t.getClass();
TableName annotation = aClass.getAnnotation(TableName.class);
String tableName ="";
if(annotation!=null){
tableName = annotation.value();
}else {
tableName = aClass.getSimpleName();
}
sb.append(tableName);
System.out.println(sb);
Field[] declaredFields = aClass.getDeclaredFields();
List<String> columns = new ArrayList<>();
List<String> values = new ArrayList<>();
for (Field declaredField:declaredFields){
declaredField.setAccessible(true);
TableFiled tableField = declaredField.getAnnotation(TableFiled.class);
if(tableField!=null){
columns.add(tableField.value());
}else {
columns.add(declaredField.getName());
}
values.add("'"+declaredField.get(t)+"'");
}
sb.append(columns.toString().replace("[","(").replace("]",")"));
sb.append(" values ");
sb.append(values.toString().replace("[","(").replace("]",")"));
System.out.println(sb);
Connection conn = DBUtils.getConn();
PreparedStatement ps = conn.prepareStatement(sb.toString());
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
DBUtils.closeAll(rs,ps,connection);
}
return 0;
}
}
7.测试
public class Test {
public static void main(String[] args) {
DeptDao deptDao = new DeptDao();
//查询所有
System.out.println(deptDao.fandAll());
//根据id查询
System.out.println(deptDao.findId(3));
//删除
deptDao.delete(2);
Dept dept = new Dept();
//修改
dept.setId(12);
dept.setName("王");
dept.setAddress("杭州");
deptDao.update(dept);
//添加
dept.setName("xyang");
dept.setAddress("北京");
deptDao.insert(dept);
}
}
边栏推荐
- How to avoid the most common mistakes when building a knowledge base?
- 1. There is a fractional sequence: 2/1, 3/2, 5/3, 8/5, 13/8,... Program to sum the first 20 items of this sequence.
- Using a* heuristic search to solve maze routing problem
- [database connection] - excerpt from training
- C primer plus learning notes - 6. Arrays and pointers
- 熊市抄底指南
- MGRE and OSPF comprehensive experiment
- 泛型和注解
- FRP intranet penetration service usage
- 13. Write a program, in which a user-defined function is used to judge whether an integer is a prime number. The main function inputs a number and outputs whether it is a prime number.
猜你喜欢

智能指针、左值引用右值引用、lambda表达式

HCIA NAT experiment

Hcip day 3 - mGRE experiment

Zhaoyi innovation gd25wdxxk6 SPI nor flash product series comes out

OSS文件上传

Chapter5 foundation of deep learning

Chapter III encog workbench

Learning pyramid context encoder network for high quality image painting paper notes

线程
![[Huang ah code] Introduction to MySQL - 3. I use select *, and the boss directly rushed me home by train, but I still bought a station ticket](/img/60/23fc79cf0e399265b4bd75159ad4d1.png)
[Huang ah code] Introduction to MySQL - 3. I use select *, and the boss directly rushed me home by train, but I still bought a station ticket
随机推荐
Technical team: improve team effectiveness, starting from never doing three things
Jiang Xingqun, senior vice president of BOE: aiot technology enables enterprise IOT transformation
It is related to the amount of work and ho. Embedded, only one 70 should be connected
Some thoughts about blogger coach soserious
支撑复杂的模型群监控、实时告警等t4 文件系统。e
Image to image translation with conditional advantageous networks paper notes
NLP learning roadmap (mind map) is very comprehensive and clear!
JMeter record the BeanShell written into excel instance caused by an automatic data generation
PSO and mfpso
Ren Xudong, chief open source liaison officer of Huawei: deeply cultivate basic software open source and jointly build the root technology of the digital world
Chapter 1 regression, classification & clustering
。 Single type digital sensing is an application 0 Up address is at the factory
[postgraduate entrance examination vocabulary training camp] day 10 - capital, expand, force, adapt, depand
Scikit learn -- steps of machine learning application development
Pointer learning diary (IV) use structure and pointer (linked list)
How to set up an internal wiki for your enterprise?
Industry relevance of stock price trend
Markov random field: definition, properties, maximum a posteriori probability problem, energy minimization problem
postgresql:在Docker中运行PostgreSQL + pgAdmin 4
[database connection] - excerpt from training