当前位置:网站首页>Tear the ORM framework by hand (generic + annotation + reflection)
Tear the ORM framework by hand (generic + annotation + reflection)
2022-07-29 05:54:00 【Don't want bald Xiao Yang】
ORM:(Object relative Mapping) Object relational mapping framework . Help you automatically compare the records in the database with java Entity classes are mapped together .
annitation package : Custom annotation Used on entity classes
TableName: When the table name is inconsistent with the entity class name, use
TableField: When the column name and attribute name are inconsistent, use
TablePrimaryKey: Use on primary key , Used to distinguish from other attributes
package com.qy151.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @unthor : YSH
* @date : 20:39 2022/7/14
*/
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface TabelName {
String value();
}
util package : Public class
DBUtils: Get the connection object and close the connection resource
package com.qy151.util;
import java.sql.*;
/**
* @unthor : YSH
* @date : 20:06 2022/7/14
*/
/* Get the connection object and close the connection resource */
public class DBUtils {
private static String driverName="com.mysql.cj.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/myda2?serverTimezone=Asia/Shanghai";
private static String user=" Your username ";
private static String password="";
public static Connection getCon() throws Exception {
Class.forName(driverName);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
public static void closeAll(ResultSet res, PreparedStatement ps,Connection connection){
try {
if(res!=null){
res.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();
}
}
}
BaseDao class : Parent class
How to get generics in class names T:
//this The corresponding subclass object Get the reflection class object of the current class
Class<? extends BaseDao> aClass = this.getClass();
// Get the parent class of the current reflection class ---- Contains generics of the parent class
ParameterizedType genericSuperclass = (ParameterizedType) aClass.getGenericSuperclass();
// Get the generic reflection class
Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
clazz = (Class<?>) actualTypeArguments[0];
BaseDao It implements a simple CRUD operation
package com.qy151.util;
import com.qy151.annotation.TabelFiled;
import com.qy151.annotation.TabelName;
import com.qy151.annotation.TableId;
import com.qy151.entity.Student;
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;
/**
* @unthor : YSH
* @date : 20:27 2022/7/14
*/
/*T: Represents an entity class object */
public class BaseDao<T> {
private Class<?> clazz;
public BaseDao(){
//this The corresponding subclass object Get the current 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];
/*System.out.println(clazz);*/
}
/* Query single and query all public methods */
public List<T> find(String sql) throws Exception{
List<T> list = new ArrayList<T>();
Connection connection = DBUtils.getCon();
PreparedStatement ps = connection.prepareStatement(sql.toString());
ResultSet rs = ps.executeQuery();
while (rs.next()){
Object o = clazz.newInstance();
Field[] declaredFields = clazz.getDeclaredFields();
for (Field declaredField:declaredFields
) {
declaredField.setAccessible(true);
TabelFiled tabelFiled = declaredField.getAnnotation(TabelFiled.class);
if (tabelFiled==null){
TableId tableId = declaredField.getAnnotation(TableId.class);
if(tableId!=null){
declaredField.set(o,rs.getObject(tableId.value()));
}else {
declaredField.set(o,rs.getObject(declaredField.getName()));
}
}else {
declaredField.set(o, rs.getObject(tabelFiled.value()));
}
}
list.add((T) o);
}
return list;
}
/* according to id Inquire about */
public Student findOneById(Object id) throws Exception {
Student student = null;
StringBuffer sql = new StringBuffer("select * from ");
// Get table name
TabelName tabelNameAnnotation = clazz.getAnnotation(TabelName.class);
String tabelname = "";
/* Determine whether the annotation exists */
if (tabelNameAnnotation != null) {
tabelname = tabelNameAnnotation.value();
} else {
tabelname = clazz.getSimpleName();
}
// Append table name
sql.append(tabelname+" where ");
System.out.println(sql);
// Get all attribute objects in the reflection class object
Field[] declaredFields = clazz.getDeclaredFields();
boolean flag = false;
for (Field declaredFiled:declaredFields
) {
TableId tableId = declaredFiled.getAnnotation(TableId.class);
if (tableId!=null){
sql.append(tableId.value()+"='"+id+"'");
flag=true;
break;
}
}
if (flag==false){
throw new RuntimeException(" No primary key annotation is added ");
}
System.out.println(sql);
List<T> list = find(sql.toString());
if (list!=null&&list.size()==1){
return (Student) list.get(0);
}
return null;
}
// Query all
public List<T> findAll() throws Exception{
StringBuffer sql = new StringBuffer("select * from ");
// Get table name
TabelName tabelNameAnnotation = clazz.getAnnotation(TabelName.class);
String tabelname = "";
/* Determine whether the annotation exists */
if (tabelNameAnnotation != null) {
tabelname = tabelNameAnnotation.value();
} else {
tabelname = clazz.getSimpleName();
}
// Append table name
sql.append(tabelname);
System.out.println(sql);
return find(sql.toString());
}
// Delete
public int delete(Object id){
try {
StringBuffer sql = new StringBuffer("delete from ");
// Get table name
TabelName tabelNameAnnotation = clazz.getAnnotation(TabelName.class);
String tabelname = "";
/* Determine whether the annotation exists */
if (tabelNameAnnotation != null) {
tabelname = tabelNameAnnotation.value();
} else {
tabelname = clazz.getSimpleName();
}
// Append table name
sql.append(tabelname+" where ");
System.out.println(sql);
// Get all attribute objects in the reflection class object
Field[] declaredFields = clazz.getDeclaredFields();
boolean flag = false;
for (Field declaredFiled:declaredFields
) {
TableId tableId = declaredFiled.getAnnotation(TableId.class);
if (tableId!=null){
sql.append(tableId.value()+"='"+id+"'");
flag=true;
break;
}
}
if (flag==false){
throw new RuntimeException(" No primary key annotation is added ");
}
System.out.println(sql);
// Get the connection object
Connection con = DBUtils.getCon();
// obtain sql Statement object
PreparedStatement ps = con.prepareStatement(sql.toString());
// perform sql sentence
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
// increase
public int insert(T t) {
try {
//Sql:insert into Table name values(?,?,?......)
StringBuffer stringBuffer = new StringBuffer("insert into ");
// Get table name
Class<?> aClass = t.getClass();
TabelName tabelNameAnnotation = aClass.getAnnotation(TabelName.class);
String tabelname = "";
/* Determine whether the annotation exists */
if (tabelNameAnnotation != null) {
tabelname = tabelNameAnnotation.value();
} else {
tabelname = aClass.getSimpleName();
}
// Append table name
stringBuffer.append(tabelname);
// Get all attribute objects in the reflection class object
Field[] declaredFields = aClass.getDeclaredFields();
// Create two sets
List<String> columns = new ArrayList<String>();// Store all column names
List<String> values = new ArrayList<String>();// Store all column values
for (Field field : declaredFields
) {
field.setAccessible(true);
// Get all column names
TabelFiled tabelFiled = field.getAnnotation(TabelFiled.class);
if (tabelFiled != null) {
columns.add(tabelFiled.value());
} else {
columns.add(field.getName());
}
// Get all column values
values.add("'" + field.get(t) + "'");
}
stringBuffer.append(columns.toString().replace("[", "(").replace("]", ")"));
stringBuffer.append(" values ");
stringBuffer.append(values.toString().replace("[", "(").replace("]", ")"));
System.out.println(stringBuffer);
// Get the connection object
Connection con = DBUtils.getCon();
// obtain sql Statement object
PreparedStatement ps = con.prepareStatement(stringBuffer.toString());
// perform sql sentence
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
}
return 0;
}
/* modify 01*/
public int update(T t){
try {
//update Table name set Name = ? where id=?
StringBuffer stringBuffer = new StringBuffer("update ");
/* Get the reflection object */
Class<?> aClass = t.getClass();
TabelName tabelNameAnnotation = aClass.getAnnotation(TabelName.class);
String tablename = "";
if (tabelNameAnnotation != null) {
tablename = tabelNameAnnotation.value();
} else {
tablename = aClass.getSimpleName();
}
stringBuffer.append(tablename + " set ");
Field[] declaredFields = aClass.getDeclaredFields();
List<String> columns = new ArrayList<String>();
List<String> values = new ArrayList<String>();
for (Field field : declaredFields
) {
field.setAccessible(true);
TabelFiled tabelFiled = field.getAnnotation(TabelFiled.class);
if (tabelFiled != null) {
columns.add(tabelFiled.value());
} else {
columns.add(field.getName());
}
values.add("'" + field.get(t) + "'");
}
String remove = columns.remove(0);
String remove01 = values.remove(0);
System.out.println(remove + " " + remove01);
Object[] columnsArray = columns.toArray();
Object[] valuesArray = values.toArray();
for (int i = 0; i < columnsArray.length; i++) {
for (int j = 0; j < valuesArray.length; j++) {
if (i == j) {
stringBuffer.append(columnsArray[i] + "=" + valuesArray[j] + ",");
}
}
}
stringBuffer = new StringBuffer(stringBuffer.substring(0, stringBuffer.length() - 1) + " where " + remove + "=" + remove01);
System.out.println(stringBuffer);
Connection con = DBUtils.getCon();
PreparedStatement ps= con.prepareStatement(stringBuffer.toString());
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
}
return 0;
}
/* modify 02*/
public int updateById(T t){
try {
// modify --update Table name set Name = value , Name = value ... where Primary key = value ;
StringBuffer sql = new StringBuffer("update ");
/* Get table name */
Class<?> aClass = t.getClass();
TabelName tabelNameAnnotation = aClass.getAnnotation(TabelName.class);
String tableName = "";
if (tabelNameAnnotation != null) {
tableName = tabelNameAnnotation.value();
} else {
tableName = aClass.getSimpleName();
}
sql.append(tableName + " set ");
System.out.println(sql);
/* Get column values */
String columnValue = "";
String where = " where ";
Field[] declaredFields = aClass.getDeclaredFields();
boolean flag = false;
for (Field field : declaredFields
) {
field.setAccessible(true);
TabelFiled tabelFiledAnnotation = field.getAnnotation(TabelFiled.class);
if (tabelFiledAnnotation != null) {
columnValue += tabelFiledAnnotation.value() + "='" + field.get(t) + "', ";
} else {
TableId tableIdAnnotation = field.getAnnotation(TableId.class);
if (tableIdAnnotation!=null){
flag = true;
where +=tableIdAnnotation.value()+"='"+field.get(t)+"'";
}else {
columnValue+= field.getName()+ "='" + field.get(t) + "',";
}
}
}
if (flag==false){
throw new RuntimeException(" No primary key annotation is added ");
}
// Remove the last question mark
columnValue=columnValue.substring(0,columnValue.lastIndexOf(","));
sql.append(columnValue).append(where);
System.out.println(sql );
Connection con = DBUtils.getCon();
PreparedStatement ps= con.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
entity package : Entity class Student
package com.qy151.entity;
import com.qy151.annotation.TabelFiled;
import com.qy151.annotation.TabelName;
import com.qy151.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @unthor : YSH
* @date : 20:34 2022/7/14
*/
@Data
/*@NoArgsConstructor
@AllArgsConstructor*/
@TabelName(value = "t_student")
public class Student {
/*private Integer id;*/
@TabelFiled(value = "name")
private String studentname;
private String address;
// Indicates that the column is a primary key column
@TableId(value = "id")
private Integer sid;
}
dao package : Operation class
package com.qy151.dao;
import com.qy151.entity.Student;
import com.qy151.util.BaseDao;
/**
* @unthor : YSH
* @date : 20:49 2022/7/14
*/
public class StudentDao extends BaseDao<Student> {
}
Test: Test class
import com.qy151.dao.StudentDao;
import com.qy151.dao.UserDao;
import com.qy151.entity.Student;
import com.qy151.entity.User;
import org.junit.Test;
/**
* @unthor : YSH
* @date : 20:49 2022/7/14
*/
public class StudentTest {
StudentDao studentDao = new StudentDao();
@Test
public void insert(){
Student student = new Student();
student.setSid(20);
student.setStudentname(" Saturday ");
student.setAddress(" Beijing ");
studentDao.insert(student);
}
@Test
public void update() {
Student student = new Student();
student.setSid(20);
student.setStudentname(" Zhang San ");
student.setAddress(" Venus ");
studentDao.update(student);
}
@Test
public void updateById() {
Student student = new Student();
student.setSid(20);
student.setStudentname(" Zhang San ");
student.setAddress(" mercury ");
studentDao.updateById(student);
}
@Test
public void delete(){
Student student = new Student();
studentDao.delete(20);
}
@Test
public void findAll() throws Exception {
Student student = new Student();
System.out.println(studentDao.findAll());
}
@Test
public void findOneById() throws Exception {
Student student = new Student();
System.out.println(studentDao.findOneById(10));
}
}

IDEA Package the project as jar package
Include dependencies used in the project
packaged jar In bag Lombok The package cannot be used , Report errors
resolvent :
Turn on idea Annotation Processing

边栏推荐
- Extreme deflation and perpetual motion machine model will promote the outbreak of platofarm
- 加密资产熊市之下,PlatoFarm的策略玩法依旧能获得稳定收益
- How can Plato obtain premium income through elephant swap in a bear market?
- “山东大学移动互联网开发技术教学网站建设”项目实训日志二
- "Shandong University mobile Internet development technology teaching website construction" project training log V
- 量化开发必掌握的30个知识点【什么是Level-2数据】
- day02 作业之文件权限
- Simple optimization of interesting apps for deep learning (suitable for novices)
- 【数据库】数据库课程设计一一疫苗接种数据库
- 与多家机构战略合作,背后彰显PlatoFarm元宇宙龙头的实力
猜你喜欢

微信内置浏览器禁止缓存的问题

Fantom (FTM) prices will soar by 20% in the next few days

一文读懂Move2Earn项目——MOVE

MySQL decompressed version windows installation

山寨币SHIB 在 ETH 鲸鱼的投资组合中拥有 5.486 亿美元的股份——交易者应提防……

剑指核心-TaoCloud全闪SDS助力构建高性能云服务

重庆大道云行作为软件产业代表受邀参加渝中区重点项目签约仪式

DAO赛道异军突起,M-DAO的优势在哪里?

Huawei 2020 school recruitment written test programming questions read this article is enough (Part 2)

“山东大学移动互联网开发技术教学网站建设”项目实训日志六
随机推荐
山寨币SHIB 在 ETH 鲸鱼的投资组合中拥有 5.486 亿美元的股份——交易者应提防……
30 knowledge points that must be mastered in quantitative development [what is level-2 data]
Countdown of the uniapp component (such as the countdown to reading the agreement and the countdown to completing learning)
Fantom (FTM) 在 FOMC会议之前飙升 45%
XDFS&中国日报社在线协同编辑平台典型案例
iSCSI vs iSER vs NVMe-TCP vs NVMe-RDMA
MOVE PROTOCOL全球健康宣言,将健康运动进行到底
Performance comparison | FASS iSCSI vs nvme/tcp
Idea using JDBC to connect mysql database personal detailed tutorial
全闪分布式,如何深度性能POC?
The Platonic metauniverse advocated by musk has long been verified by platofarm
Extreme deflation and perpetual motion machine model will promote the outbreak of platofarm
July 28 ens/usd Value Forecast: ENS attracts huge profits
Windows下cmd窗口连接mysql并操作表
学习、研究编程之道
超简单集成HMS ML Kit 人脸检测实现可爱贴纸
Simple optimization of interesting apps for deep learning (suitable for novices)
识变!应变!求变!
裸金属云FASS高性能弹性块存储解决方案
打印出1-100之间的所有质数
https://blog.csdn.net/weixin_61634823/article/details/124827963