当前位置:网站首页>Tear the ORM container object relational mapping framework (JDBC container)
Tear the ORM container object relational mapping framework (JDBC container)
2022-07-21 06:37:00 【Have_ MonkeyG】
What is? ORM Containers ?
ORM:(Object relative Mapping) Object relational mapping framework . Help you automatically compare the records in the database with java Entity classes are mapped together .
One 、Maven in POM Dependencies that need to be introduced into the file
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
Two 、 Create database connection JDBCUtil Tool class
package com.gsh.orm.util;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class JDBCUtil {
private static String driverName;
private static String url;
private static String username;
private static String password;
static {
try {
// establish Prop File object
Properties properties=new Properties();
// Load profile
properties.load(new FileInputStream("db.properties"));
// Read the contents of the configuration file
driverName=properties.getProperty("jdbc.driverName");
url=properties.getProperty("jdbc.url");
username=properties.getProperty("jdbc.username");
password=properties.getProperty("jdbc.password");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConn()throws Exception{
Class.forName(driverName);
Connection connection= DriverManager.getConnection(url,username,password);
return connection;
}
public static void closeAll(Connection connection,PreparedStatement ps,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(connection!=null){
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、 ... and 、 Create database connection profile db.properties
Be sure to put it under the project file directory
jdbc.driverName=com.mysql.cj.jdbc.Driver
# Your database path
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
# Your database name
jdbc.username= user name
# Your database password
jdbc.password= password
#
Four 、 Create annotations ( Three )
1. Table name comments TableName
The purpose of creating the table name annotation is to prevent the inconsistency between the table name and the entity class name in the database
package com.gsh.orm.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Can only work on classes
@Target(value = ElementType.TYPE)
// It works at runtime
@Retention(value = RetentionPolicy.RUNTIME)
// Table name comments
public @interface TableName {
// Table name
String value();
}
2. Attribute annotation ( Column name annotation )TableField
In order to prevent the attribute name in the entity class from being different from the column name in the data table
package com.gsh.orm.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// On properties
@Target(value = ElementType.FIELD)
// It works at runtime
@Retention(value = RetentionPolicy.RUNTIME)
// Attribute annotation ( Prevent column names from being inconsistent with attribute names )
public @interface TableField {
// Name
String value();
}
3. Primary key annotations TableKey
effect : Get the primary key
Subsequent functions must be deleted according to the primary key , Modify... According to the primary key , Query information according to primary key
package com.gsh.orm.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Can only act on attributes
@Target(value = ElementType.FIELD)
// It works at runtime
@Retention(value = RetentionPolicy.RUNTIME)
// Primary key annotations
public @interface TableKey {
// Primary key
String value()default "id";
}
5、 ... and 、 Create a tool class BaseDao( Specifically curd The operation is all here )
BaseDao Generic types of
//T For entity class objects
public abstract class BaseDao<T>
BaseDao Owned properties
private static Connection connection;
private static ResultSet rs;
private static PreparedStatement ps;
1. Add method
Add data to the database
// Increase method
public int insert(T t) {
try {
// Define the storage of database statements strBuf
StringBuffer stringBuffer=new StringBuffer("insert into ");
// Create entity class t Reflection class of
Class<?> aClass = t.getClass();
//1. Get table name ( Get the table name annotation )
TableName tableNameAnnotation = aClass.getAnnotation(TableName.class);
// Define a string to store the obtained table name
String tableName="";
// Determine whether there are table name comments
if(tableNameAnnotation!=null){
// Annotate the table name with value Value is assigned to tableName
tableName=tableNameAnnotation.value();
}else {
// If there is no table name annotation, get the simple name of the object
tableName=aClass.getSimpleName();
}
// Add the obtained table name to our sql In the sentence
stringBuffer.append(tableName);
/*System.out.println(stringBuffer);*/
//2. Get all attribute objects in the reflection class object
Field[] declaredFields = aClass.getDeclaredFields();
// Two sets store column names and column values
List<String> columns=new ArrayList<>();// Store all column names
List<String> values=new ArrayList<>();// Store all column values
//for Loop through all column names and values
for (Field declaredField : declaredFields) {
// Turn on the permission to get values
declaredField.setAccessible(true);
// Get column name comments
TableField ColumnsAnnotation = declaredField.getAnnotation(TableField.class);
//if Disk to determine whether there is column name annotation
if(ColumnsAnnotation!=null){
// If there is, take out the value of the annotation and add it to the column name collection
columns.add(ColumnsAnnotation.value());
}else {
// If not, assign the attribute to the column name set
columns.add(declaredField.getName());
}
// Assign column values to column value sets
// Column values may have characters, so add single quotation marks to each column value
values.add("'"+declaredField.get(t)+"'");
}
// Add the column name set to sql In the sentence [] Replace with ()
stringBuffer.append(columns.toString().replace("[","(").replace("]",")"));
stringBuffer.append("values");
// Add a set of column values to sql In the sentence [] Replace with ()
stringBuffer.append(values.toString().replace("[","(").replace("]",")"));
System.out.println(stringBuffer);
// Call the database method
Connection conn = JDBCUtil.getConn();
PreparedStatement ps=conn.prepareStatement(stringBuffer.toString());
int i = ps.executeUpdate();
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(connection,ps,rs);
}
return 0;
}
2. Modification method
Modify the information according to the primary key
// Modification method
public int update (T t){
try {
// Stored in the database strBuf
StringBuffer stringBuffer=new StringBuffer("update ");
// Create a reflective object of an entity class
Class<?> aClass = t.getClass();
//1. Get table name
TableName TableNameAnnotation = aClass.getAnnotation(TableName.class);
// Define a string storage table name
String TableName="";
// Judge whether there is a table name annotation
if(TableNameAnnotation!=null){
// There are table name annotations , Take the value of the table name annotation and add it to sql In the sentence
TableName = TableNameAnnotation.value();
}else {
// No table name annotation , Get the simple name of the reflection object directly
TableName = aClass.getSimpleName();
}
// Add the table name to sql sentence
stringBuffer.append(TableName+" set ");
//2. Get all column names and column values
Field[] declaredFields = aClass.getDeclaredFields();
// Define a string to store the primary key
String TableKey="";
// Store the value of the primary key
String KeyValue="";
// Determine if there is a primary key
boolean k=false;
for (Field declaredField : declaredFields) {
// Open permission
declaredField.setAccessible(true);
// Get column attribute annotation
TableField declaredFieldAnnotation = declaredField.getAnnotation(TableField.class);
// Get the annotation of the current primary key column
TableKey tableKey = declaredField.getAnnotation(TableKey.class);
// Determine whether there are primary key annotations
if(tableKey!=null){
// There are primary key columns
TableKey=tableKey.value();// Store the primary key column name
KeyValue="'"+declaredField.get(t)+"'";// The column value of the column storing the primary key
}else {
// Judge whether there is column name annotation
if(declaredFieldAnnotation!=null){
k=true;
// Column notes , Add the value of the column annotation to the column name set
String colum = declaredFieldAnnotation.value();
// Add column names to sql In the sentence
stringBuffer.append(""+colum+"=");
stringBuffer.append("'"+declaredField.get(t)+"'"+",");
}else {
// No notes , Get the property name
String colum = declaredField.getName();
// Add column names to sql In the sentence
stringBuffer.append(""+colum+"=");
stringBuffer.append("'"+declaredField.get(t)+"'"+",");
}
}
}
if(k==false){
throw new RuntimeException(" You didn't add the primary key annotation !");
}
// Remove the last redundant , Number ( The contents before the last comma are all intercepted )
stringBuffer =new StringBuffer(stringBuffer.substring(0, stringBuffer.lastIndexOf(","))) ;
// Splice the primary key to sql sentence
stringBuffer.append(" where "+TableKey+"="+KeyValue);
// Call database
Connection connection=JDBCUtil.getConn();
PreparedStatement preparedStatement=connection.prepareStatement(stringBuffer.toString());
int i = preparedStatement.executeUpdate();
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(connection,ps,rs);
}
return 0;
}
3. Delete method
Delete the corresponding data according to the primary key
When deleting data, we will find that my passed parameter is id There is no way to pass directly id Get the name of the entity class
terms of settlement :
(1) At present BaseDao Create a reflection class under
private Class<?> clazz;
(2) Create a parameterless constructor
In nonparametric construction
a. Get the reflection object of the current class
b. Get the parent class of the current reflection class -- Include generics of the parent class
c. Get the generic reflection class
In this way, we get the reflection class of entity class
public BaseDao(){
//this The corresponding subclass object Get the reflection object of the current class
Class<? extends BaseDao> aClass = this.getClass();
// Get the parent class of the current reflection class -- Include generics of the parent class
ParameterizedType genericSuperclass1 = (ParameterizedType) aClass.getGenericSuperclass();
// Get the generic reflection class
Type[] actualTypeArguments = genericSuperclass1.getActualTypeArguments();
clazz= (Class<?>) actualTypeArguments[0];
}
// Delete method
public int delete(Object id){
try {
// Database statement sql
StringBuffer sql=new StringBuffer("delete from ");
//1. Get table name
TableName TableNameAnnotation = clazz.getAnnotation(TableName.class);
// Define a string storage table name
String TableName="";
// Judge whether there is a table name annotation
if(TableNameAnnotation!=null){
// There are table name annotations , Take the value of the table name annotation and add it to sql In the sentence
TableName = TableNameAnnotation.value();
}else {
// No table name annotation , Get the simple name of the reflection object directly
TableName = clazz.getSimpleName();
}
sql.append(TableName+" where ");
Field[] declaredFields = clazz.getDeclaredFields();
// Determine whether the primary key exists
boolean key=false;
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
// Get primary key
TableKey annotation = declaredField.getAnnotation(TableKey.class);
if(annotation!=null){
key=true;
sql.append(annotation.value()+"='"+id+"'");
break;
}
}
if(key==false){
throw new RuntimeException(" Missing primary key annotation !");
}
// Call database
Connection connection=JDBCUtil.getConn();
PreparedStatement preparedStatement=connection.prepareStatement(sql.toString());
int i = preparedStatement.executeUpdate();
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(connection,ps,rs);
}
return 0;
}
4. Query all methods
Query all data unconditionally
// Query all methods
public List<T> findAll(){
try {
List<T> list=new ArrayList<T>();
// Definition sql sentence
StringBuffer sql=new StringBuffer("select * from ");
//1. Get table name
TableName TableNameAnnotation = clazz.getAnnotation(TableName.class);
// Define a string storage table name
String TableName="";
// Judge whether there is a table name annotation
if(TableNameAnnotation!=null){
// There are table name annotations , Take the value of the table name annotation and add it to sql In the sentence
TableName = TableNameAnnotation.value();
}else {
// No table name annotation , Get the simple name of the reflection object directly
TableName = clazz.getSimpleName();
}
sql.append(TableName);
// Call the database method
Connection connection=JDBCUtil.getConn();
PreparedStatement ps=connection.prepareStatement(sql.toString());
ResultSet rs = ps.executeQuery();
while (rs.next()){
// Get objects through reflection classes
Object o=clazz.newInstance();
// Get objects
Field[] declaredFields = clazz.getDeclaredFields();
for (Field declaredField : declaredFields) {
// Open permission
declaredField.setAccessible(true);
// Get attribute value annotation
TableField tableField = declaredField.getAnnotation(TableField.class);
if(tableField!=null){
// Get the primary key annotation
TableKey tableKey = declaredField.getAnnotation(TableKey.class);
if(tableKey!=null){
// There are primary key annotations for assignment
declaredField.set(o,rs.getObject(tableKey.value()));
}else {
declaredField.set(o,rs.getObject(tableField.value()));
}
}else {
declaredField.set(o,rs.getObject(declaredField.getName()));
}
}
list.add((T) o);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(connection,ps,rs);
}
return null;
}
5. Conditional query
Query the corresponding data according to the primary key
// Query according to the primary key
public T findById(int id){
try {
// Definition sql sentence
StringBuffer sql=new StringBuffer("select * from ");
//1. Get table name
TableName TableNameAnnotation = clazz.getAnnotation(TableName.class);
// Define a string storage table name
String TableName="";
// Judge whether there is a table name annotation
if(TableNameAnnotation!=null){
// There are table name annotations , Take the value of the table name annotation and add it to sql In the sentence
TableName = TableNameAnnotation.value();
}else {
// No table name annotation , Get the simple name of the reflection object directly
TableName = clazz.getSimpleName();
}
sql.append(TableName+" where ");
// Judge if there is a comment
boolean key=false;
// Get the primary key annotation
Field[] declaredFields = clazz.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
// Open permission
declaredField.setAccessible(true);
// Get the primary key annotation
TableKey tableKey = declaredField.getAnnotation(TableKey.class);
if(tableKey!=null){
key=true;
sql.append(tableKey.value()+"="+id);
}
}
if(key==false){
throw new Exception(" Missing primary key !");
}
// database
Connection connection=JDBCUtil.getConn();
PreparedStatement ps=connection.prepareStatement(sql.toString());
ResultSet rs = ps.executeQuery();
Object o = clazz.newInstance();
while (rs.next()){
for (Field declaredField : declaredFields) {
// Open permission
declaredField.setAccessible(true);
// Get attribute value annotation
TableField tableField = declaredField.getAnnotation(TableField.class);
if(tableField!=null){
// Get the primary key annotation
TableKey tableKey = declaredField.getAnnotation(TableKey.class);
if(tableKey!=null){
// There are primary key annotations for assignment
declaredField.set(o,rs.getObject(tableKey.value()));
}else {
declaredField.set(o,rs.getObject(tableField.value()));
}
}else {
declaredField.set(o,rs.getObject(declaredField.getName()));
}
}
return (T) o;
}
System.out.println(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(connection,ps,rs);
}
return null;
}
6、 ... and 、 Create entity class (User)
This step is for better operation , Let users define entity classes by themselves , What entity classes are has no effect on us
package com.gsh.orm.entity;
import com.gsh.orm.annotation.TableField;
import com.gsh.orm.annotation.TableKey;
import com.gsh.orm.annotation.TableName;
/**
* @Auther: haohao
* @Date:2022/7/1419:27
*/
@TableName("tb_user")
public class User {
@TableKey("id")
private Integer id;
@TableField("username")
private String uname;
private String password;
private String name;
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(Integer id, String uname, String password, String name) {
this.id = id;
this.uname = uname;
this.password = password;
this.name = name;
}
}
7、 ... and 、 Create an entity class Dao( Here is the UserDao)
public class UserDao extends BaseDao<User> {
}
6、 ... and 、 Seven are written by users
We have completed all functions , Next is the test
边栏推荐
- LeetCode简单题之强密码检验器 II
- I/o reuse: select poll epoll
- Recurrent neural network (RNN)
- Le point d'interrogation est en place! Yu Jingchuan 2013 Best think "China Space Station", stars of the Sea to navigate!...
- codeforces:D1. Chopping Carrots (Easy Version)【最大最小值问题 + 控制一边让另一边尽量靠近 + 思维】
- 什么是 IP SSL 证书,如何申请?
- 6G: typical applications, key technologies and challenges
- 全球首条“消费-投资”公链——Genesis,受邀参加Consensus 2022
- Flink battle: consume Wikipedia real-time messages
- win10开机启动ps1脚本
猜你喜欢
[STL]string类的模拟实现
解密方舟的高性能内存回收技术——HPP GC
铁钉扎头、酸奶瓶“咬”舌……广东消防:暑期儿童安全不容忽视
有什么好玩的网页小游戏网站推荐么?
在 Business Application Studio 里使用 SAP UI5 应用消费 OData 的 Create 和 Delete 操作
你必须知道的4种 Redis 集群方案及优缺点对比
全球首条“消费-投资”公链——Genesis,受邀参加Consensus 2022
[问题已处理]-mysql使用同一个yaml使用nfs共享存储报错
codeforces:D1. Chopping Carrots (Easy Version)【最大最小值问题 + 控制一边让另一边尽量靠近 + 思维】
云原生平台,让边缘应用玩出花!
随机推荐
C语言整数类型
云原生(八) | Devops篇之深入Devops
R语言使用逻辑回归Logistic、单因素方差分析anova、异常点分析和可视化分类iris鸢尾花数据集
【系统设计】分布式键值数据库
工控安全PLC固件逆向三
自定义持久层框架MyORMFramework(二)—框架设计
有什么好玩的网页小游戏网站推荐么?
Section 1 of Chapter 2: detailed explanation of basic data types
[问题已处理]-helm提示kubernetes configuration file is group-readable
win10开机启动ps1脚本
Mobius inversion - Summary
[问题已处理]-jenkins免密登录exsi主机
Excel-vba quick start (VIII. Cell objects - common cell operations)
LeetCode简单题之强密码检验器 II
【云驻共创】全场景软件开发生产线,端到端提效,全链路安全
vs2019配置Qt5开发环境
Flink实战:消费Wikipedia实时消息
Exchange 2010 SSL证书安装文档
Custom persistence layer framework myormframework (III) - framework implementation
Rearrange characters of leetcode simple question to form target string