簡體   English   中英

通用DAO,春季,休眠

[英]Generic DAO, Spring, Hibernate

我想了解如何在數據庫上實現添加,編輯,刪除和搜索之類的通用方法,我已經建立了連接(休眠)並且工作正常

我有這種方法,有效

類: GenericDAO

public <T> T save(final T o){
        Session session=HibernateUtil.getSessionFactory().openSession();
        Transaction trans=session.beginTransaction();
        Object object = (T) session.save(o);
        trans.commit();
        return (T) object;
    }

和在主要

GenericDAO gen = new GenericDAO();
gen.save(object); 

我也有其他方法,我不知道如何使用它們

類: GenericDAO

public void delete(final Object object){
   Session session=HibernateUtil.getSessionFactory().openSession();
   Transaction trans=session.beginTransaction();
   session.delete(object);
   trans.commit();
}

/***/
public <T> T get(final Class<T> type, final int id){
    Session session=HibernateUtil.getSessionFactory().openSession();
    Transaction trans=session.beginTransaction();
    Object object = (T) session.get(type, id);
    trans.commit();
    return (T) object;
}

public <T> List<T> getAll(final Class<T> type) {
    Session session=HibernateUtil.getSessionFactory().openSession();
    Transaction trans=session.beginTransaction();
    final Criteria crit = session.createCriteria(type);
    List<T> list = crit.list();
    trans.commit();
    return list;
}

謝謝

我認為GenericDAO類是基類。 它不是直接使用。 您檢查了這篇文章嗎? 我檢查了這篇文章,並創建了一個示例項目。

GitHub-dao-hibernate-樣本

例如,您可能想根據MySQL第一步創建一個API以檢索所有員工列表。

員工表架構如下所示:

基本SQL

    CREATE TABLE employees (
        emp_no      INT             NOT NULL,  -- UNSIGNED AUTO_INCREMENT??
        birth_date  DATE            NOT NULL,
        first_name  VARCHAR(14)     NOT NULL,
        last_name   VARCHAR(16)     NOT NULL,
        gender      ENUM ('M','F')  NOT NULL,  -- Enumeration of either 'M' or 'F'  
        hire_date   DATE            NOT NULL,
        PRIMARY KEY (emp_no)                   -- Index built automatically on primary-key column
                                               -- INDEX (first_name)
                                               -- INDEX (last_name)
    );

O / R映射

Hibernate要求您配置映射對象關系設置。 之后,您將享受將對象轉換為sql和sql-to-object的樂趣。

基於SQL的實體類

  • @Entity, @Table, @Id, @Column, @GeneratedValue來自Hibernate
  • @Data, @NoArgsConstructor來自@Data, @NoArgsConstructor ,它減少了getter / setter代碼
  • @XmlRootElement, @XmlAccessorType來自jaxb,您可能不需要使用它

     @Entity @Data @NoArgsConstructor @Table(name = "employees") @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement public class Employees implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "emp_no", unique = true) @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer empNo; @Column(name = "birth_date") private Date birthDate; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "gender") @Enumerated(EnumType.STRING) private Gender gender; @Column(name = "hire_date") private Date hireDate; } 

前端資源類

您始終需要編寫DAO(數據訪問對象)來訪問數據庫。 GenericDAO是一種減少樣板源代碼的方法。

員工資源類

  • WEB API上的CRUD操作
    • #create#read#update#delete

應該與

  • 的SQL
    • INSERTSELECTUPDATEDELETE

您需要標識一條記錄或帶有鍵的記錄。 在這種情況下, id是樣本主鍵。

    @Path("/employee")
    public class EmployeesResource {

        static Logger log = LoggerFactory.getLogger(EmployeesResource.class);

        @GET
        @Produces(MediaType.APPLICATION_JSON)
        public List<Employees> index(@BeanParam Employees paramBean) {
            EmployeesDao dao = (EmployeesDao) SpringApplicationContext.getBean("employeesDao");
            List<Employees> result = dao.read();
            System.out.println("Get all employees: size = " + result.size());
            return result;
        }

        @GET
        @Path("{id}")
        @Produces(MediaType.APPLICATION_JSON)
        public Employees show(@PathParam("id") Integer id) {
            EmployeesDao dao = (EmployeesDao) SpringApplicationContext.getBean("employeesDao");
            System.out.println("Get employees -> id = " + id);
            return dao.read(id);
        }

        @POST
        @Consumes(MediaType.APPLICATION_JSON)
        public Integer create(Employees obj) {
            EmployeesDao dao = (EmployeesDao) SpringApplicationContext.getBean("employeesDao");
            return dao.create(obj);
        }

        @PUT
        @Path("{id}")
        @Consumes(MediaType.APPLICATION_JSON)
        public void update(Employees obj, @PathParam("id") String id) {
            EmployeesDao dao = (EmployeesDao) SpringApplicationContext.getBean("employeesDao");
            dao.update(obj);
        }

        @DELETE
        @Path("{id}")
        public void destroy(@PathParam("id") Integer id) throws Exception {
            EmployeesDao dao = (EmployeesDao) SpringApplicationContext.getBean("EmployeesDao");
            dao.delete(id);
        }
    }

GenericDao接口和實現

界面 (如ibm的帖子所述)

根據帖子,我們可以聲明dao接口。 然后,我們應該實現該接口的方法。

    public interface GenericDao<T, PK extends Serializable> {

        /** Persist the newInstance object into database */
        PK create(T newInstance);

        /**
         * Retrieve an object that was previously persisted to the database using
         * the indicated id as primary key
         */
        T read(PK id);
        List<T> read();

        /** Save changes made to a persistent object. */
        void update(T transientObject);

        /** Remove an object from persistent storage in the database */
        void delete(PK id) throws Exception;
        void delete(T persistentObject) throws Exception;
    }

實作

    public class GenericDaoHibernateImpl<T, PK extends Serializable> implements GenericDao<T, PK> {

        private Class<T> type;

        @Autowired
        private SessionFactory sessionFactory;

        public SessionFactory getSessionFactory() {
            return sessionFactory;
        }

        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }

        public GenericDaoHibernateImpl(Class<T> type) {
            this.type = type;
        }

        // Not showing implementations of getSession() and setSessionFactory()
        private Session getSession() {
            Session session = sessionFactory.getCurrentSession();
            return session;
        }

        @Transactional(readOnly = false, rollbackFor = RuntimeException.class)
        public PK create(T o) {
            return (PK) getSession().save(o);
        }

        @Transactional(readOnly = false, rollbackFor = RuntimeException.class)
        public void update(T o) {
            getSession().update(o);
        }

        @Transactional(readOnly = true)
        public T read(PK id) {
            return (T) getSession().get(type, id);
        }

        @SuppressWarnings("unchecked")
        @Transactional(readOnly = true)
        public List<T> read() {
            return (List<T>) getSession().createCriteria(type).list();
        }

        @Transactional(readOnly = false, rollbackFor = RuntimeException.class)
        public void delete(PK id) {
            T o = getSession().load(type, id);
            getSession().delete(o);
        }

        @Transactional(readOnly = false, rollbackFor = RuntimeException.class)
        public void delete(T o) {
            getSession().delete(o);
        }

如果在項目中僅使用簡單的CRUD操作,則無需為SQL操作附加任何代碼。 例如,您可以使用extends GenericDao<Division, Integer>extends GenericDao<Personnel, Integer>創建另一個簡單的SQL表,例如divisions_tablepersonnel_table

編輯

要實例化與每個表相關的真實dao類,您需要配置applicationContext.xml和bean。

<bean id="employeesDao" parent="abstractDao">
    <!-- You need to configure the interface for Dao -->
    <property name="proxyInterfaces">
        <value>jp.gr.java_conf.hangedman.dao.EmployeesDao</value>
    </property>
    <property name="target">
        <bean parent="abstractDaoTarget">
            <constructor-arg>
                <value>jp.gr.java_conf.hangedman.models.Employees</value>
            </constructor-arg>
        </bean>
    </property>
</bean>

聚苯乙烯

您需要記住這篇文章是十年前寫的。 並且,您應該認真考慮哪個O / R映射器確實好。 我認為O / R映射器現在略有下降。 除了Hibernate,您還可以找到MyBatisJOOQ

這是實現休眠中心通用DAO的一種方法。 它提供基本的CRUD操作以及簡單的搜索,但可以擴展為包括其他通用功能。

IGenericDAO界面

public interface IGenericDAO<T extends Serializable> {

T findOne(long id);

List<T> findAll();

void create(T entity);

void update(T entity);

void delete(T entity);

void deleteById(long entityId);

public void setClazz(Class<T> clazzToSet);

}

抽象模板

import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class AbstractHibernateDAO<T extends Serializable> implements IGenericDAO<T> {

private Class<T> clazz;

@Autowired
SessionFactory sessionFactory;

public final void setClazz(Class<T> clazzToSet) {
    this.clazz = clazzToSet;
}


@Override
public T findOne(long id) {
    return (T) getCurrentSession().get(clazz, id);
}


@Override
public List<T> findAll() {
    return getCurrentSession().createQuery("from " + clazz.getName(),clazz).getResultList();
}


@Override
public void create(T entity) {
    getCurrentSession().persist(entity);
}


@Override
public void update(T entity) {
    getCurrentSession().merge(entity);
}


@Override
public void delete(T entity) {
    getCurrentSession().delete(entity);
}


@Override
public void deleteById(long entityId) {
    T entity = findOne(entityId);
    delete(entity);
}

protected final Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
    }
}

通用冬眠DAO

注意:這里使用范圍原型。 彈簧容器在每個請求上創建dao的新實例。

@Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class GenericHibernateDAO<T extends Serializable> extends AbstractHibernateDAO<T> 
implements IGenericDAO<T> {
   //
}

服務等級

顯示如何在服務類中使用自動連接通用dao以及如何向模型類傳遞參數。 另外,請注意,此實現使用@Transactional注釋進行Spring事務管理。

@Service
public class TestService implements ITestService {

private IGenericDAO<TestModel> dao;

@Autowired
public void setDao(IGenericDAO<TestModel> daoToSet) {
    dao = daoToSet;
    dao.setClazz(TestModel.class);

}

@Override
@Transactional
public List<TestModel> findAll() {
    return dao.findAll();
}
}

應用配置

顯示如何使用@EnableTransactionManagement為自動交易管理設置spring

@Configuration
@ComponentScan("com.base-package")
@EnableTransactionManagement
public class AppConfig {

       // add hibernate configuration

      // add beans


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM