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

查询单个

插入
![]()
修改

删除

边栏推荐
- Utilisation de simpletk - 4. Question étrange
- php优化foreach中的sql查询
- [shutter] shutter gesture interaction (small ball following the movement of fingers)
- 钟薛高回应产品1小时不化:含固体成分 融化不能变成水
- Server response status code
- Unity publishes a method of webgl playing sound
- JS solution for obtaining the width and height of hidden elements whose display is none
- php实现根据输入的年龄查询出生日期符合的数据
- [QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
- 540. Single element in ordered array
猜你喜欢

Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
![NC24325 [USACO 2012 Mar S]Flowerpot](/img/cf/86acbcb524b3af0999ce887c877781.png)
NC24325 [USACO 2012 Mar S]Flowerpot

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

Build your own website (22)

20220702 how do programmers build knowledge systems?

SimpleITK使用——3. 常见操作

Wait to solve the zombie process

An overview of the development of affective computing and understanding research

Phpcms realizes the direct Alipay payment function of orders

Share how to make professional hand drawn electronic maps
随机推荐
SimpleITK使用——4. 奇怪的問題
Market Research - current market situation and future development trend of third-party data platform
PMP项目整合管理
[shutter] shutter gesture interaction (small ball following the movement of fingers)
Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed
Using rendertext() to output multiple lines of text with rendertext() in R shiny
Based on asp Net (used mobile phone sales management system) +asp Net+c # language +vs2010+ database can be used for course design and post design learning
[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
杰理之、产线装配环节【篇】
附加:【登录信息存储】与【登录状态校验】;(包括:总结了到目前为止,有关【登录信息存储】与【登录状态校验】的所有内容;)
540. Single element in ordered array
New feature of go1.18: introduce new netip Network Library
Mathematical modeling -- graph and network models and methods (I)
Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
PHP wechat red packet grabbing algorithm
Oracle cursor
Market Research - current market situation and future development trend of aircraft front wheel steering system
Unity3d learning notes 4 - create mesh advanced interface
Micro service gateway selection, please accept my knees!
Wait to solve the zombie process