首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JTA事务和线程

JTA事务和线程
EN

Stack Overflow用户
提问于 2015-12-18 13:29:10
回答 1查看 698关注 0票数 1

我想和JTA做一个多线程的治疗。

环境:

  • JBOSS AS 6.3
  • Java 7
  • Oracle 11.2g
  • CDI

处理:我想用数据库中的所有数据生成一个zip。这个zip文件可能很大,所以我想启动一个线程,在jboss将其发送到客户端的同时生成这个流。

我的休息项目:

代码语言:javascript
复制
@Stateless
@Path("/exportProcess")
public class ExportProcessusResource {

    @Inject
    private IExport export;

    @GET
    @Path("/{processCode: [^/]+}")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response export(@PathParam("processCode") final String pProcessCode) {
        return Response.ok(export.export(pProcessCode))
                                .header("Content-Disposition", "attachment; filename=" + pCodeProcessus + ".zip")
                                .build();
    }
}

我的模特:

代码语言:javascript
复制
@Entity
@Table(name = "T_PROCESS")
@NamedQueries({
    @NamedQuery(name = "Process.GetByCode", query = "SELECT p FROM Process p WHERE p.code=:code")
})
public class Process {

    @Column(name = "CODE", length = 50, nullable = false)
    private String code;

    @OneToMany(mappedBy = "process", targetEntity = Step.class)
    private Collection<Step> steps;

    //Getters/Setters
}

@Entity
@Table(name = "T_STEP")
public class STEP {
    @Id
    @Column(name = "ID_STEP")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_ID_STEP")
    @SequenceGenerator(name = "SEQ_ID_STEP", sequenceName = "SEQ_ID_STEP")
    private int id;

    @ManyToOne(targetEntity = Process.class)
    @JoinColumn(name = "CODE_PROCESS", referencedColumnName = "CODE", nullable = false)
    private Process process;

    //Getters/Setters
}

我的刀:

代码语言:javascript
复制
public interface IProcessDao {

    Processus getByCode(final String pCode);
}

public class ProcessDao implements IProcessDao {

    @Override
    public Processus getByCode(final String pCode) {
        Processus lResult = null;
        try {
            final TypedQuery<Processus> lRequest = pEm.createNamedQuery("Process.GetByCode", Process.class);
            lRequest.setParameter("code", pCode);
            lResult = lRequest.getSingleResult();
        } catch (final NoResultException e) {
            // Return null
            lResult = null;
        }
        return lResult;
    }
}

我的财务主任:

代码语言:javascript
复制
public interface IExport {

    /**
     * Generate export
     * 
     * @param pProcessCode Process code
     * @return Datas
     */
    InputStream export(final String pProcessCode);
}


public class Export implements IExport {

    @PersistenceContext(unitName="authorizations")
    private EntityManager entityManagerAuthorizations;

    @Inject
    private ExportThreadHelper exportThreadHelper;

    @Override
    public InputStream export(final String pProcessCode) {
        //Check if user has the profile. Use database "AUTHORIZATIONS"
        checkProfil(entityManagerAuthorizations, Profiles.ADMIN);

        final PipedInputStream lInputStream = new PipedInputStream();
        OutputStream lOutputStream = null;
        try {
            lOutputStream = new FileOutputStream("d:/test.zip");// new
                                                                // PipedOutputStream(lInputStream);
        } catch (final IOException e) {
            throw new RuntimeException("Cannot start zip generation", e);
        }

        final ZipOutputStream lZipOutputStream = new ZipOutputStream(lOutputStream);

        final Runnable lRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    exportThreadHelper.export(pProcessCode, lZipOutputStream);
                } catch (final Exception e) {
                    logger.error(e);
                } finally {
                    IOUtils.closeQuietly(lZipOutputStream);
                }
            }
        };
        //To execute in same thread :
        //lRunnable.run();

        //To execute in another thread
        final Thread lThread = new Thread(lRunnable);
        lThread.start();
        try {
            lThread.join();
        } catch (final InterruptedException e1) {
            throw new RuntimeException(e1);
        }


        try {
            return new FileInputStream("d:/test.zip");
        } catch (final FileNotFoundException e) {
            logger.error(e);
        }
        return lInputStream;
    }
}


public class ExportThreadHelper {

    private class ProcessToExport {
        //...
    }

    @PersistenceContext
    @Named("Application")
    private EntityManager entityManagerThreadable;

    @Inject
    private IProcessDao processDao;

    public void export(final String pProcesssCode, final ZipOutputStream pZipOutputStream)
                    throws MyWayBusinessException {
        try {

            final ProcessToExport lProcessToExport = new ProcessToExport();

            transaction(entityManagerThreadable, new Callable<Void>() {
                @Override
                public Void execute() {
                    final Process lProcess = processDao.getByCode(pProcesssCode);
                    for (final Step lStep : lProcess.getSteps()) {
                        //Many things
                    }
                    return null;
                }
            });

            //MANY OTHER TREATMENTS

        } catch (final Exception e) {
            logger.error(e);
            throw new RuntimeException("Cannot generate export", e);
        }
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    protected <T> T transaction(final EntityManager pEntityManager, final Callable<T> pCallable) {
        //I've tried with and without the annotation and with and without the "UserTransaction"
        try {
            final UserTransaction tx = com.arjuna.ats.jta.UserTransaction.userTransaction();
            try {
                tx.begin();
                final T lResultat = pCallable.execute();
                tx.commit();
                return lResultat;
            } catch (final Throwable e) {
                tx.rollback();
                throw e;
            }
        } catch (final Throwable e) {
            throw new RuntimeException(e);
        }
    }
}

我的persistence.xml:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<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="APPLICATION" transaction-type="JTA">
        <jta-data-source>java:/jdbc/app</jta-data-source>
        <class>Processus</class>
        <class>Step</class>
        <properties>
            <!-- Scan for annotated classes and Hibernate mapping XML files -->
            <property name="hibernate.archive.autodetection" value="class, hbm" />
        </properties>
    </persistence-unit>
    <persistence-unit name="AUTHORIZATION" transaction-type="JTA">
        <jta-data-source>java:/jdbc/AUTHORIZATION</jta-data-source>
        <!-- many things... -->
    </persistence-unit>
</persistence>

(我已经清理了密码,只保留重要的东西)。

而且,如果我使用单线程版本(lRunnable.run()),我有一个压缩文件,但是如果我运行了多线程版本(thread.start()) (为了确保我的测试没有通过父线程关闭连接,我在这里阻止了这个版本),但是在我要删除thread.join()之后,我就有了这个异常:

错误...ExportThreadHelper未能延迟初始化角色集合:.steps,无法初始化代理-无会话: org.hibernate.LazyInitializationException:未能延迟初始化角色:.steps的集合,无法初始化代理-在org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:569) hibernate-core-4.2.14.SP1-redhat-1.jar:4.2.14.SP1-redhat-1 at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:188) hibernate-core-4.2.14.SP1-redhat-1.jar:4.2.14.SP1-redhat-1 at org.hibernate.collection.internal.AbstractPersistentCollection没有会话.initialize(AbstractPersistentCollection.java:548) hibernate-core-4.2.14.SP1-redhat-1.jar:4.2.14.SP1-redhat-1 at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:126) hibernate-core-4.2.14.SP1-redhat-1.jar:4.2.14.SP1-redhat-1 at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266) hibernate-core-4.2.14。SP1-redhat-1.jar:4.2.14.SP1-redhat-1 at ExportThreadHelper$1.execute(ExportThreadHelper.java:101) metier-2.3.0-SNAPSHOT.jar: at ExportThreadHelper$1.execute(ExportThreadHelper.java:1) metier-2.3.0-SNAPSHOT.jar: at ExportThreadHelper.transaction(ExportThreadHelper.java:148) metier-2.3.0-SNAPSHOT.jar: at ExportThreadHelper.export(ExportThreadHelper.java:97) metier-2.3.0-快照。jar:在ExportMetier$1.run(ExportMetier.java:62) metier-2.3.0-SNAPSHOT.jar: at java.lang.Thread.run(Thread.java:722) rt.jar:1.7.0_04

你看到我的代码有问题了吗?

EN

回答 1

Stack Overflow用户

发布于 2015-12-18 13:49:12

您需要像这样更改查询:

代码语言:javascript
复制
@NamedQueries({
    @NamedQuery(name = "Process.GetByCode", query = "SELECT p FROM Process p LEFT JOIN FETCH p.steps WHERE p.code=:code")
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34356850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档