减少hibernate所需的查询数量

时间:2016-10-11 01:28:31

标签: java hibernate

当使用hibernate从数据库填充表时,理想情况下想要使用最少量的查询,以便他们的应用程序很快。理想情况下,您不希望进行比正在构建的表中的列更多的查询,因为按查询分组将允许您填充所有行。因此,如果您有m列和n行,则只需执行m次查询。

但是我发现很难在没有编写新方法的情况下在我的Daos中实现这一点。假设您正在处理一个名为Employee的实体,并且您想计算平均工作小时数,那么您将需要2种方法:

public interface EmployeesDao
{
    public List<Double> averageOfHoursWorked(List<Integer> ids);
    public double averageOfHoursWorked(Integer id);
}

因此,当您想要创建表时,您将使用接受列表的方法,但是当您只处理单个员工时,您将使用带有单个ID的那个。

但是我不想写2个方法,我只想写一个理想的方法。但是如果我写一个方法,我最终会使用一个for循环,它会产生一大堆查询而不只是一个:

    // THIS IS BAD, creates many queries
    List<Integer> ids = Arrays.asList(1,3,5,99, 1921);
    for (Integer id : ids) {
        double avg = dao.averageOfHoursWorked(id);
        // .... doing some table stuff with avg...
    }

    // THIS IS GOOD, only 1 query, yet now I must write more code ):
    List<Double> avgs = dao.averageOfHoursWorked(ids);
    for (Double avg : avgs) {
        // .... doing some table stuff with avg...
    }

所以我知道第二个版本要快得多,但是编码需要更长的时间。但是当我写这篇文章时,我想我可以这样做:

class EmployeesDaoImp implements EmployeesDao {

    @Override
    public double averageOfHoursWorked(Integer id) {
        return averageOfHoursWorked(Arrays.asList(id)).get(0);
    }
}

然后我只需要写List<Double> averageOfHoursWorked(List<Integer> ids),这是个好主意吗?有人用hibernate制作表格更优雅吗?也许建筑师模式或其他东西会更好:

Table table = dao.buildTable().withIds(ids).columnId().columnAvgHoursWorked().columnDaysOff()

其中columnId()会给你一列id,columnAvgHoursWorked会给你另一个列有工作小时数的列,依此类推。使用hibernate创建表的最佳方法是什么,需要最少量的查询和代码。

3 个答案:

答案 0 :(得分:0)

我相信现在我了解您的问题,请参阅以下选项:

<h2 style="text-align: center;font-size: 25px;font-family: Arial, Helvetica, sans-serif;line-height: 1.3; margin-bottom: 18px; font-weight: 400;"><strong>Premium Transportation Servicing The Dominican Republic</strong></h2> <p style="text-align: center;">Transekur is the only company in the Dominican Republic dedicated exclusively to providing premium transportation and airport transfers in private, luxurious vehicles. No matter how big or small your vacation party, we have the transportation to fit your needs.</p> &nbsp; <div style="width: 100%; background-color: white; border: 1px solid grey; height:100%;"> <div id="first_div" style="width: 100%; background-color: #ca7a09;"> <h2 style="text-align: center; color: white; padding-top: 5%;font-size: 36px;">The benefits of using Transekur</h2> <div style="display: flex; display: -webkit-flex; overflow: auto;"> <div class="first_image" style="width: 25%;"><img style="display: block; margin-left: auto; margin-right: auto; padding-top: 12%;" src="http://transekur.seobrandserver.com/wp-content/uploads/2016/10/wifi.png" /> <h3 style="text-align: center; color: white;padding-top: 3%;padding-left:2%;">FREE Wi-Fi service</h3> <p style="text-align: center; color: white;padding-top: 15%;padding-left:2%;">All of our modern luxury vehicles come equipped with mobile hotspot Wi-Fi service, so that you always have internet on the go. </p> </div> <div class="second_image" style="width: 25%;"><img style="display: block; margin-left: auto; margin-right: auto;" src="http://transekur.seobrandserver.com/wp-content/uploads/2016/10/phone-1.png" /> <h3 style="text-align: center; color: white; padding-top: 16%;">FREE Phone Service</h3> <p style="text-align: center; color: white;padding-left:2%;padding-top: 1%;">A mobile phone with unlimited calls within the Dominican Republic, the United States, Puerto Rico and Canada is provided free of charge for our clients during the rental period</p> </div> <div class="thirdt_image" style="width: 25%;"><img style="display: block; margin-left: auto; margin-right: auto;padding-top: 15%;" src="http://transekur.seobrandserver.com/wp-content/uploads/2016/10/car-1.png" /> <h3 style="text-align: center; color: white; padding-top: 1%;">New Vehicles</h3> <p style="text-align: center; color: white; padding-top: 15%;padding-left:2%;"> Transekur Premium Transport’s fleet of modern luxury SUV’s and limo buses come with leather interior, tinted windows, WiFi service, and cold beverages. These come standard in all of our vehicles.</p> </div> <div class="fourth_image" style="width: 25%;"> <img style="display: block; margin-left: auto; margin-right: auto; padding-top: 5%;" src="http://transekur.seobrandserver.com/wp-content/uploads/2016/10/driver.png" /> <h3 style="text-align: center; color: white; padding-top: 11%;">Bilingual Drivers</h3> <p style="text-align: center; color: white; padding-top: 13%;padding-right:5%">We are excellent communicators. If English is not your primary language, our drivers also speak French, German, Italian, Portuguese, and Spanish.</p> </div> </div> <!-- End of the first iner div flex div --> </div> <!-- End of the first div --> <div id="second_div" style="width: 100%; background-color: white; display: flex; display: -webkit-flex;height:100%;"> <div style="width: 50%;"> <p style="text-align: center;">Visited October 2016</p> <img style="display: block; margin-left: auto; margin-right: auto; border-radius: 50%;" src="http://transekur.seobrandserver.com/wp-content/uploads/2016/10/avatar030-1.jpg" /> <h2 style="text-align: center; color: gray;">Yezabel D</h2> </div> <div style="width: 50%;"> <a href="https://www.tripadvisor.com/ShowUserReviews-g147289-d10263324-r425689594-Transekur-Santo_Domingo_Santo_Domingo_Province_Dominican_Republic.html#CHECK_RATES_CONT" style="text-align: center; color: gray; margin-left: auto; margin-right: auto; padding-right: 10%;font-size:20px;color:#ca7a09;" target="_blank">"The best service there is, at a price you can’t resist."</a> <p style="margin-left: auto; margin-right: auto; padding-right: 10%;">I want to let you know how much my husband and I enjoyed our trips with Transekur. We used your service for trips to the Punta Cana airport. Very nice. Both of your drivers were on time and very courteous. We had used other services when we traveled to the Dominican before, needless to say yours is superior. Thank you for a trouble free ride to and from the airport, we will highly recommend your service to family and friends!</p> </div> </div> <!-- End of the second first div --> <div id="third_div" style="width: 100%; background-color: #363636;display:inline-block"> <style>@media only screen and (min-device-width: 320px) { #third_div{ display:block; } }</style> <img src="http://transekur.seobrandserver.com/wp-content/uploads/2016/03/logo_transekur.png"/> <h2 style="color:white;padding-left:50%;padding-top:2%;">Book Transport With Us Today!<h2> <p><a href="tel:18888858708">1-888-885-8708</a></p> <p><img src="http://transekur.seobrandserver.com/wp-content/uploads/2016/10/testgif.gif" style="width: 48px; height:24px;" /></p> </div> </div>

public abstract class GenericDAOImpl<T> implements GenericDAO<T>{

       private Class<T> entityBeanType;

       @Autowired
       protected SessionFactory sessionFactory;

       public GenericDAOImpl() {

          ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
           Type type = genericSuperclass.getActualTypeArguments()[0];

           @SuppressWarnings("unchecked")
           Class<T> clazz = (Class<T>) type;

           this.entityBeanType = clazz;
       }

       @SuppressWarnings("unchecked")
       public T save(T t) {
            T t1 = (T) sessionFactory.getCurrentSession().merge(t);
            sessionFactory.getCurrentSession().flush();
           return t1;
       }
    }

</code>

Repair that if you need to create another table, you will can extend this class to create a concrete DAO.

Example:

1 - create a table User and use the following code:

public class UserDAOImpl extends GenericDAOImpl<User> implements UserDAO{
    ///other specific methods will be here
}

2 - create a table Receipts and use the following code:

public class ReceiptsDAOImpl extends GenericDAOImpl<Receipts> implements     ReceiptsDAO{
  ///other specific methods will be here
}

泛型类型T可以是您软件的某个实体。

我希望我的回答可以帮助你。

答案 1 :(得分:-1)

起初,对不起我糟糕的英语。 我认为可以创建一个将成为数据对象的DTO对象,并且将包含要在JSP中使用的所有信息,您将把这些对象作为一个唯一方法的返回,并在一个唯一的调用中解决您的问题。

例如:

public List getAllEmployeesWithAverageHoursWorked(int start, int finish){

List<EmployeeDTO> result = new ArrayList<EmployeeDTO>();
///execute query that load registers that start in parameter start and finishes in parameter finish

return result;

List<EmployeeDTO> result = new ArrayList<EmployeeDTO>(); ///execute query that load registers that start in parameter start and finishes in parameter finish return result;

EmployeeDTO类将包含您需要在JSP页面中使用的所有字段,或者,如果此选项不能解决此问题,您将更改方法和类EmployeeDTO以获得所需的字段。

答案 2 :(得分:-1)

我不明白你的问题,但我会给出三种形式,我认为可以提供帮助。

1 - 使用泛型并对软件中的所有类型的对象使用相同的DAO。

2 - 在我的回答中可以指定你需要阅读的起点和终点,例如:你读了10条记录,现在需要阅读超过,然后你传递10和20,并阅读更多10

3 - 在第一次调用中,您将把所需的记录放在静态变量中并使用(这很可怕)。

如果你的问题不是“写”代码,使用泛型,那么解决这个问题是非常好的。

但是,如果我的答案不正确,请再次提出问题,但换句话说,我可以帮助你。