Jndi,hibernate和entitymanager持久化和flush方法没有记录在数据库中

时间:2013-06-15 15:46:17

标签: spring hibernate spring-mvc jpa transactions

我在SpringMVC中向PostgreSQL数据库刷新数据时遇到问题。 当我使用entityManager.flush()时。

Table是在PosgreSQL中创建的,我可以使用pgadmin3但它存在但问题是我将元素从控制器传递到ImageDaoImpl后它没有将记录推送到数据库; /

@Repository

@Transactional(propagation = Propagation.REQUIRED)
public class ImageDaoImpl implements ImageDao {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public void register(Image image) { 
        em.persist(image);
        em.flush(); 
        return;
    }

}

当我想做注册方法时,它给我一个错误。 javax.persistence.TransactionRequiredException: no transaction is in progress

我试着这样做:

    @Transactional
public void register(Image image) {
    em.getTransaction().begin();
    em.persist(image);
    em.getTransaction().commit();
    return;
}

但它让我失望:

threw exception: java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead

首先,我认为有些事情是错误的,并添加了@PersistenceContext

我找到了EntityManager cannot use persist to save element to database

并尝试添加

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

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

但我接着想到如何附加经理是不可能的: 然后我得到这样的错误:

java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.JdbcTransactionObjectSupport

下一步该怎么做?我如何将<jee:jndi-lookup jndi-name="java:jboss/spring-quickstart/persistence" id="entityManagerFactory" ...与transactionManager集成? 他们之间有什么区别?我应该使用哪一个与数据库连接?

也许还有另一个我看不到的问题。

我设置了所有数据库连接但是flush的问题让我发疯了。在我想将信息推送到数据库之前,我没有尝试从浏览器中的实体读取信息。

我看了 Spring jta-transaction-manager

并试图评论该行

但是它让我失望:    (MSC服务线程1-2)上下文初始化失败:java.lang.NoClassDefFoundError:org / springframework / orm / jpa / JpaTransactionManager $ JpaTransactionObject

为什么找不到合适的解决方案: EntityManager persist() method does not insert record to database 我应该在哪里注册类Image来进行交易?

这是Controller的片段。

 @RequestMapping(value = "/save", method = RequestMethod.POST)
        public String save(
                @ModelAttribute("uploadForm") ImageDaoImpl uploadForm,
                        Model map, BindingResult result) throws IllegalStateException, IOException {
                           ...
                           String filePath = fileCatalog + orgName;                                        
                        Image memberImage = new Image();
                        memberImage.setFilePath(filePath);             
                        imageDao.register(memberImage);

                                 ...
                }
            }

我创建了对象并在数据库中设置了一个我需要的值。我得到的文件保存在硬盘中。我后来需要它用于我的另一个程序。 这是在应用程序中注册对象的好方法。也许是因为它没有刷新数据库?

最后我附上配置文件:

ImageDomain:

@Entity
@Table(name="IMAGES")
public class Image {

    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;

    @Column(name="NAME")
    private String name;

    @Column(name="CONTENTTYPE")
    private String contentType;

    @Column(name="LENGTH")
    private Integer length;

    @Column(name="ISPOCESSED")
    private boolean isprocessed;

    @Column(name="CONTENT")
    @Lob
    private Blob content;

    @Column(name="FILEPATH")
    private String filepath;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }

    public void setFilePath(String filepath) {
        this.filepath = filepath;
    }

    public String getFilePath(){
        return filepath;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContentType() {
        return contentType;
    }
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    public Blob getContent() {
        return content;
    }
    public void setContent(Blob content) {
        this.content = content;
    }
    public Integer getLength() {
        return length;
    }
    public void setLength(Integer length) {
        this.length = length;
    }

}

META-INF /弹簧/ applicationContext.xml的

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="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.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:component-scan base-package="org.springmvc.trophy.domain"/>

    <context:component-scan base-package="org.springmvc.trophy.repo"/>

    <tx:annotation-driven />

</beans>

META-INF /弹簧/ infrastructure.xml

 <?xml version="1.0" encoding="UTF-8"?>

    <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:jee="http://www.springframework.org/schema/jee"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
               http://www.springframework.org/schema/tx
               http://www.springframework.org/schema/tx/spring-tx.xsd
               http://www.springframework.org/schema/jee 
               http://www.springframework.org/schema/jee/spring-jee.xsd">

    <!-- JDNI name for EntityManagerFactory is defined in src/main/resources/META-INF/persistence.xml -->


    <jee:jndi-lookup jndi-name="java:jboss/spring-quickstart/persistence" id="entityManagerFactory"
                     expected-type="javax.persistence.EntityManagerFactory" />

    <bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:jta-transaction-manager /> 

</beans>

META-INF / Persistance.xml

<persistence version="2.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_2_0.xsd">
    <persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">
        <!-- If you are running in a production environment, add a managed data 
            source, this example data source is just for development and testing! -->
        <!-- The datasource is deployed as WEB-INF/spring-quickstart-ds.xml, you 
            can find it in the source at src/main/webapp/WEB-INF/spring-quickstart-ds.xml -->
         <jta-data-source>java:jboss/datasources/ImagesDS</jta-data-source>

        <properties>
           <property name="jboss.entity.manager.factory.jndi.name"
                value="java:jboss/spring-quickstart/persistence" />             
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.format_sql" value="true" />


        </properties>
</persistence-unit>

</persistence>

web应用/ WEB-INF /图像-ds.xml中

<?xml version="1.0" encoding="UTF-8"?>
<datasources xmlns="http://www.jboss.org/ironjacamar/schema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd">
    <!-- The datasource is bound into JNDI at this location. We reference this 
        in META-INF/persistence.xml -->
     <datasource jndi-name="java:jboss/datasources/ImagesDS"
        pool-name="kitchensink-quickstart" enabled="true" jta="false" use-java-context="true" use-ccm="false">
        <connection-url>jdbc:postgresql://localhost:5432/dermadb</connection-url>
        <driver-class>org.postgresql.Driver</driver-class>
        <driver>postgresql-9.1-901.jdbc4.jar</driver>
        <security>
            <user-name>username</user-name>
            <password>dbpassword</password>
        </security>
    </datasource> 
</datasources>

我为PostgreSQL部署了模块:在webapp / WEB-INF / jboss-deployment-structure.xml

<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.0">
   <deployment>
       <dependencies>
            <module name="org.postgresql"/>
            <!-- <module name="com.h2database.h2"/> -->
            <module name="org.codehaus.jackson.jackson-core-asl"/>
            <module name="org.codehaus.jackson.jackson-mapper-asl"/>
            <module name="org.slf4j"/>
       </dependencies>
   </deployment>
</jboss-deployment-structure>

提前感谢您的回答。

2 个答案:

答案 0 :(得分:0)

看起来像类路径问题。你想分享Spring库吗?如果没有,请验证您的依赖项中是否有spring-orm

答案 1 :(得分:0)

我终于解决了这个问题。

首先,我认为事务管理器出了问题,我将aspectj添加到项目中。

META-INF /弹簧/ infrastructure.xml

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

我还将库添加到Maven - 文件:POM.XML

 <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>2.5</version>
    </dependency>

最后我意识到我不需要使用提交和关闭交易等。正如你在我的第一篇文章中看到的那样。实体工厂和经理被认为是@PersistenceContext,我可以使用entityManager.persist(object)将对象传递到数据库,交易将结束。

我的错误是在persistence.xml中设置与数据库的连接期间 我在这一行使用了本地资源:

<persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">

并在下一步中使用JTA连接数据库。这是整个问题。

我将该行更改为

<persistence-unit name="primary" transaction-type="JTA">

并且发生了一切都很好并且对象被刷新到数据库。

感谢Pavel Horal的帮助,我希望这个答案可以帮助其他人。您需要始终注意细节。