当前位置:网站首页>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

边栏推荐
- win10+opencv3.2+vs2015配置
- Common prompt pop-up box of uniapp
- From starfish OS' continued deflationary consumption of SFO, the value of SFO in the long run
- Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
- Training log III of "Shandong University mobile Internet development technology teaching website construction" project
- July 28 ens/usd Value Forecast: ENS attracts huge profits
- File文件上传的使用(2)--上传到阿里云Oss文件服务器
- Research and implementation of flash loan DAPP
- 熊市下PLATO如何通过Elephant Swap,获得溢价收益?
- Xsan is highly available - xdfs and San are integrated with new vitality
猜你喜欢

Strategic cooperation with many institutions shows the strength of the leading company of platofarm yuancosmos

xSAN高可用—XDFS与SAN融合焕发新生命力

Idea using JDBC to connect mysql database personal detailed tutorial

Flink connector Oracle CDC 实时同步数据到MySQL(Oracle19c)

ssm整合

一文读懂Move2Earn项目——MOVE

如何在加密市场熊市中生存?

The Platonic metauniverse advocated by musk has long been verified by platofarm

Some opportunities for young people in rural brand building

Training log 6 of the project "construction of Shandong University mobile Internet development technology teaching website"
随机推荐
File permissions of day02 operation
我的理想工作,码农的绝对自由支配才是最重要的——未来创业的追求
【数据库】数据库课程设计一一疫苗接种数据库
Elastic box flex
Move protocol global health declaration, carry out the health campaign to the end
数组的基础使用--遍历循环数组求出数组最大值,最小值以及最大值下标,最小值下标
打印出1-100之间的所有质数
ssm整合
Fantom (FTM) 价格将在未来几天飙升 20%
How to make interesting apps for deep learning with zero code (suitable for novices)
量化开发必掌握的30个知识点【什么是Level-2数据】
性能对比|FASS iSCSI vs NVMe/TCP
"Shandong University mobile Internet development technology teaching website construction" project training log V
新手入门:手把手从PHP环境到ThinkPHP6框架下载
Thinkphp6 output QR code image format to solve the conflict with debug
钉钉告警脚本
Win10+opencv3.2+vs2015 configuration
Crypto巨头们ALL IN元宇宙,PlatoFarm或能突围
极致通缩和永动机模型,将推动 PlatoFarm 爆发
改哭了,终于解决了Cannot read properties of undefined (reading ‘parseComponent‘)
https://blog.csdn.net/weixin_61634823/article/details/124827963