java持久性适用于从数据库读取,无法插入/更新

时间:2014-05-24 08:17:20

标签: java hibernate jpa entitymanager spring-transactions

嗨,我不熟悉Hibernate和JPA。 这是我的VO课程。

Product.java

package com.sample.myproduct.valueobject;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import com.sample.myproduct.constants.MyproductConstants;


@Entity
@Table(name = "product")
@NamedQuery( 
          name=MyproductConstants.PRODUCT_NAMED_QUERY, 
          query=MyproductConstants.SELECT_QUERY_PRODUCT
        )
public class Product {

    @Id
    @Column(name="Product_id")
    int productId;

    @Column(name="Name")
    String name;

    @Column(name="Desc")
    String desc;

    @Column(name="Rating")
    int rating;

    @Column(name="stock")
    int stock;

    public int getProductId() {
        return productId;
    }
    public void setProductId(int productId) {
        this.productId = productId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public int getRating() {
        return rating;
    }
    public void setRating(int rating) {
        this.rating = rating;
    }
    public int getStock() {
        return stock;
    }
    public void setStock(int stock) {
        this.stock = stock;
    }   
}

Impl Class

package com.sample.myproduct.servicedao;

import java.util.List;
import java.util.Random;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;

import com.sample.myproduct.constants.MyproductConstants;
import com.sample.myproduct.valueobject.Product;

@Transactional
public class ProductDAOImpl implements ProductDAO {

    @PersistenceContext
    private EntityManager entityManagerFactory;

    public EntityManager getEntityManagerFactory() {
        return entityManagerFactory;
    }

    public void setEntityManagerFactory(EntityManager entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    public void save(Product product){
        entityManagerFactory.persist(product);
    }

    public Product getProductById(int id) throws DataAccessException{
        return entityManagerFactory.find(Product.class,id);
    }

}

}

persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"

    version="1.0">
    <persistence-unit name="JpaPersistenceUnit"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.sample.myproduct.servicedao.ProductDAOImpl</class>
    </persistence-unit>
</persistence>

servlet的context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
                 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                 http://www.springframework.org/schema/beans 
                 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                 http://www.springframework.org/schema/context
                 http://www.springframework.org/schema/context/spring-context-3.1.xsd
                 http://www.springframework.org/schema/tx 
                 http://www.springframework.org/schema/tx/spring-tx.xsd
                 http://www.springframework.org/schema/mvc
                 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing 
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.sample.myproduct" />

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost/testdb" p:username="root" p:password="" />

    <beans:bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="packagesToScan" value="com.sample.myproduct" />
        <beans:property name="jpaVendorAdapter">
            <beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </beans:property>
        <beans:property name="jpaProperties">
            <beans:props>
            <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
            </beans:props>
        </beans:property>
        <beans:property name="persistenceUnitName" value="entityManager" />
    </beans:bean>

    <beans:bean class="org.springframework.orm.jpa.JpaTransactionManager"
        id="transactionManager">
        <beans:property name="entityManagerFactory" ref="entityManagerFactory" />
    </beans:bean>

    <tx:annotation-driven mode="aspectj"
        transaction-manager="transactionManager" />

    <context:spring-configured />
    <context:annotation-config />

    <beans:bean id="productService"
        class="com.sample.myproduct.servicebo.ProductService">
    </beans:bean>

    <beans:bean id="productDAO" class="com.sample.myproduct.servicedao.ProductDAOImpl"></beans:bean>

</beans:beans>

我能够从数据库读取数据,但无法插入数据..没有任何异常。当我在persist函数后添加了entityManager.flush(); 由于没有交易正在进行,因此给予例外 我无法为此找到解决方案..

1 个答案:

答案 0 :(得分:0)

使用JpaTransactionManager时,您应该指定方言以及下方。

<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

<bean id="transactionManager" 
      class="org.springframework.orm.jpa.JpaTransactionManager">
   <property name="entityManagerFactory" ref="entityManagerFactory"/>
   <property name="jpaDialect" ref="jpaDialect"/>
</bean>

更新

从数据库读取数据不需要任何事务,但需要活动事务才能将数据写入数据库。

如果您没有正确配置事务管理器,则会以静默方式忽略@Transaction注释,并且所有操作都将运行,就像没有可用的事务一样;因此,您的写操作将失败。