gpt4 book ai didi

java - 通用 DAO、Spring、Hibernate

转载 作者:行者123 更新时间:2023-12-01 20:17:47 24 4
gpt4 key购买 nike

我想了解如何在我的数据库上实现添加、编辑、删除和搜索等通用方法,我已经建立了连接( 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;
}

Main

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 - generic-dao-hibernate sample

例如,您可能希望创建一个 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)
);

对象/关系映射

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

基于SQL的实体类

  • @Entity, @Table, @Id, @Column, @GeneratedValue来自 Hibernate
  • @Data, @NoArgsConstructor来自 lombok,它减少了 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是一种减少样板源代码的方法。

EmployeesResource 类

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

应该等同于

  • SQL
    • INSERT , SELECT , UPDATEDELETE

您需要使用 key 来识别一条或多条记录。在这种情况下,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 接口(interface)和实现

界面(来自 ibm 的帖子)

根据帖子,我们可以声明dao接口(interface)。然后我们应该实现该接口(interface)的方法。

    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操作的代码。例如,您可以创建另一个简单的 SQL 表,如 divisions_tablepersonnel_table使用extends GenericDao<Division, Integer>extends GenericDao<Personnel, Integer> .

编辑

要实例化与每个表相关的真实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 而不是 Hibernate , JOOQ

关于java - 通用 DAO、Spring、Hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com