我认为GenericDAO
类是基类。它不是用来直接使用的。你检查过这篇文章吗?我检查了这篇文章并创建了一个示例项目。
例子
GitHub - generic-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 要求您配置映射对象关系设置。之后,您将享受将 object-to-sql 和 sql-to-object 的转换。
基于SQL的实体类
@Entity, @Table, @Id, @Column, @GeneratedValue
来自休眠
@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
是一种减少样板源代码的方法。
雇员资源类
- WEB API 上的 CRUD 操作
#create
, #read
,#update
或#delete
应该等同于
- SQL
INSERT
, SELECT
,UPDATE
和DELETE
您需要使用密钥识别一条或多条记录。在这种情况下,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 的帖子)
根据post,我们可以声明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 操作附加任何代码。例如,您可以使用or创建另一个简单的 SQL 表,例如divisions_table
or 。personnel_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 映射器现在略有下降。代替 Hibernate,你可以找到MyBatis , JOOQ