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

边栏推荐
- Rails 3 activerecord: sort by association count - rails 3 activerecord: order by count on Association
- 【板栗糖GIS】arcscene—如何做出有高度的高程图
- Socket套接字C/S端流程
- [error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')
- Mathematical modeling -- graph and network models and methods (I)
- 用sentinel熔断比例阈值改不了,设置慢调用比例没效果
- Oracle-PL/SQL编程
- Storage unit conversion
- 位的高阶运算
- stop slave卡住--事务的事件没有复制完整
猜你喜欢

NC50965 Largest Rectangle in a Histogram

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

Task and privilege level protection

Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed

Socket socket c/s end process

图形视图框架

Struct, bit segment, enumeration, union
![NC24325 [USACO 2012 Mar S]Flowerpot](/img/cf/86acbcb524b3af0999ce887c877781.png)
NC24325 [USACO 2012 Mar S]Flowerpot

Dahua cloud native load balancing article - the passenger flow of small restaurants has increased
![Gas station [problem analysis - > problem conversion - > greed]](/img/15/5313f900abedb46ce82d8ab81af1d7.png)
Gas station [problem analysis - > problem conversion - > greed]
随机推荐
高并发介绍及应对
NC24325 [USACO 2012 Mar S]Flowerpot
What is the'function'keyword used in some bash scripts- What is the 'function' keyword used in some bash scripts?
Niuke: Dragon and dungeon games
[error record] the flutter reports an error (could not read script 'xxx\flutter\u tools\gradle\app\u plugin\u loader.gradle')
`${}`的用法
[QT] QT multithreading development - four methods to realize multithreading design
影视随摘
Leetcode circular linked list (fast and slow pointer) code line by line interpretation
JS syntax ES6, ES7, es8, es9, ES10, es11, ES12 new features (Abstract)
Unity发布WebGL播放声音的一种方法
How can I use knockout's $parent/$root pseudovariables from inside a . computed() observable?
钟薛高回应产品1小时不化:含固体成分 融化不能变成水
E-commerce system microservice architecture
[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
Market Research - current situation and future development trend of cell-based seafood market
JS获取display为none的隐藏元素的宽度和高度的解决方案
Pointer - function pointer
杰理之修改不需要长按开机功能【篇】
Golang面试整理 三 简历如何书写