当前位置:网站首页>手写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));
}
}
查询所有

查询单个

插入
![]()
修改

删除

边栏推荐
- Market Research - current market situation and future development trend of aircraft front wheel steering system
- 大话云原生之负载均衡篇-小饭馆客流量变大了
- 杰理之样机在多次触摸后会触发关机【篇】
- Commodity information management system (C language document version)
- New feature of go1.18: trylock, which has been tossed n times
- Task and privilege level protection
- Market Research - current market situation and future development trend of aircraft audio control panel system
- [autosar-dcm] - 4.3-how UDS $22 and $2e services read and write NVM data
- Utilisation de simpletk - 4. Question étrange
- Film and television excerpts
猜你喜欢
![NC24325 [USACO 2012 Mar S]Flowerpot](/img/cf/86acbcb524b3af0999ce887c877781.png)
NC24325 [USACO 2012 Mar S]Flowerpot

任务和特权级保护

Wait to solve the zombie process

Leetcode circular linked list (fast and slow pointer) code line by line interpretation

Micro service gateway selection, please accept my knees!

杰理之、产线装配环节【篇】

开发者分享 | HLS, 巧用AXI_master总线接口指令的定制并提升数据带宽-面积换速度...

Objects and object variables

大话云原生之负载均衡篇-小饭馆客流量变大了

20220702 how do programmers build knowledge systems?
随机推荐
Il n'est pas nécessaire d'appuyer longtemps sur la fonction de démarrage pour modifier Jelly [chapitre]
How can I use knockout's $parent/$root pseudovariables from inside a . computed() observable?
【外刊】睡眠与减肥
影视随摘
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)
杰理之如何测试按键的误触率【篇】
Market Research - current market situation and future development trend of night vision goggles for pilots
杰理之直接触摸样机的顶针反应不正常【篇】
php优化foreach中的sql查询
【微服务|Sentinel】重写sentinel的接口BlockExceptionHandler
Objects and object variables
杰理之样机在多次触摸后会触发关机【篇】
Oracle-PL/SQL编程
原生js添加样式的方法
[QT] QT multithreading development - four methods to realize multithreading design
Basic concepts of image and deep understanding of yuv/rgb
Necessary browser plug-ins for network security engineers
"Actbert" Baidu & Sydney University of technology proposed actbert to learn the global and local video text representation, which is effective in five video text tasks!
Niuke: Dragon and dungeon games
Notes on key vocabulary in the English original of the biography of jobs (11) [chapter nine]