当前位置:网站首页>Handwritten ORM framework
Handwritten ORM framework
2022-07-24 05:21:00 【x0757】
Catalog
5.1 Create a db.properties file
6. establish BaseDao Class to add, delete, modify and query (CRUD)
General framework
1. Build the framework
First create a Maven project , In reference to third-party dependencies
<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. Add a new class
@Data
// annotation
@TableName(value = "tb_dept")
public class Dept {
// annotation
@TableId(value = "id")
public Integer id;
// annotation
@TableFiled(value = "deptname")
public String name;
public String address;
}
3. Add one dao package
// Inherit BaseDao
public class DeptDao extends BaseDao<Dept> {
}4. adding annotations
// On properties
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableFiled {
String value();
}
// Action on a class
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
String value();
}
// On properties
@Target(value = ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableId {
String value() default "id";
}5. Connect to database
5.1 Create a db.properties file
jdbc.driverName=com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ Database name ?serverTimezone=Asia/Shanghai
jdbc.username =root
jdbc.password = Database password 5.2 establish DBUtils class
public class DBUtils {
private static String driverName;
private static String url;
private static String username;
private static String password;
// Establishing a connection
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;
}
// close resource
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. establish BaseDao Class to add, delete, modify and query (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 Corresponding subclass object Get the current class reflection class object
Class<? extends BaseDao> aClass = this.getClass();
// Get the parent class of the current reflection class --- Generics containing parent classes
ParameterizedType genericSuperclass = (ParameterizedType) aClass.getGenericSuperclass();
// Get the generic reflection class
Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
clazz= (Class<?>) actualTypeArguments[0];
}
// according to id Inquire about
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;
}
// Query all
public List<T> fandAll(){
List<T> list = new ArrayList<T>();
try {
StringBuffer sb = new StringBuffer();
sb.append("select * from ");
// Get table name
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;
}
// Delete
public int delete(Object id){
try {
StringBuffer sb = new StringBuffer();
sb.append("delete from ");
// Get table name
TableName tableNameannotation = clazz.getAnnotation(TableName.class);
String tableName = "";
// Gets the annotations on the class
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;
}
// Modify... According to the primary key
public int update(T t){
try {
StringBuffer sb = new StringBuffer();
sb.append("update ");
// obtain T Reflection class of
Class<?> aClass = t.getClass();
// Gets the annotations on the class
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;
}
// add to
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. test
public class Test {
public static void main(String[] args) {
DeptDao deptDao = new DeptDao();
// Query all
System.out.println(deptDao.fandAll());
// according to id Inquire about
System.out.println(deptDao.findId(3));
// Delete
deptDao.delete(2);
Dept dept = new Dept();
// modify
dept.setId(12);
dept.setName(" king ");
dept.setAddress(" Hangzhou ");
deptDao.update(dept);
// add to
dept.setName("xyang");
dept.setAddress(" Beijing ");
deptDao.insert(dept);
}
}
边栏推荐
- PXE efficient batch network installation
- Industry relevance of stock price trend
- Embedded system transplantation [2] - Construction of cross development environment
- XML schema
- The difference between compiled language and interpreted language
- 使用swagger2markup生成API文档
- 利用a*启发式搜索解决迷宫寻路问题
- 好的程序员与不好的程序员
- Optional consistency
- Data annotation learning summary
猜你喜欢
![Codeforce:d2. remove the substring (hard version) [greedy string + subsequence]](/img/c1/320e0349e2edda0eb420ed018aa831.png)
Codeforce:d2. remove the substring (hard version) [greedy string + subsequence]
![Knowledge record of College Physics C in advance in summer [update]](/img/c4/76b669c3229a365a5e2567f7fb824e.png)
Knowledge record of College Physics C in advance in summer [update]

手写orm框架

PPPoE gateway simulation environment setup

PPPoE网关模拟环境搭建

SSM整合

C primer plus learning notes - 6. Arrays and pointers

jdbc封装一个父类减少代码重复

FTP file transfer protocol

1、基于增量式生成遮挡与对抗抑制的行人再识别
随机推荐
JMeter upload and download files
NumPy 统计相关函数示例教程
反射的介绍
Chapter5 foundation of deep learning
Problems encountered in configuring Yum source
The world's first large aerospace model came out. Wenxin's second supplement "Fuchun Mountain Residence map" is Baidu Pratt Whitney AI's perseverance
MySQL深入了解
支撑复杂的模型群监控、实时告警等t4 文件系统。e
Industry relevance of stock price trend
SSH service
修改jupyter保存路径
Create and delete databases using databases
Data annotation learning summary
浅谈不可转让的声誉积分NFT SBTs面临的困境
Wang Qing, director of cloud infrastructure software research and development of Intel (China): Intel's technology development and prospects in cloud native
How to avoid the most common mistakes when building a knowledge base?
postgresql:在Docker中运行PostgreSQL + pgAdmin 4
scikit-learn笔记
Echo speaker pairing and operation method
frp内网穿透服务使用