当前位置:网站首页>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);
}
}
边栏推荐
- ansible防火墙firewalld设置
- CAD插件的安装和自动加载dll、arx
- How to set up altaro offsite server for replication
- 中职网络子网划分例题解析
- 1. 兩數之和
- 2022.6.30DAY591
- [teacher Zhao Yuqiang] MySQL flashback
- Ansible firewall firewalld setting
- [set theory] relational closure (relational closure related theorem)
- kubernetes资源对象介绍及常用命令(五)-(ConfigMap)
猜你喜欢

Capacity expansion mechanism of map

伯努利分布,二项分布和泊松分布以及最大似然之间的关系(未完成)

Altaro virtual machine replication failed: "unsupported file type vmgs"

Apache+PHP+MySQL环境搭建超详细!!!

"C and pointer" - Chapter 13 advanced pointer int * (* (* (*f) () [6]) ()

Error 1045 (28000) occurs when Linux logs in MySQL: access denied for user 'root' @ 'localhost' (using password: yes)

为什么网站打开速度慢?
![[teacher Zhao Yuqiang] use the catalog database of Oracle](/img/0b/73a7d12caf955dff17480a907234ad.jpg)
[teacher Zhao Yuqiang] use the catalog database of Oracle

mapbox尝鲜值之云图动画
![[teacher Zhao Yuqiang] kubernetes' probe](/img/cc/5509b62756dddc6e5d4facbc6a7c5f.jpg)
[teacher Zhao Yuqiang] kubernetes' probe
随机推荐
Why is the website slow to open?
[advanced pointer (2)] | [function pointer, function pointer array, callback function] key analysis + code explanation
2022.7.2day594
Es 2022 officially released! What are the new features?
"C and pointer" - Chapter 13 function pointer 1: callback function 2 (combined with template to simplify code)
[explain in depth the creation and destruction of function stack frames] | detailed analysis + graphic analysis
Common exceptions when Jenkins is released (continuous update...)
ES 2022 正式发布!有哪些新特性?
32GB Jetson Orin SOM 不能刷机问题排查
Strategy pattern: encapsulate changes and respond flexibly to changes in requirements
kubernetes资源对象介绍及常用命令(五)-(ConfigMap)
Final review (Day2)
Solve the problem of automatic disconnection of SecureCRT timeout connection
Source insight License Activation
2022.6.30DAY591
1. Sum of two numbers
Apt update and apt upgrade commands - what is the difference?
[written examination question analysis] | | get [sizeof and strlen] [pointer and array] graphic explanation + code analysis
Together, Shangshui Shuo series] day 9
一起上水碩系列】Day 9