自定义简单版ORMapping框架:
1、在mysql中创建相应的表
create table t_user(
id int not null auto_increment,
name varchar(10) not null,
age int not null,
birth_day date,
primary key(id)
);
我的mysql版本:
2、框架代码
HuiqBean.java:
package com.xiaoqiang.interview.framework.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by Huiq on 2021/4/11.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface HuiqBean {
String value();
}
HuiqField.java:
package com.xiaoqiang.interview.framework.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by Huiq on 2021/4/11.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface HuiqField {
String value();
}
BaseDAOImpl.java:
package com.xiaoqiang.interview.framework.dao.impl;
import com.xiaoqiang.interview.framework.dao.BaseDAO;
import com.xiaoqiang.interview.framework.utils.DBUtils;
import com.xiaoqiang.interview.framework.utils.Tools;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Created by Huiq on 2021/4/11.
*/
public class BaseDAOImpl implements BaseDAO {
/**
* 入参是T:User
*
* insert into t_user(name,age,birth_day) values(?,?,?);
*/
@Override
public <T> Serializable save(T t) {
StringBuilder builder = new StringBuilder("insert into ");
String table = Tools.getTable(t.getClass());
builder.append(table).append("(");
Class<?> clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("id")) {
String colum = Tools.getColum(field);
builder.append(colum).append(",");
}
}
builder.deleteCharAt(builder.toString().length()-1)
.append(") values (");
for (Field field : fields) {
if (!field.getName().equals("id")) {
builder.append("?,");
}
}
builder.deleteCharAt(builder.toString().length()-1)
.append(")");
System.out.println(builder.toString());
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int index = 1;
try {
connection = DBUtils.getConnection();
pstmt = connection.prepareStatement(builder.toString(), new String[]{"id"});
for (Field field : fields) {
if (!field.getName().equals("id")) {
String getMethod = Tools.getMethod(field);
Method method = clazz.getDeclaredMethod(getMethod);
Object obj = method.invoke(t);
pstmt.setObject(index++, obj);
}
}
int rowCount = pstmt.executeUpdate();
System.out.println("rowCount: " + rowCount);
if (rowCount > 0) {
rs = pstmt.getGeneratedKeys();
rs.next();
return (Serializable)rs.getObject(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
BaseDAO.java:
package com.xiaoqiang.interview.framework.dao;
import java.io.Serializable;
/**
* Created by Huiq on 2021/4/11.
*/
public interface BaseDAO {
/**
* insert into xxx(col1,col2,col3...) values(?,?,?...)
*/
<T> Serializable save(T t);
}
User.java:
package com.xiaoqiang.interview.framework.domain;
import com.xiaoqiang.interview.framework.annotation.HuiqBean;
import com.xiaoqiang.interview.framework.annotation.HuiqField;
import java.util.Date;
/**
* Created by Huiq on 2021/4/11.
*/
@HuiqBean("t_user")
public class User {
private Integer id;
private String name;
private Integer age;
@HuiqField("birth_day")
private Date birthday;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
public User(String name, Integer age, Date birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
DBUtils.java:
package com.xiaoqiang.interview.framework.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Created by Huiq on 2021/4/12.
*/
public class DBUtils {
public static Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/database1?useSSL=false";
String user = "root";
String password = "123456";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Tools.java:
package com.xiaoqiang.interview.framework.utils;
import com.xiaoqiang.interview.framework.annotation.HuiqBean;
import com.xiaoqiang.interview.framework.annotation.HuiqField;
import java.lang.reflect.Field;
/**
* Created by Huiq on 2021/4/11.
*/
public class Tools {
/**
* 根据注解获取表名
*/
public static String getTable(Class<?> clazz) {
String tableName = "";
HuiqBean huiqBean = clazz.getAnnotation(HuiqBean.class);
if (huiqBean != null) {
tableName = huiqBean.value();
} else {
tableName = clazz.getSimpleName();
}
return tableName;
}
/**
* 根据注解获取属性名称
*/
public static String getColum(Field field) {
String colum = "";
HuiqField huiqField = field.getAnnotation(HuiqField.class);
if (huiqField != null) {
colum = huiqField.value();
} else {
colum = field.getName();
}
return colum;
}
public static String getMethod(Field field) {
String fieldName = field.getName();
// id==>getId name==>getName
String name = fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
return "get" + name;
}
}
3、测试代码
BaseDAOImplTest.java:
package com.xiaoqiang.interview.framework.dao.impl;
import com.xiaoqiang.interview.framework.dao.BaseDAO;
import com.xiaoqiang.interview.framework.domain.User;
import org.junit.Test;
import java.io.Serializable;
import java.util.Date;
/**
* Created by Huiq on 2021/4/12.
*/
public class BaseDAOImplTest {
@Test
public void test02() {
BaseDAO dao = new BaseDAOImpl();
for (int i=0; i<10; i++) {
User user = new User("xiaoqiang" + i, 18+i, new Date());
Serializable id = dao.save(user);
System.out.println("id: " + id);
}
}
@Test
public void test01() {
BaseDAO dao = new BaseDAOImpl();
User user = new User("xiaoqiang", 18, new Date());
Serializable id = dao.save(user);
System.out.println("id: " + id);
}
}
DBUtilsTest.java:
package com.xiaoqiang.interview.framework.utils;
import org.junit.Test;
/**
* Created by Huiq on 2021/4/12.
*/
public class DBUtilsTest {
@Test
public void test01() {
System.out.println(DBUtils.getConnection());
}
}
ToolsTest.java:
package com.xiaoqiang.interview.framework.utils;
import com.xiaoqiang.interview.framework.domain.User;
import org.junit.Test;
import javax.tools.Tool;
import java.lang.reflect.Field;
/**
* Created by Huiq on 2021/4/11.
*/
public class ToolsTest {
@Test
public void test03() throws Exception {
Class<?> clazz = Class.forName("com.xiaoqiang.interview.framework.domain.User");
Field field = clazz.getDeclaredField("name");
System.out.println(Tools.getMethod(field));
field = clazz.getDeclaredField("birthday");
System.out.println(Tools.getMethod(field));
}
@Test
public void test02() throws Exception {
Class<?> clazz = Class.forName("com.xiaoqiang.interview.framework.domain.User");
Field field = clazz.getDeclaredField("birthday");
System.out.println(Tools.getColum(field));
}
@Test
public void test01() throws Exception {
System.out.println(Tools.getTable(User.class));
}
}