Product creation doesn't work (under Spring MV

2019-07-20 16:24发布

问题:

Well, the code is working under the Test Enviroment, but not on the front context of the application. This is driving me crazy to be honest.

Here is the 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();
    }
}

The DAO implementation:

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);
    }

}

The applicationContext looks like this: http://pastie.org/1175350

回答1:

1.Create transaction manager as follow :

<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.use 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.Add following annotation in applicationContext.xml

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

4.annoatate your Entitymanager in service class like:

 @PersistenceContext
 private EntityManager em = null;

5.Inject TrasnsactionManager to :

private PlatformTransactionManager platformTransactionManager = null;

6.persist object like:

platformTransactionManager .persist(obj);


回答2:

Have you tried with getJpaTemplate().persist(Object)?