package cn.it.shop.service.impl;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import cn.it.shop.model.Category;
import cn.it.shop.service.BaseService;
@SuppressWarnings("unchecked")
public class BaseServiceImpl<T> implements BaseService<T> {
private Class clazz; //clazz中存储了当前操作的类型
private SessionFactory sessionFactory;
public BaseServiceImpl(){
System.out.println("this代表的是当前调用构造方法的对象:" + this);
System.out.println("获取当前this对象的父类信息:" + this.getClass().getSuperclass());
System.out.println("获取当前this对象的父类信息(包括泛型):" + this.getClass().getGenericSuperclass());
//获取泛型类
ParameterizedType type =(ParameterizedType)this.getClass().getGenericSuperclass();
clazz = (Class)type.getActualTypeArguments()[0];
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
@Override
public void save(T t) {
getSession().save(t);
}
@Override
public void update(T t) {
getSession().update(t);
}
@Override
public void delete(int id) {
String hql = "DELETE " + clazz.getSimpleName() + " WHERE id=:id";
getSession().createQuery(hql).setInteger("id", id).executeUpdate();
}
@Override
public T get(int id) {
return (T)getSession().get(clazz,id);
}
@Override
public List<Category> query() {
String hql = "FROM "+ clazz.getSimpleName();
return getSession().createQuery(hql).list();
}
}
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import cn.it.shop.model.Category;
import cn.it.shop.service.BaseService;
@SuppressWarnings("unchecked")
public class BaseServiceImpl<T> implements BaseService<T> {
private Class clazz; //clazz中存储了当前操作的类型
private SessionFactory sessionFactory;
public BaseServiceImpl(){
System.out.println("this代表的是当前调用构造方法的对象:" + this);
System.out.println("获取当前this对象的父类信息:" + this.getClass().getSuperclass());
System.out.println("获取当前this对象的父类信息(包括泛型):" + this.getClass().getGenericSuperclass());
//获取泛型类
ParameterizedType type =(ParameterizedType)this.getClass().getGenericSuperclass();
clazz = (Class)type.getActualTypeArguments()[0];
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
@Override
public void save(T t) {
getSession().save(t);
}
@Override
public void update(T t) {
getSession().update(t);
}
@Override
public void delete(int id) {
String hql = "DELETE " + clazz.getSimpleName() + " WHERE id=:id";
getSession().createQuery(hql).setInteger("id", id).executeUpdate();
}
@Override
public T get(int id) {
return (T)getSession().get(clazz,id);
}
@Override
public List<Category> query() {
String hql = "FROM "+ clazz.getSimpleName();
return getSession().createQuery(hql).list();
}
}