Java 通用DAO、Spring、Hibernate
我想了解如何在我的数据库上实现添加、编辑、删除和搜索等通用方法,我已经建立了连接(hibernate)并且工作正常 我有这个方法,很有效 类别:GenericDAO 我也有其他方法,我不知道如何使用它们 类别:GenericDAOJava 通用DAO、Spring、Hibernate,java,dao,genericdao,hibernate-generic-dao,Java,Dao,Genericdao,Hibernate Generic Dao,我想了解如何在我的数据库上实现添加、编辑、删除和搜索等通用方法,我已经建立了连接(hibernate)并且工作正常 我有这个方法,很有效 类别:GenericDAO 我也有其他方法,我不知道如何使用它们 类别:GenericDAO public void delete(最终对象){ Session Session=HibernateUtil.getSessionFactory().openSession(); Transaction=session.beginTransaction(); 删除(
public void delete(最终对象){
Session Session=HibernateUtil.getSessionFactory().openSession();
Transaction=session.beginTransaction();
删除(目标);
trans.commit();
}
/***/
公共T get(最终类类型,最终整型id){
Session Session=HibernateUtil.getSessionFactory().openSession();
Transaction=session.beginTransaction();
Object=(T)session.get(类型,id);
trans.commit();
返回(T)对象;
}
公共列表getAll(最终类类型){
Session Session=HibernateUtil.getSessionFactory().openSession();
Transaction=session.beginTransaction();
最终标准crit=session.createCriteria(类型);
List=crit.List();
trans.commit();
退货清单;
}
谢谢我认为
GenericDAO
类是基类。它不是直接使用的。你看过这篇文章了吗?我检查了这篇文章并创建了一个示例项目
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);
}
例如,您可能希望根据MySQL第一步示例创建一个API来检索所有员工列表
Employees表架构如下所示:
基本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转换为对象的过程
基于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@Entity、@Table、@Id、@Column、@GeneratedValue
来自lombok,它减少了getter/setter代码@Data、@noargsconstuctor
来自jaxb,您可能不需要使用它@XmlRootElement、@xmlacessorType
@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; }
GenericDAO
是一种减少样板源代码的方法
员工资源类
- webapi上的CRUD操作
,#创建
,#读取
或#更新
#删除
- SQL
,插入
,选择
和更新
删除
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);
}
}
p.S.
你需要记住这篇文章是十年前写的。而且,您应该认真考虑哪个O/R映射器真正好还是不好。我认为O/R映射器现在略有下降。您可以发现,我认为
GenericDAO
类是基类,而不是Hibernate。它不是直接使用的。你看过这篇文章了吗?我检查了这篇文章并创建了一个示例项目
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);
}
例如,您可能希望根据MySQL第一步示例创建一个API来检索所有员工列表
Employees表架构如下所示:
基本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转换为对象的过程
基于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@Entity、@Table、@Id、@Column、@GeneratedValue
来自lombok,它减少了getter/setter代码@Data、@noargsconstuctor
来自jaxb,您可能不需要使用它@XmlRootElement、@xmlacessorType
@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; }
GenericDAO
是一种减少样板源代码的方法
员工资源类
- webapi上的CRUD操作
,#创建
,#读取
或#更新
#删除
- SQL
,插入
,选择
和更新
删除
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);
}
}
p.S.
你需要记住这篇文章是十年前写的。而且,您应该认真考虑哪个O/R映射器真正好还是不好。我认为O/R映射器现在略有下降。您可以发现,这是实现以Hibernate为中心的通用DAO的一种方法,而不是Hibernate。它提供了基本的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);
}
这是实现以hibernate为中心的通用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);
}
如果你希望得到任何有用的帮助,你需要更精确地描述“不工作”。你到底有什么问题?你说的“不工作”是什么意思?请分享异常和堆栈跟踪。对不起,我的意思是我不知道如何使用它们,不是说“不工作”,如果你希望得到任何有用的帮助,你需要对“不工作”更精确一点。你到底有什么问题?你说的“不工作”是什么意思?请分享异常和堆栈跟踪。对不起,我的意思是我不知道如何使用它们,不是“不工作”是的,我读了那篇文章。我不知道
@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();
}
}
@Configuration
@ComponentScan("com.base-package")
@EnableTransactionManagement
public class AppConfig {
// add hibernate configuration
// add beans
}