Hibernate
//模拟Hibernate
public class HibernateMock {
//模拟保存操作
public static void save(Object obj) {
try {
StringBuilder sql = new StringBuilder();
//sql.append("INSERT INTO student (name,age) VALUES (?,?)");
sql.append("INSERT INTO student (");
StringBuilder columnSql = new StringBuilder();//拼接列的SQL
StringBuilder placeHolderSql = new StringBuilder();//拼接占位符的SQL
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass(),Object.class);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String propertyName = pd.getName();
columnSql.append(propertyName).append(",");
placeHolderSql.append("?").append(",");
}
//删除最后一个,
columnSql.deleteCharAt(columnSql.length()-1);
placeHolderSql.deleteCharAt(placeHolderSql.length()-1);
sql.append(columnSql);
sql.append(") VALUES (");
sql.append(placeHolderSql);
sql.append(")");
System.out.println(columnSql);
Object[] params = {};
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
HibernateMock.save(new Student());
}
}
若表名和类名不一致,使用文件映射:
映射文件:处理表名和类名不同的情况,属性名和列名不同的情况
<class name = "......Student" table = "t_student">
<property name = "id" column = "sid"/>
<property name = "name" column = "sname"/>
<property name = "age" column = "sage"/>
</class>
或者使用注解来实现:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();
}
然后获取对象上的注解和注解里的值:
String tableName = obj.getClass().getSimpleName();
Table table = obj.getClass().getAnnotation(Table.class);
if (table != null) {
tableName = table.value();
}