当前位置:网站首页>Addition, deletion, modification and query of handwritten ORM (object relationship mapping)
Addition, deletion, modification and query of handwritten ORM (object relationship mapping)
2022-07-02 22:51:00 【Fall in love with*】
Catalog

Custom annotation
package com.jxy.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author Jin XueYang
* @Date 2022/6/23 10:29
* @Description
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableField {
String value();
}
/**
* @Author Jin XueYang
* @Date 2022/6/23 9:29
* @Description
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableId {
String value();
}
/**
* @Author Jin XueYang
* @Date 2022/6/22 19:11
* @Description
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
String name();
}
Entity
package com.jxy.entity;
import com.jxy.annotation.TableField;
import com.jxy.annotation.TableId;
import com.jxy.annotation.TableName;
/**
* @Author Jin XueYang
* @Date 2022/6/22 18:57
* @Description
*/
@TableName(name = "tab_stu")
public class Student {
@TableId(value = "id")
private Integer id;
private String sno;
private String sname;
private String sex;
private String phone1;
private String privince;
public Student() {
}
public Student(Integer id,String sno, String sname, String sex, String phone1, String privince) {
this.id = id;
this.sno = sno;
this.sname = sname;
this.sex = sex;
this.phone1 = phone1;
this.privince = privince;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", sno='" + sno + '\'' +
", sname='" + sname + '\'' +
", sex='" + sex + '\'' +
", phone1='" + phone1 + '\'' +
", privince='" + privince + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
public String getPrivince() {
return privince;
}
public void setPrivince(String privince) {
this.privince = privince;
}
}
DButil
package com.jxy.utils;
import java.sql.*;
/**
* @Author Jin XueYang
* @Date 2022/6/22 18:34
* @Description
*/
public class DBUtil {
public static Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3307/lesdb?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true";
String driverName = "com.mysql.cj.jdbc.Driver";
String username = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url,username,password);
return connection;
}
public static void closeAll(ResultSet rs, PreparedStatement ps,Connection con){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
BaseDao( It mainly writes the operations of adding, deleting, modifying and querying )
package com.jxy.utils;
import com.jxy.annotation.TableField;
import com.jxy.annotation.TableId;
import com.jxy.annotation.TableName;
import com.jxy.dao.StudentDao;
import com.jxy.entity.Student;
import java.lang.annotation.Annotation;
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.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Author Jin XueYang
* @Date 2022/6/22 18:54
* @Description
*/
public class BaseDao<T> {
ResultSet rs = null;
Connection connection = null;
PreparedStatement ps = null;
//BaseDao Generic T Reflection class of
private Class cla;
public BaseDao() {
// At this point, the reflection class is BaseDao Subclasses of
Class<? extends BaseDao> studentClass = this.getClass();
// Get the reflection object of the subclass inheriting the parent class And get the generic of the parent class
Type type = studentClass.getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) type;
Type[] actualType = pt.getActualTypeArguments();
// Get parent BaseDao The generic <student>
cla = (Class) actualType[0];
}
/**
* A full table query
* @return
*/
public List<T> selectAll(){
StringBuffer sql = new StringBuffer("select * from ");
TableName tableName = (TableName) cla.getAnnotation(TableName.class);
if(tableName == null){
throw new RuntimeException(" Table name annotation is not used ");
}
String name = tableName.name();
sql.append(name);
System.out.println(sql);
return selectCondition(sql.toString());
}
public List<T> selectCondition(String sql){
List<T> list = new ArrayList<>();
try {
connection = DBUtil.getConnection();
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
// Find a record every time you cycle
// Records are loaded into entities The entity is handed over to the set
while (rs.next()){
T t = (T) cla.newInstance();
Field[] declaredFields = cla.getDeclaredFields();
for(Field field:declaredFields){
field.setAccessible(true);
TableId tableId = field.getAnnotation(TableId.class);
if(tableId!=null){
field.set(t,rs.getObject(tableId.value()));
}else{
TableField tableField = field.getAnnotation(TableField.class);
if(tableField!=null){
// The column name is inconsistent with the attribute
//set() Set the field represented by this attribute object on the specified object variable to the specified new value
// adopt set(Object obj,value) Reset new property values
//getObject() Access to this ResultSet The value of the specified column in the current column of the object
field.set(t,rs.getObject(tableField.value()));
}else{
// The column name is consistent with the attribute
field.set(t,rs.getObject(field.getName()));
}
}
}
list.add(t);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}finally {
DBUtil.closeAll(rs,ps,connection);
}
return list;
}
/**
* according to id Inquire about
* @param id
* @return
*/
public T selectById(Object id){
StringBuffer sql = new StringBuffer("select * from ");
TableName tableName = (TableName) cla.getAnnotation(TableName.class);
if(tableName == null){
throw new RuntimeException(" Table name annotation is not used ");
}
String name = tableName.name();
sql.append(name+" where ");
Field[] declaredFields = cla.getDeclaredFields();
for(Field field:declaredFields){
TableId tableId = field.getAnnotation(TableId.class);
if(tableId!=null){
sql.append(tableId.value()+"="+id);
break;
}
}
System.out.println(sql);
List<T> list = selectCondition(sql.toString());
if(list!=null&&list.size()>0){
return list.get(0);
}else{
return null;
}
}
/**
*
* @param id
* @return
* Delete
*/
public int delete(Object id){
StringBuffer sql = new StringBuffer("delete from ");
TableName tableName = (TableName) cla.getAnnotation(TableName.class);
if(tableName == null){
throw new RuntimeException(" Table name annotation is not used ");
}
String name = tableName.name();
sql.append(name+" where ");
Field[] declaredFields = cla.getDeclaredFields();
for(Field field:declaredFields){
TableId tableId = field.getAnnotation(TableId.class);
if(tableId!=null){
sql.append(tableId.value()+"="+id);
System.out.println(sql);
}
}
try {
connection = DBUtil.getConnection();
ps = connection.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.closeAll(rs,ps,connection);
}
return 0;
}
/**
*
* @param t
* @return
* modify
*/
public int update(T t){
StringBuffer sq = new StringBuffer("update ");
Class<?> tClass = t.getClass();
TableName tableName = tClass.getAnnotation(TableName.class);
if(tableName==null){
throw new RuntimeException(" not used TableName Annotation tag table name ");
}
String name = tableName.name();
sq.append(name+" set ");
Field[] fields = tClass.getDeclaredFields();
String where = " where ";
for(Field f:fields){
f.setAccessible(true);
// Primary key column
TableId id = f.getAnnotation(TableId.class);
if(id!=null){
try {
where += id.value() + "=" +f.get(t);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else{
// Is not a primary key column
TableField field = f.getAnnotation(TableField.class);
if(field!=null){
try {
// For different column names and attribute names
sq.append(field.value() + "='" + f.get(t) + "',");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else{
try {
// For the same case of column name and attribute name
sq.append(f.getName() + "='" + f.get(t) +"',");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
String str = sq.substring(0, sq.lastIndexOf(","));
String sql = str + where;
try{
System.out.println(sql);
connection = DBUtil.getConnection();
ps = connection.prepareStatement(sql);
int i = ps.executeUpdate();
return i;
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.closeAll(rs,ps,connection);
}
return 0;
}
/**
*
* @param t
* @return
* add to
*/
public int insert(T t){
StringBuffer sql = new StringBuffer("insert into ");
Class<?> tClass = t.getClass();
TableName tableName = tClass.getAnnotation(TableName.class);
if(tableName==null){
throw new RuntimeException(" Not used TableName Annotation tag table name ");
}
String name = tableName.name();
sql.append(name+" values ");
// Set encapsulated value
ArrayList<Object> values = new ArrayList<>();
Field[] fields = tClass.getDeclaredFields();
for(Field f:fields){
f.setAccessible(true);
try {
Object value = f.get(t);
System.out.println("{
{
{
{
{
{
{
{
{
{
{
{
{
{"+value);
values.add("'"+value+"'");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/*System.out.println(values);*/
String replace = values.toString().replace("[", "(").replace("]", ")");
sql.append(replace);
System.out.println(sql);
try {
connection = DBUtil.getConnection();
ps = connection.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBUtil.closeAll(rs,ps,connection);
}
return 0;
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
StudentDao studentDao = new StudentDao();
// studentDao.insert(new Student(3,"206319"," Xiaofang "," male ","139"," Zhengzhou, Henan "));
// studentDao.update(new Student(3,"222"," Xiao Ming "," male ","11125"," Zhengzhou, Henan "));
// studentDao.delete(2);
System.out.println(studentDao.selectAll());
// System.out.println(studentDao.selectById(1));
}
}
Query all

Query individual

Insert
![]()
modify

Delete

边栏推荐
- 电商系统微服务架构
- JS获取display为none的隐藏元素的宽度和高度的解决方案
- Hanging mirror security won four global infosec awards on rsac2022
- Graphic view frame
- 地方经销商玩转社区团购模式,百万运营分享
- 影视随摘
- UE4 游戏架构 学习笔记
- Il n'est pas nécessaire d'appuyer longtemps sur la fonction de démarrage pour modifier Jelly [chapitre]
- Socket套接字C/S端流程
- Objects and object variables
猜你喜欢

Task and privilege level protection

地方经销商玩转社区团购模式,百万运营分享

【ODX Studio编辑PDX】-0.1-如何快速查看各Variant变体间的支持的诊断信息差异(服务,Sub-Function...)

Oracle-游标

对象与对象变量

It's not easy to say I love you | use the minimum web API to upload files (swagger support) # yyds dry inventory #

数学建模——图与网络模型及方法(一)

Hanging mirror security won four global infosec awards on rsac2022

分享 10 个 JS 闭包面试题(图解),进来看看你能答对多少
![[foreign journal] sleep and weight loss](/img/81/42dcfae19e72a0bc761cb7a40fe5d5.jpg)
[foreign journal] sleep and weight loss
随机推荐
杰理之快速触摸不响应问题【篇】
NC50965 Largest Rectangle in a Histogram
Mathematical modeling -- graph and network models and methods (I)
Notes on key vocabulary in the English original of the biography of jobs (11) [chapter nine]
Oracle-游标
U++ 学习笔记 堆
[micro service sentinel] rewrite Sentinel's interface blockexceptionhandler
NC24325 [USACO 2012 Mar S]Flowerpot
Pointer - function pointer
[autosar-dcm] - 4.3-how UDS $22 and $2e services read and write NVM data
Radis:Linux上安装Redis(步骤)
[QT] QT multithreading development - four methods to realize multithreading design
Objects and object variables
Storage unit conversion
Build your own website (22)
分享 10 个 JS 闭包面试题(图解),进来看看你能答对多少
#include errors detected. Please update your includePath.
Methods of adding styles to native JS
Local dealers play the community group purchase mode and share millions of operations
Go four singleton modes