import java.util.List;
public interface BaseService<M extends java.io.Serializable, PK extends java.io.Serializable> {
public M findById(PK id);
public List<M> findByHQL(String hql, Object... params);
public void update(M entity);
public PK save(M entity);
public void saveOrUpdate(M entity);
public void delete(M entity);
public void deleteById(PK id);
}
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public abstract class BaseServiceImpl<M extends java.io.Serializable, PK extends java.io.Serializable> implements BaseService<M, PK> {
//这里不能使用spring3的ioc注入,泛型只在编译期间有效,所以必须在编译时决定类型。
//@Autowired spring4新特性泛型注入可以实现
//protected BaseDao<M, PK> dao;
/*public void setDao(BaseDao<M, PK> dao) {
this.dao = dao;
}*/
protected BaseDao<M, PK> dao;
@Override
public M findById(PK id) {
return this.dao.findById(id);
}
@Override
public List<M> findByHQL(String hql, Object... params) {
return this.dao.findByHQL(hql, params);
}
@Override
public void update(M entity) {
this.dao.update(entity);
}
@Override
public PK save(M entity) {
PK id = this.dao.save(entity);
/* test rollback
if (id != null)
throw new RuntimeException("runtime exception throw from " + this.getClass().getSimpleName() + ".save()");
*/
return id;
}
@Override
public void saveOrUpdate(M entity) {
this.dao.saveOrUpdate(entity);
}
@Override
public void delete(M entity) {
this.dao.delete(entity);
}
@Override
public void deleteById(PK id) {
this.dao.delete(this.findById(id));
}
}
///
public interface StudentService extends BaseService<Student, String> {
/**
* 添加 IBaseService 没有定义的方法
*/
public void serviceMethod();
}
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("studentService")
@Transactional
public class StudentServiceImpl extends BaseServiceImpl<Student, String> implements
StudentService {
protected StudentDao studentDao;
@Resource(name = "studentDao")
public void setStudentDao(StudentDao dao) {
super.dao = dao;
this.studentDao = dao;
}
@Override
public void serviceMethod() {
this.studentDao.studentMethod();
}
}