有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在一个genericDao中可以不使用nvariables@Autowired

我试图用尽可能少的代码创建一个CRUD,基于:不要重复Dao;我有几个问题:

  1. 有一种方法可以不为数据库中的每个表创建变量:userService、phoneService、n千多个表
  2. 如果不可能的话。如何从字符串中获取这些变量来调用Dao的函数

控制器

String model = "phone"
Class<?> abc = model+"Service"; ??
Class<?> def = model; ??
abc.read(def, 1);

Dao

public interface GenericDao<E, K> {
 public E read(Class<E> type, K id);
}

@Repository
public class GenericDaoImpl<E, K extends Serializable> implements GenericDao<E, K> {
 @Autowired
 private SessionFactory sessionFactory;
 @Override
 public E read(Class<E> type, K id) {
  return currentSession().get(type, id);
 }
}

服务

public interface GenericService<E, K> {
 public List<E> read(Class<E> type);
}

@Service
@Transactional
public class GenericServiceImpl<E, K> implements GenericService<E, K> {
 @Autowired
 private GenericDao<E, K> dao;
 @Override
 public E read(Class<E> type, K id) {
  return dao.read(type, id);
 }
}

控制器

@RestController
@RequestMapping("/{model}")
public class CrudController extends Controller {
 @Autowired
 protected GenericService<User, Integer> userService;
 @Autowired
 protected GenericService<Phone, Integer> phoneService;
 @GetMapping("/{id}")
 public ResponseEntity<Object> read(@PathVariable String model, @PathVariable Integer id) {
  Object object = phoneService.read(Phone.class, id);
  return ResponseEntity.ok(object);
 }
}

共 (1) 个答案

  1. # 1 楼答案

    在我以前的一份工作中,我开发了一个Eclipse RCP桌面应用程序。这是一个ERP,所以想想它必须处理的大量数据库表,以及所有可能的参数化

    该架构是完全通用的,我的意思是,每个视图都基于一些元数据。虽然这种方法一开始可能看起来不错,但事实并非如此。强大的泛化意味着在整体设计中有很多折衷,泛化意味着在调试时变得疯狂,因为,好吧,一切都在那里进行
    泛化意味着在维护代码时变得疯狂。具体的用例呢?你需要以某种方式处理这件事

    典型的web应用程序没有那么大,它不处理数百个表。所以不要害怕重复同样的控制器-服务-存储库模式。这被称为关注点分离,甚至是数据和行为的封装

    把你的包裹整理好,一切都会好起来的