|
1、在项目开发过程中,简单的插入sql可以通过注解实现自动生成sql
2、准备两个注解,分别是Table和Column,Table可记录表的信息,Column可记录字段的信息,通过这两个注解可以将JavaBean和数据库建立连接。
3、
Table注解代码如下:
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
public String name();
}
Column代码如下:
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
public String name();//通过该字段可将属性和数据库字段对应起来
public Class<?> type() default String.class;//该字段可将
}
JavaBean的代码如下:(不包含Get和Set方法)
@Table(name="jiudian")
public class Hotel {
@Column(name = "id", type = Integer.class)
private Integer id;
private String name;
private String dizhi;
private String style;
private String info;
private String pic;
private String tel;
...
}
自动生成插入sql代码如下:
public static boolean insertWithoutId(Object value) {
String sql = "insert into ";
Table table = value.getClass().getAnnotation(Table.class);
String columns = "( ";
String values = "( ";
//getDeclaredFields 获取当前类的所有属性
Field[] fields = value.getClass().getDeclaredFields();
List<Object> vals = new ArrayList<Object>();
//通过反射获取字段和注解,如果不存在注解,则默认数据库字段和属性一致,并且为varchar类型
for (Field field : fields) {
//insert into table (userName, ) values (?, )
if (!field.getName().equals("id")) {
Column column = field.getAnnotation(Column.class);
if (null != column ) {
columns = columns + " " + column.name() + ", ";
} else {
columns = columns + field.getName() + ",";
}
values = values + " ?, ";
//userName getUserName -> getUserName
try {
String name = field.getName();
String methodName = "get" + name.substring(0,1).toUpperCase() + name.substring(1);
//动态的调用getUserName方法
Method method = value.getClass().getDeclaredMethod(methodName);
vals.add(method.invoke(value));//通过调用getXxx方法,获取对象的值,装入列表中
} catch (Exception e) {
}
}
}
columns = columns.substring(0, columns.lastIndexOf(",")) + " ) ";
values = values.substring(0, values.lastIndexOf(",")) + " )";
sql = sql + table.name() + columns +" values " + values;
Connection conn = DbUtils.getConnection();
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
for (int i = 0 ; i < vals.size(); i++) {
ps.setObject(i+1, vals.get(i));//通过setObject可以给预执行文件设置值
}
ps.execute();
return true;
} catch (SQLException e) {
return false;
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
}
}
|
|