开发者

Which one is the efficient solution for the following problem?

开发者 https://www.devze.com 2023-02-17 21:58 出处:网络
I have a struts and hibernate project, From the action class, I need t开发者_如何学Co call the DAO, to get the data from the database.

I have a struts and hibernate project,

  1. From the action class, I need t开发者_如何学Co call the DAO, to get the data from the database.

  2. I need all the fields in the form class, to be passed to method in the DAO.

The form has about 15 fields, all are of type String.

Which is better or efficient: Pass the fields directly to the DAO, or the entire FORM object as a parameter?


Imagine a method with 15 String parameters:

public void save(String name, String firstName, String email, String ..., String ..., String ..., String ..., String ..., String ..., String ..., String ..., String ..., String ..., String ..., String ...)

Oh look, a horizontal scrollbar. And a pretty small button. Hm. That looks dubious. Don't do it.

It's always better to collect parameters in a parameter object if you have more than 3 or 4 of them. Long parameter lists create the following problems:

  1. You can't omit any paramater. So if you don't need any of them, you'll have to pass lots of nulls or something.

  2. The order of parameters is fixed. If you need to change it, or add parameters, you're always in trouble. If you make a mistake (and you will), there is no easy way to find out where.

    If you use a parameter object with setters and getters, you can fill in the values in any order.

  3. Parameters have no name. Example:

    method("23894623");
    

    what does that mean? Look here:

    Params params = new Params();
    params.setPhoneNumber("23894623");
    method(params);
    

    Oh, it's a phone number. Now it's obvious.


Passing 15 parameters in a method or in a Collection based datastructure is error prone and hard to maintain.

You could simply pass your pojo (Form bean) into a Dao method and which will construct the query. As a bonus hibernate offers the hibernate Query by Example API which may suit you 100% for this problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消