通用DAO,春天,冬眠



我想了解如何在我的数据库上实现添加、编辑、删除和搜索等通用方法,我已经建立了连接(休眠(并且工作正常

我确实有这种方法,有效

类:通用道

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); 

我还有其他我不知道如何使用它们的方法

类:通用道

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类是基类。它不适合直接使用。你检查过这篇文章吗?我查看了这篇文章并创建了一个示例项目。

  • 不要重复 DAO!

GitHub - 泛型 dao-hibernate 示例

例如,您可能希望创建一个 API 以根据 MySQL 第一步示例检索所有员工列表。

员工表架构如下所示:

基础 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)
);

手术室映射

休眠要求您配置映射对象关系设置。之后,您将享受将对象转换为SQL和SQL到对象的乐趣。

基于 SQL 的实体类

  • @Entity, @Table, @Id, @Column, @GeneratedValue来自Hibernate。
  • @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);
}
}

泛型道接口和实现

界面(来自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 映射器现在略有下降。而不是冬眠,你可以找到MyBatis,JOOQ

这是实现以休眠为中心的通用DAO的一种方法。它提供基本的 CRUD 操作以及简单的搜索,但可以扩展以包括其他通用功能。

IGeneric DAO 接口

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);
}

抽象模板DAO

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();
}
}

通用HiberateDAO

注:此处使用示波器原型。Spring 容器在每个请求上创建一个新的 dao 实例。

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

服务类

演示如何在服务类中使用自动连线泛型 DAO,并向模型类传递参数。另外,请注意,此实现使用 Spring 事务管理的@Transactional注释。

@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

}

相关内容

  • 没有找到相关文章

最新更新