简体   繁体   中英

Generate service layer with Hibernate

I generate .hbm.xml mapping files and .java files from the DB schema, with Hibernate Tools. My question is, that is there any option, to generate service classes also? These are the classes where I implement the store(), find(), delete(), etc... methods. I know that for C# there are many solutions to generate almost everything. I'm looking for the same, but with Hibernate. Is there any?

No option to generate services.

You should be able to write just one generic DAO interface and implementation with Hibernate.

Like this:

package persistence;

import java.io.Serializable;
import java.util.List;

public interface GenericDao<T, K extends Serializable>
{
    T find(K id);
    List<T> find();
    List<T> find(T example);
    List<T> find(String queryName, String [] paramNames, Object [] bindValues);

    K save(T instance);
    void update(T instance);
    void delete(T instance);
}

Generating "services" doesn't make much sense for me as services typically implement business logic (that Hibernate can't magically generate).

Now, if what you mean is data access code ie DAOs (exposing and implementing CRUD methods and finders), then the Hibernate Tools can do that. That's the DAO code (.java) option on the capture of the Eclipse plugin shown below:

alt text http://docs.jboss.org/tools/2.0.0.GA/hibernatetools/en/html/images/codegenexporters.png

The equivalent Ant Task is hbm2dao .

But I personally don't use this feature and I'd go duffymo's way .

Spring Roo可能有您想要的。

You can implement the data access layer by just declaring interfaces, and having these implemented using JDK proxies, that then call hibernate methods. The details are here - A simple data access layer using hibernate .

I have implemented this and it works well and has grown to meet my needs. I extended the add(), remove() etc.. methods to also incude named queries ( findQueryName ) and use of Generics, so all I need to do to declare a basic CRUD data access interface is

   public interface SomeObjectDAO extends GenericDAO<SomeObject> {
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM