java学习

java学习

 

java自定义annotation模仿hibernate注解实体和表对象

package com.annotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={ FIELD, METHOD})
public @interface Column {
String ColumnName();
}
package com.annotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={ FIELD, METHOD})
public @interface Id {
}
package com.annotation;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={  TYPE})
public @interface Table {
String tableName();
}
package com;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.annotation.Column;
import com.annotation.Id;
import com.annotation.Table;
public class BaseDao<T,Pk> {
private Class<T> persistentClass;
@SuppressWarnings("unused")
private Class<Pk> persistentPK;
private String tableName;//表名称
private String id;//主键
public BaseDao() {
ParameterizedType ptype=(ParameterizedType) this.getClass().getGenericSuperclass();
Type[] types = ptype.getActualTypeArguments();
for (Type type : types) {
System.out.println(type.toString());
}
this.persistentPK = (Class<Pk>) types[1];
this.persistentClass = (Class<T>) types[0];
Table table = this.persistentClass.getAnnotation(Table.class);
tableName=table.tableName();
Field[] fields = this.persistentClass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Id annotationId = field.getAnnotation(Id.class);
if(annotationId != null){
Column annotationCo = field.getAnnotation(Column.class);
id=annotationCo.ColumnName();
break;
}
}
}
public T getT(T t){
System.out.println(tableName);
System.out.println(id);
return t;
}
}
package com;
import com.annotation.Column;
import com.annotation.Id;
import com.annotation.Table;
@Table(tableName = "t_user")
public class User {
@Id
@Column(ColumnName = "uid")
private String id="1";
public String getId()  {
return id;
}
public void setId(String id) {
this.id = id;
}
public User(String id) {
super();
this.id = id;
System.out.println("有参数");
}
public User() {
System.out.println("没有参数");
}
}
package com;
public class UserDao extends BaseDao<User, String>{
}

posted on 2017-11-14 17:15 杨军威 阅读(227) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜