当前位置:网站首页>Simple handwritten ORM framework
Simple handwritten ORM framework
2022-07-03 05:51:00 【SSID-cc-r】
Simple handwriting ORM frame
Project structure 
1. introduce jar package <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.7</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
AnMyTableFieldId annotation
// Mark the primary key used
// Use
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnMyTableFieldId {
String value();
}
AnMyTableFiled
// Mark different field names
public @interface AnMyTableFiled {
String value();
}
AnMyTableName
// Custom annotation
// Can only be used on classes
@Target(ElementType.TYPE)
// Runtime annotations are still in scope
@Retention(RetentionPolicy.RUNTIME)
public @interface AnMyTableName {
String value();
}
AccountDao
public class AccountDao extends BaseDao<Account> {
}
Account
@AnMyTableName("account")
public class Account {
@AnMyTableFieldId("username")
private String username;
@AnMyTableFiled("balance")
private Integer balance;
@Override
public String toString() {
return "Account{" +
"username='" + username + '\'' +
", balance=" + balance +
'}';
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getBalance() {
return balance;
}
public void setBalance(Integer balance) {
this.balance = balance;
}
}
DbUtil
package com.ccr.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
@SuppressWarnings("all")
public class DbUtil {
// Declare the data source object
private static DataSource dataSource;
static {
try {
InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
// Read configuration file
properties.load(inputStream);
// According to the content in the configuration file datasourcse To configure
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// Get connection pool object
public static Connection getConn(){
// Get the connection object from the connection pool
try {
Connection connection = dataSource.getConnection();
return connection;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
// close resource
public static void close(ResultSet r, PreparedStatement ps, Connection c) {
if (r != null) {
try {
r.close();
if (ps != null) {
ps.close();
}
if (c != null) {
c.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
BaseDao
package com.ccr.util;
import com.ccr.annotation.AnMyTableFieldId;
import com.ccr.annotation.AnMyTableFiled;
import com.ccr.annotation.AnMyTableName;
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.List;
// Table plus data
public class BaseDao<T> {
public PreparedStatement ps;
public Connection conn;
public ResultSet rs;
private Class<?> aClass;
public BaseDao() {
// Of the direct superclass of the current object Type
// To obtain a subclass Dao Reflection class object
Class<? extends BaseDao> aClazz = this.getClass();
// Get subclass objects and subclass object generics
ParameterizedType genericSuperclass = (ParameterizedType) aClazz.getGenericSuperclass();
// Get generic objects in subclasses
Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
// Get the reflection object
aClass = (Class<?>) actualTypeArguments[0];
// System.out.println(aClass);
}
// Query all
public List<T> findAll() {
// The query method is to use an array
List<T> list = new ArrayList<T>();
StringBuffer sql = new StringBuffer("select * from ");
// Get table name
String tableName = aClass.getAnnotation(AnMyTableName.class).value();
// sql Add table name
sql.append(tableName);
// perform sql sentence
try {
// Connect to database
conn = DbUtil.getConn();
ps = conn.prepareStatement(sql.toString());
rs = ps.executeQuery();
// Get all field names
while (rs.next()){
// Create entity class objects
Object o = aClass.newInstance();
// Get the property name
Field[] declaredFields = aClass.getDeclaredFields();
for (Field f: declaredFields) {
// Set attribute courseware
f.setAccessible(true);
// Loop to get the attributes in the table , But not rigorous , The data in the entity class may not be compared with the data in the data group
// f.set(o,rs.getObject(f.getName()));
AnMyTableFieldId annotationid = f.getAnnotation(AnMyTableFieldId.class);
//
if (annotationid!=null){
f.set(o,rs.getObject(annotationid.value()));
}
AnMyTableFiled annotationname = f.getAnnotation(AnMyTableFiled.class);
if (annotationname!=null){
f.set(o,rs.getObject(annotationname.value()));
}else {
f.set(o,rs.getObject(f.getName()));
}
}
list.add((T) o);
}
} catch (Exception throwables) {
throwables.printStackTrace();
} finally {
DbUtil.close(null, ps, conn);
}
return list;
}
// according to id Inquire about
public T findById(Object id){
StringBuffer sql = new StringBuffer("select * from ");
// Get table name
String tableName = aClass.getAnnotation(AnMyTableName.class).value();
sql.append(tableName+" where ");
// Get primary key id
// Get all first
Field[] declaredFields = aClass.getDeclaredFields();
for (Field f: declaredFields){
AnMyTableFieldId annotationid = f.getAnnotation(AnMyTableFieldId.class);
if (annotationid!=null){
String valueid = annotationid.value();
// Add to data
sql.append(valueid+"='"+id+"'");
break;
}
}
try {
// Connect to database
conn = DbUtil.getConn();
ps = conn.prepareStatement(sql.toString());
rs = ps.executeQuery();
// Create entity class objects
Object o = aClass.newInstance();
// Get all field names
if (rs.next()){
for (Field f: declaredFields) {
// Set attribute courseware
f.setAccessible(true);
// Loop to get the attributes in the table , But not rigorous , The data in the entity class may not be compared with the data in the data group
// f.set(o,rs.getObject(f.getName()));
AnMyTableFieldId annotationid = f.getAnnotation(AnMyTableFieldId.class);
//
if (annotationid!=null){
f.set(o,rs.getObject(annotationid.value()));
}
AnMyTableFiled annotationname = f.getAnnotation(AnMyTableFiled.class);
if (annotationname!=null){
f.set(o,rs.getObject(annotationname.value()));
}else {
f.set(o,rs.getObject(f.getName()));
}
}
return (T) o;
}
} catch (Exception throwables) {
throwables.printStackTrace();
}finally {
DbUtil.close(null, ps, conn);
}
// System.out.println(sql);
return null;
}
// Add function add function of all tables . insert into surface () values()
public int insert(T t) {
try {
// Declare a string sql sentence
StringBuffer sql = new StringBuffer("insert into ");
// Get reflection class objects through generics
Class<?> aClass = t.getClass();
// Get the class name by annotation
AnMyTableName anMyTableName = aClass.getAnnotation(AnMyTableName.class);
// Get table name
String tableName = anMyTableName.value();
// Splice the obtained table names sql On
sql.append(tableName);
// Declare two sets Store column names separately The column value
// The column value
ArrayList<Object> values = new ArrayList<Object>();
// Name
ArrayList<String> columns = new ArrayList<String>();
// Get the column name of the added field through the reflection class
Field[] declaredFields = aClass.getDeclaredFields();
for (Field f : declaredFields) {
// Set the current class property value to visibility
f.setAccessible(true);
// Determine the properties of the current class id Is it empty
if (f.getAnnotation(AnMyTableFieldId.class) == null || f.get(t) != null) {
// When id When the value is equal to null, add
String name = f.getName();
// Add values through generics
Object value = f.get(t);
// Save the name in the defined class name array
columns.add(name);
// Values are stored in column values It is uncertain whether the value is the string column value plus ‘’
values.add("'" + value + "'");
}
}
// Get the column name and column value The data is The array situation appears, so we should put [] Replace ()
sql.append(columns.toString().replace("[", "(").replace("]", ")"));
sql.append("values ");
sql.append(values.toString().replace("[", "(").replace("]", ")"));
System.out.println(sql);
// Database connection
conn = DbUtil.getConn();
ps = conn.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
} catch (Exception e) {
DbUtil.close(null, ps, conn);
}
return 0;
}
// modify update Table name set Field = value where id=id;
public int update(T t) {
try {
StringBuffer sql = new StringBuffer("update ");
// 1. Get table name ,
Class<?> aClass = t.getClass();
// Get the corresponding table name in the database through annotations
AnMyTableName tableNamean = aClass.getAnnotation(AnMyTableName.class);
String tablename = tableNamean.value();
sql.append(tablename + " set ");
// obtain values value
Field[] declaredFields = aClass.getDeclaredFields();
// Acquisition conditions
String where = " where ";
for (Field f : declaredFields) {
// Set visibility
f.setAccessible(true);
// Get id Modify the data through judgment
AnMyTableFieldId annotation = f.getAnnotation(AnMyTableFieldId.class);
// Get data
String name = f.getName();
Object value = f.get(t);
/*if (annotation.equals("")||annotation!=null)*/
if (annotation == null || annotation.equals("")) {
sql.append(name + "='" + value + "',");
} else {
where += name + "='" + value + "'";
}
}
// Intercept where Before , Number
String s = sql.substring(0, sql.lastIndexOf(",")) + where;
Connection conn = DbUtil.getConn();
ps = conn.prepareStatement(s);
// System.out.println(s);
int i = ps.executeUpdate();
return i;
} catch (Exception e) {
} finally {
DbUtil.close(null, ps, conn);
}
return 0;
}
// Delete delete from Table name
public int delete(Object id) {
try {
StringBuffer sql = new StringBuffer("delete from ");
// Get the reflection object of the entity class Table name
String tableName = aClass.getAnnotation(AnMyTableName.class).value();
sql.append(tableName + " where ");
// Get primary key
Field[] declaredFields = aClass.getDeclaredFields();
// Cycle to get id
for (Field f : declaredFields) {
// Set field visibility
f.setAccessible(true);
// obtain id value
AnMyTableFieldId annotation = f.getAnnotation(AnMyTableFieldId.class);
// Judge id Is it empty to delete
if (annotation != null) {
// To get the column name
String vaid = annotation.value();
// Joining together to SQL in
sql.append(vaid + "='" + id + "'");
// Get to stop and delete
break;
}
}
// Get data link object
conn = DbUtil.getConn();
ps = conn.prepareStatement(sql.toString());
int i = ps.executeUpdate();
return i;
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
DbUtil.close(null, ps, conn);
}
return 0;
}
}
db.properties
# druid.properties Configuration of files
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/tranbook?serverTimezone=Asia/Shanghai
username=root
password=root
# Initialize the number of connections
initialSize=5
# maximum connection
maxActive=10
# Maximum timeout
maxWait=3000
Test
public class Test01 {
@Test
// according to id check
public void Test11(){
AccountDao accountDao = new AccountDao();
Account a = accountDao.findById(" Ha ha ha 21");
System.out.println(a);
}
@Test
// add to
public void Test12(){
AccountDao accountDao = new AccountDao();
Account account = new Account();
account.setUsername(" Ha ha ha ");
account.setBalance(12);
int insert = accountDao.insert(account);
System.out.println(" Add success "+insert);
}
@Test
// modify
public void Test13(){
AccountDao accountDao = new AccountDao();
Account account = new Account();
account.setUsername(" Ha ha ha ");
account.setBalance(15);
int update = accountDao.update(account);
System.out.println(" Modification successful "+update);
}
@Test
// Delete id
public void Test14(){
AccountDao accountDao = new AccountDao();
int a = accountDao.delete(" Ha ha ha ");
System.out.println(a);
}
@Test
// according to id check
public void Test15(){
AccountDao accountDao = new AccountDao();
List<Account> all = accountDao.findAll();
System.out.println(all);
}
}
边栏推荐
- Jetson AGX Orin 平台移植ar0233-gw5200-max9295相机驱动
- [escape character] [full of dry goods] super detailed explanation + code illustration!
- Redhat7系统root用户密码破解
- Final review (day3)
- "C and pointer" - Chapter 13 function pointer 1: callback function 2 (combined with template to simplify code)
- [together Shangshui Shuo series] day 7 content +day8
- Can altaro back up Microsoft teams?
- Why should there be a firewall? This time xiaowai has something to say!!!
- Communication - how to be a good listener?
- Altaro o365 total backup subscription plan
猜你喜欢
![[advanced pointer (2)] | [function pointer, function pointer array, callback function] key analysis + code explanation](/img/9b/a309607c037b0a18ff6b234a866f9f.jpg)
[advanced pointer (2)] | [function pointer, function pointer array, callback function] key analysis + code explanation

Personal outlook | looking forward to the future from Xiaobai's self analysis and future planning

Understand one-way hash function

一起上水硕系列】Day 9

How to set up altaro offsite server for replication

Error 1045 (28000) occurs when Linux logs in MySQL: access denied for user 'root' @ 'localhost' (using password: yes)
![[video of Teacher Zhao Yuqiang's speech on wot] redis high performance cache and persistence](/img/a7/2140744ebad9f1dc0a609254cc618e.jpg)
[video of Teacher Zhao Yuqiang's speech on wot] redis high performance cache and persistence

Apache+php+mysql environment construction is super detailed!!!

Qt读写Excel--QXlsx插入图表5

中职网络子网划分例题解析
随机推荐
It is said that the operation and maintenance of shell scripts are paid tens of thousands of yuan a month!!!
[branch and cycle] | | super long detailed explanation + code analysis + a trick game
[teacher Zhao Yuqiang] use Oracle's tracking file
NG Textarea-auto-resize
70 shell script interview questions and answers
The server data is all gone! Thinking caused by a RAID5 crash
@Import annotation: four ways to import configuration classes & source code analysis
[teacher Zhao Yuqiang] Flink's dataset operator
Apt update and apt upgrade commands - what is the difference?
How to set up altaro offsite server for replication
Niuke JS separator
Download the corresponding version of chromedriver
Es 2022 officially released! What are the new features?
Sorry, this user does not exist!
The programmer shell with a monthly salary of more than 10000 becomes a grammar skill for secondary school. Do you often use it!!!
Shanghai daoning, together with American /n software, will provide you with more powerful Internet enterprise communication and security component services
MySQL 5.7.32-winx64 installation tutorial (support installing multiple MySQL services on one host)
How to use source insight
Common exceptions when Jenkins is released (continuous update...)
Final review (Day6)