当前位置:网站首页>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);
}
}
边栏推荐
- CAD插件的安裝和自動加載dll、arx
- Source insight License Activation
- [set theory] relational closure (reflexive closure | symmetric closure | transitive closure)
- How to install and configure altaro VM backup for VMware vSphere
- 88. 合并两个有序数组
- [teacher Zhao Yuqiang] index in mongodb (Part 1)
- Capacity expansion mechanism of map
- kubernetes资源对象介绍及常用命令(五)-(ConfigMap)
- Apt update and apt upgrade commands - what is the difference?
- [teacher Zhao Yuqiang] calculate aggregation using MapReduce in mongodb
猜你喜欢

卷积神经网络CNN中的卷积操作详解
![[together Shangshui Shuo series] day 7 content +day8](/img/fc/74b12addde3a4d3480e98f8578a969.png)
[together Shangshui Shuo series] day 7 content +day8

Deep learning, thinking from one dimensional input to multi-dimensional feature input

Introduction to redis using Lua script

Exception when introducing redistemplate: noclassdeffounderror: com/fasterxml/jackson/core/jsonprocessingexception

How to set up altaro offsite server for replication

Method of finding prime number

2022.DAY592

2022.DAY592
![[Zhao Yuqiang] deploy kubernetes cluster with binary package](/img/cc/5509b62756dddc6e5d4facbc6a7c5f.jpg)
[Zhao Yuqiang] deploy kubernetes cluster with binary package
随机推荐
"C and pointer" - Chapter 13 advanced pointer int * (* (* (*f) () [6]) ()
Introduction to redis using Lua script
【无标题】
1. Sum of two numbers
It is said that the operation and maintenance of shell scripts are paid tens of thousands of yuan a month!!!
CAD插件的安裝和自動加載dll、arx
1. 两数之和
AtCoder Beginner Contest 258(A-D)
2022.6.30DAY591
1. Somme des deux nombres
Altaro requirements for starting from backup on Hyper-V
Strategy pattern: encapsulate changes and respond flexibly to changes in requirements
[trivia of two-dimensional array application] | [simple version] [detailed steps + code]
[teacher Zhao Yuqiang] Alibaba cloud big data ACP certified Alibaba big data product system
Beaucoup de CTO ont été tués aujourd'hui parce qu'il n'a pas fait d'affaires
Ansible firewall firewalld setting
Final review Day8
MySQL startup error: several solutions to the server quit without updating PID file
How to install and configure altaro VM backup for VMware vSphere
chromedriver对应版本下载