当前位置:网站首页>手写ORM(对象关系映射)增删改查
手写ORM(对象关系映射)增删改查
2022-07-02 22:06:00 【倾心*】
目录

自定义注解
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();
}
实体
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(主写增删改查操作)
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泛型T的反射类
private Class cla;
public BaseDao() {
//此时反射类就是BaseDao的子类
Class<? extends BaseDao> studentClass = this.getClass();
//获取子类继承父类的反射对象 并得到父类的泛型
Type type = studentClass.getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) type;
Type[] actualType = pt.getActualTypeArguments();
//得到父类BaseDao的泛型<student>
cla = (Class) actualType[0];
}
/**
* 全表查询
* @return
*/
public List<T> selectAll(){
StringBuffer sql = new StringBuffer("select * from ");
TableName tableName = (TableName) cla.getAnnotation(TableName.class);
if(tableName == null){
throw new RuntimeException("未使用表名注解");
}
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();
//每循环一次找到一条记录
//记录装到实体 实体交给集合
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){
//列名与属性不一致
//set()将指定对象变量上此属性对象表示的字段设置为指定的新值
//通过set(Object obj,value)重新设置新的属性值
//getObject()获取此 ResultSet 对象的当前列中指定列的值
field.set(t,rs.getObject(tableField.value()));
}else{
//列名与属性一致
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;
}
/**
* 根据id查询
* @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("未使用表名注解");
}
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
* 删除
*/
public int delete(Object id){
StringBuffer sql = new StringBuffer("delete from ");
TableName tableName = (TableName) cla.getAnnotation(TableName.class);
if(tableName == null){
throw new RuntimeException("未使用表名注解");
}
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
* 修改
*/
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("未使用TableName注解标记表名");
}
String name = tableName.name();
sq.append(name+" set ");
Field[] fields = tClass.getDeclaredFields();
String where = " where ";
for(Field f:fields){
f.setAccessible(true);
//主键列
TableId id = f.getAnnotation(TableId.class);
if(id!=null){
try {
where += id.value() + "=" +f.get(t);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else{
//不是主键列
TableField field = f.getAnnotation(TableField.class);
if(field!=null){
try {
//针对列名属性名不一样的情况
sq.append(field.value() + "='" + f.get(t) + "',");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else{
try {
//针对列名属性名一样的情况
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
* 添加
*/
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("没有使用TableName注解标记表名");
}
String name = tableName.name();
sql.append(name+" values ");
//集合封装值
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","小方","男","139","河南郑州"));
// studentDao.update(new Student(3,"222","小明","男","11125","河南郑州"));
// studentDao.delete(2);
System.out.println(studentDao.selectAll());
// System.out.println(studentDao.selectById(1));
}
}
查询所有

查询单个

插入
![]()
修改

删除

边栏推荐
- 【AUTOSAR-DCM】-4.3-UDS $22和$2E服务如何读取和写入NVM数据
- Unity3d learning notes 4 - create mesh advanced interface
- 基于ASP.net的手机销售管理系统(二手手机销售管理系统)+ASP.NET+C#语言+VS2010+数据库可以用于课设、毕设学习
- PHP wechat red packet grabbing algorithm
- [shutter] shutter application theme (themedata | dynamic modification theme)
- Kubernetes resource object introduction and common commands (4)
- 附加:【登录信息存储】与【登录状态校验】;(包括:总结了到目前为止,有关【登录信息存储】与【登录状态校验】的所有内容;)
- Storage unit conversion
- Radis:Linux上安装Redis(步骤)
- Commodity information management system (C language document version)
猜你喜欢

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

UE4 game architecture learning notes
![[ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)](/img/2b/f31b81cedf37ca187bcaa20dfe0b83.png)
[ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)
![[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)](/img/4c/c8dae41fc2eb18b5153cf36861fc7d.jpg)
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)

Reading experience of just because
![[shutter] shutter resource file use (import resource pictures | use image resources)](/img/e9/94ae2e3ee315f490eb3cf14bcf2e49.jpg)
[shutter] shutter resource file use (import resource pictures | use image resources)

Source code analysis - lightweight asynchronous crawler framework Ruia

Oracle-游标
![[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)](/img/27/8594ba0b49d5008b7469967babed17.jpg)
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)

Kubernetes resource object introduction and common commands (4)
随机推荐
Dynamic memory allocation (malloc calloc realloc free)
数学建模——图与网络模型及方法(一)
UE4 UI自适应屏幕
Market Research - current market situation and future development trend of aircraft wireless intercom system
PHP implements querying the data matching the date of birth according to the entered age
'when to use const char * and when to use const char []' - when to use const char * and when to use const char []
Micro service gateway selection, please accept my knees!
Market Research - current situation and future development trend of cell-based seafood market
《乔布斯传》英文原著重点词汇笔记(十一)【 chapter nine】
U++ 学习笔记 堆
#include errors detected. Please update your includePath.
傑理之修改不需要長按開機功能【篇】
Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
Market Research - current situation and future development trend of sickle cell therapy Market
Market Research - current market situation and future development trend of aircraft audio control panel system
How can I use knockout's $parent/$root pseudovariables from inside a . computed() observable?
Simpleitk use - 3 Common operations
Oracle PL / SQL programming
Market Research - current market situation and future development trend of handheld wound imaging equipment
Market Research - current market situation and future development trend of genome editing mutation detection kit