gpt4 book ai didi

java - 产品创建不起作用(在带有 JPA 的 Spring MVC 下)

转载 作者:行者123 更新时间:2023-11-30 11:57:30 24 4
gpt4 key购买 nike

好吧,代码在测试环境下运行,但不在应用程序的前端上下文中运行。老实说,这让我发疯。

这是 Controller :

package org.admios.nuevoproyecto.controller;

import java.util.List;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import org.admios.nuevoproyecto.dao.ProductDAO;
import org.admios.nuevoproyecto.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.PathVariable;

import static java.lang.System.out;

@Controller
@RequestMapping("/product")
public class ProductController {

private static Logger logger = Logger.getLogger(ProductController.class);

@Autowired
ProductDAO pdi;

@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}

@RequestMapping(value="/list")
public void listAllProducts() {
List<Product> products = pdi.getProducts();

for (Product product : products) {
System.out.println("Title: " + product.getTitle());
System.out.println("Description: " + product.getDescription());
System.out.println("Price: " + product.getPrice());
System.out.println("--------");
}
}

@RequestMapping(value="/add", method=RequestMethod.POST)
public String addProduct(@ModelAttribute Product product, BindingResult result) {
logger.info("Entrando en el metodo para agregar nuevo producto");

// Product newProduct = new Product();
// newProduct.setTitle("Titulo del producto2s");
// newProduct.setDescription("Descripcion del producto");
// newProduct.setPrice(220f);

System.out.println(product.getPrice());

Product savedProduct = pdi.saveProduct(product);

System.out.println(savedProduct.getId());

return "hello";
}

@RequestMapping(value="/form")
public String viewForm() {
out.println("entering viewForm()");
return "addproduct";
}

@RequestMapping(value="/view/{id}", method=RequestMethod.GET)
public void viewProduct(@PathVariable("id") Long id) {
System.out.println(id);
}

@ModelAttribute("product")
public Product getProductObject() {
out.println("entering getProductObject()");
return new Product();
}
}

DAO 实现:

package org.admios.nuevoproyecto.dao;

import java.util.List;
import javax.persistence.EntityManagerFactory;
import org.admios.nuevoproyecto.model.Product;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class ProductDaoImp extends JpaDaoSupport implements ProductDAO {

private static Logger log = Logger.getLogger(ProductDaoImp.class);

@Autowired
public ProductDaoImp(EntityManagerFactory entityManagerFactory) {
super.setEntityManagerFactory(entityManagerFactory);
}

@Override
public List<Product> getProducts() {
return getJpaTemplate().find("select p from Product p");
}

@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public Product saveProduct(Product product) {
log.info("Trying to create a new product");

Product newProduct = getJpaTemplate().merge(product);
log.info(newProduct.getDescription());
log.info(newProduct.getTitle());
log.info(newProduct.getId());
log.info(newProduct.getPrice());

return newProduct;
}

@Override
public void removeProduct(Product product) {
getJpaTemplate().remove(product);
}

@Override
public Product getProductById(Integer id) {
return getJpaTemplate().find(Product.class, id);
}

}

applicationContext 看起来像这样: http://pastie.org/1175350

最佳答案

1.创建事务管理器如下:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >  
<property name="persistenceUnitName" value="persistanceUnit"/>
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${db.orm.showsql}" />
<property name="generateDdl" value="${db.orm.generateDdl}" />
<property name="database" value="${db.type}"/>
<property name="databasePlatform" value="${db.orm.dialect}" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>

2.使用persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="persistanceUnit" transaction-type="RESOURCE_LOCAL">
<description>Oracle db Persistence Unit</description>
<class>com.company.YourModelClass</class>
<properties/>
</persistence-unit>
</persistence>

3.在applicationContext.xml中添加如下注解

<context:component-scan base-package="com.yourcompany.basepackage" />

4.在服务类中注释您的 Entitymanager,例如:

 @PersistenceContext
private EntityManager em = null;

5.将 TrasnsactionManager 注入(inject):

private PlatformTransactionManager platformTransactionManager = null;

6.坚持对象,如:

platformTransactionManager .persist(obj);

关于java - 产品创建不起作用(在带有 JPA 的 Spring MVC 下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3773389/

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