【问题标题】:Retrieve Blob(pdf) from database using JPA, Jersey使用 JPA, Jersey 从数据库中检索 Blob(pdf)
【发布时间】:2016-05-28 20:16:03
【问题描述】:

我在后端有一个使用 JPA-REST 的 JSP 页面,我已经设法将一个 blob 插入到数据库中。现在我希望能够 retrieve / GET 从数据库中获取 blob,但我似乎找不到任何关于如何通过 Jersey 而不是使用 servlet 来执行此操作的示例(我很新来创建我自己的 REST 服务)。

这是我用来插入 blob 到数据库的代码:

@POST
@Path("upload/{id}")
@Consumes({"application/x-www-form-urlencoded", "multipart/form-data"})
public void addBlob(@PathParam("id") Integer id, @FormDataParam("file") InputStream uploadedInputStream) throws IOException {
    ClientCaseDoc entityToMerge = find(id);
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        entityToMerge.setDocument(out.toByteArray());
        super.edit(entityToMerge);
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

是否有任何类似的方法可以从数据库中检索 blob?还是我必须使用 servlet?

非常感谢任何帮助。

【问题讨论】:

  • @BorisPavlović 老实说,我认为这些答案很不清楚,其中一个创建了自己的 PDFGenerator 类,另一个创建了一个 PNG 二维码,另一个发布了他的代码以导出 excel( xlsx),正如我在问题中提到的那样,我现在不使用 servlet..
  • 当然您使用的是 servlet。任何处理 Web 请求的服务器端 java 代码都是 servlet。 REST 使它更容易,但它仍然是一个 servlet。
  • @BorisPavlović 好吧,谢谢,我学到了一些新东西,现在..为什么人们在这种情况下使用 REST 时要创建自己的 servlet 类?这没有意义..
  • 嗯,不知道你说servlet是怎么想的……

标签: java rest jpa blob


【解决方案1】:

这已经得到回答,但有助于解决更广泛的问题;

我有一个实体;

@Entity
public class BlobEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

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

    @Lob
    @Column(name="DATA", length=100000)
    private byte[] data;

一个 JPA 存储库

@Repository
public interface BlobEntityRepository extends CrudRepository<BlobEntity, Long> {
}

还有一个读取word doc并从数据库中检索出来的测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-test.xml")
public class BlobEntitytRepositoryTest extends AbstractTest {

    @Autowired
    private BlobEntityRepository repository;

    @Test
    @Transactional
    public void test1() throws IOException {

        InputStream inputStream = getClass().getResourceAsStream("/HelloGreg.docx");
        byte[] byteArray = IOUtils.toByteArray(inputStream);

        BlobEntity blobEntity = new BlobEntity();
        blobEntity.setName("test");
        blobEntity.setData(byteArray);

        repository.save(blobEntity);

        assertEquals(1, repository.count());

        BlobEntity entity = repository.findOne(1l);
        assertNotNull(entity);

        FileOutputStream outputStream = new FileOutputStream(new File("testOut.docx"));
        IOUtils.write(entity.getData(), outputStream);
    }

}

配置

<?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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
    http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

    <context:component-scan base-package="com.greg" />
    <tx:annotation-driven />
    <jpa:repositories base-package="com.greg" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:file:~/data/jpa-test" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.greg" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            </props>
        </property>
    </bean>

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

</beans>

【讨论】:

  • 是否可以在不使用 Spring 和不使用 JPA 存储库的情况下做到这一点?我现在拥有的是一个Entity类,FacadeREST,pom.xml,AbstractFacade,Application Config,JSP pages。
  • 我要做的是在@Path("Download/{id}") 处,我想找到连接到该{id} 的blob 并将其作为回应
  • 你需要使用JPA(API)和Hibernate(实现,真的很简单,我已经添加了spring config。
  • 我正在使用 JPA 和球衣。
  • 我建议你创建一个服务层,它包装了一个存储库层。您可以通过复制测试来创建服务。 Jersey 只是在前端做所有请求/响应的事情。我展示的一切都是 JPA。
【解决方案2】:

是否有任何类似的方法可以从数据库中检索 blob?还是我必须使用 servlet?

虽然问题中没有提到,但我认为这是关于通过 Jersey 返回 BLOB 而不是使用 Servlet。 OP 如果我错了,请在 cmets 中纠正我。如果我是正确的,您可能希望更新您的问题以提及泽西岛。

我认为这个问题与Input and Output binary streams using JERSEY? 重复。然而,cmets 似乎对如何在 OPs 案例中实现它表现出一些困惑。当您在域模型中加载 PDF 时(如果这是一件好事,我会让其他人争论)不需要流式传输。您需要做的就是创建一个Response,并将entity 设置为数据层返回的字节数组。

@Path("upload/{id}")
@GET
public Response getPDF(@PathParam("id") Integer id) throws Exception {
    ClientCaseDoc entity = find(id);
    return Response
            .ok()
            .type("application/pdf")
            .entity(entity.getDocument()) // Assumes document is a byte array in the domain object.
            .build();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2011-09-09
    • 2012-01-25
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多