简体   繁体   中英

Generic Hibernate DAO

appreciate it if some one could help on it.

My plan is to have two layers. One is Service layer and second is DAO layer. The service layer will do business logic and DAO layer will do CRUD data operations.

Have two hibernate entities named Person and Order. These two entities implement a BaseEntity interface. Would like to write a generic method in DAO layer, so that it can take any entity.

Any suggestion as how to write that generic dao method?

@Entity
@Table(name = "PERSON")
public class Person implements BaseEntity, java.io.Serializable {

private int id;
private String firstName;

public Person() {
}

@Id
@Column(name = "PERSON_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Column(name = "FIRST_NAME", nullable = false, length = 50)
public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}
}

@Entity
@Table(name = "PURCHASE_ORDER")
public class Order implements BaseEntity java.io.Serializable {

private int id;

public Order() {
}

@Id
@Column(name = "ORDER_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Transient
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public Set<OrderItem> getOrderItems() {
    return orderItems;
}

public void setOrderItems(Set<OrderItem> orderItems) {
    this.orderItems = orderItems;
}
}

Can you please advise as how to create a generic method which should take either Person or Order entity as input parameter?

Have Person and Order subclass a base DAO, the have the method take in the DAO.

This is how you would write a generic fetch method:

 public <T> T get(long id,Class<T> clazz) throws Exception{

            Session session = null;
            T t=null;
            try
            {
                session=getSessionFactory().openSession();
                t= (T) session.get(clazz.getCanonicalName(),id);
            }
            catch(Exception e)
            {
                throw e;
            }
                    finally{
                          if(session!=null) session.close();
                    }
            return t;
        }

Ignore the exception handling. Use you own exception handling technique.

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