我仍然在努力改变我的Spring应用程序以使用Hibernate和JPA来进行数据库活动。显然,从以前的帖子我需要一个persistence.xml文件。但是,我是否需要更改当前的DAO类?
public class JdbcProductDao extends Dao implements ProductDao {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public List<Product> getProductList() {
logger.info("Getting products!");
List<Product> products = getSimpleJdbcTemplate().query(
"select id, description, price from products",
new ProductMapper());
return products;
}
public void saveProduct(Product prod) {
logger.info("Saving product: " + prod.getDescription());
int count = getSimpleJdbcTemplate().update(
"update products set description = :description, price = :price where id = :id",
new MapSqlParameterSource().addValue("description", prod.getDescription())
.addValue("price", prod.getPrice())
.addValue("id", prod.getId()));
logger.info("Rows affected: " + count);
}
private static class ProductMapper implements ParameterizedRowMapper<Product> {
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product prod = new Product();
prod.setId(rs.getInt("id"));
prod.setDescription(rs.getString("description"));
prod.setPrice(new Double(rs.getDouble("price")));
return prod;
}
}
}
我的Product.Java也在
之下public class Product implements Serializable {
private int id;
private String description;
private Double price;
public void setId(int i) {
id = i;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Description: " + description + ";");
buffer.append("Price: " + price);
return buffer.toString();
}
}
我想我的问题是, 将Hibernate + JPA与实体管理器
一起使用后,我当前的类会如何变化答案 0 :(得分:0)
您是否查看了官方文档中12.6. JPA的Chapter 12. Object Relational Mapping (ORM) data access部分?你需要知道的一切都在那里讨论。
如果这是一个选项,您应该扩展JpaDaoSupport
基类,它提供了方便的方法,如get/setEntityManagerFactory
和getJpaTemplate()
子类使用。如果没有,则注入EntityManagerFactory
并使用它来创建JpaTemplate
。有关详细信息,请参阅12.6.2. JpaTemplate and JpaDaoSupport部分。
另请查看Getting Started With JPA in Spring 2.0以获取更完整的示例(博客文章有点旧,但实际上并不过时),它将向您展示如何重写DAO的方法。
答案 1 :(得分:0)
此外,我建议您在决定设计之前阅读this article: Generic DAO with Hibernate and Spring AOP。