产品创建不起作用(在带有JPA的Spring MVC下) [英] Product creation doesn't work (under Spring MVC with JPA)

查看:61
本文介绍了产品创建不起作用(在带有JPA的Spring MVC下)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,代码在测试环境"下工作,但不在应用程序的前端环境下工作.老实说,这使我发疯.

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.

这里是控制器:

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

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.使用persistance.xml

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.在applicationContext.xml中添加以下注释

3.Add following annotation in applicationContext.xml

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

4.在服务类中对Entitymanager进行注释,例如:

4.annoatate your Entitymanager in service class like:

 @PersistenceContext
 private EntityManager em = null;

5.将TrasnsactionManager注入到:

5.Inject TrasnsactionManager to :

private PlatformTransactionManager platformTransactionManager = null;

6.persist对象,例如:

6.persist object like:

platformTransactionManager .persist(obj);

这篇关于产品创建不起作用(在带有JPA的Spring MVC下)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆