ORM,即Object-Relational Mapping(对象关系映射)
1.类和表结构对应;2.属性(POJO)和字段(表中字段)对应;3、对象和记录对应
一、对类进行自定义注解
目的:来映射表,可以在运行的时候通过反射机制读取注解的信息
package
com.bjsxt.test.annotation;
import
java.lang.annotation.ElementType;
import
java.lang.annotation.Retention;
import
java.lang.annotation.RetentionPolicy;
import
java.lang.annotation.Target;
@Target
(value={ElementType.TYPE})
@Retention
(RetentionPolicy.RUNTIME)
public
@interface
SxtTable {
String value();
}
目的:来映射表中的字段,可以在运行的时候通过反射机制读取注解的信息
package
com.bjsxt.test.annotation;
import
java.lang.annotation.ElementType;
import
java.lang.annotation.Retention;
import
java.lang.annotation.RetentionPolicy;
import
java.lang.annotation.Target;
@Target
(value={ElementType.FIELD})
@Retention
(RetentionPolicy.RUNTIME)
public
@interface
SxtField {
String columnName();
String type();
int
length();
}
目的,来进行和对应数据库进行映射
package
com.bjsxt.test.annotation;
@SxtTable
(
"tb_student"
)
public
class
SxtStudent {
@SxtField
(columnName=
"id"
,type=
"int"
,length=
10
)
private
int
id;
@SxtField
(columnName=
"sname"
,type=
"varchar"
,length=
10
)
private
String studentName;
@SxtField
(columnName=
"age"
,type=
"int"
,length=
3
)
private
int
age;
public
int
getId() {
return
id;
}
public
void
setId(
int
id) {
this
.id = id;
}
public
String getStudentName() {
return
studentName;
}
public
void
setStudentName(String studentName) {
this
.studentName = studentName;
}
public
int
getAge() {
return
age;
}
public
void
setAge(
int
age) {
this
.age = age;
}
}
目的:通过运行时反射机制来读取实体类的注解信息,来拼凑sql语句,从而通过JDBC来创建表,从而达到ORM效果
package
com.bjsxt.test.annotation;
import
java.lang.annotation.Annotation;
import
java.lang.reflect.Field;
/**
* 使用反射读取注解的信息,模拟处理注解信息的流程
* @author 尚学堂高淇
*
*/
public
class
Demo03 {
public
static
void
main(String[] args) {
try
{
Class clazz = Class.forName(
"com.bjsxt.test.annotation.SxtStudent"
);
//获得类的所有有效注解
Annotation[] annotations=clazz.getAnnotations();
for
(Annotation a : annotations) {
System.out.println(a);
}
//获得类的指定的注解
SxtTable st = (SxtTable) clazz.getAnnotation(SxtTable.
class
);
System.out.println(st.value());
//获得类的属性的注解
Field f = clazz.getDeclaredField(
"studentName"
);
SxtField sxtField = f.getAnnotation(SxtField.
class
);
System.out.println(sxtField.columnName()+
"--"
+sxtField.type()+
"--"
+sxtField.length());
//根据获得的表名、字段的信息,拼出DDL语句,然后,使用JDBC执行这个SQL,在数据库中生成相关的表
}
catch
(Exception e) {
e.printStackTrace();
}
}
}