簡體   English   中英

使用JPA,Jersey從數據庫中檢索Blob(pdf)

[英]Retrieve Blob(pdf) from database using JPA, Jersey

我有一個在后端使用JPA-REST的JSP頁面,我已經設法將blob插入到數據庫中。 現在我希望能夠從數據庫中檢索/獲取 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?

任何幫助是極大的贊賞。

這已經得到了回答,但有助於解決更廣泛的問題;

我有一個實體;

@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> {
}

並且測試讀取單詞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>

從數據庫中檢索blob有什么類似的方法嗎? 或者我必須使用servlet?

雖然在問題中沒有提到,但我認為這是關於通過Jersey返回BLOB而不是使用Servlet。 如果我錯了,請在評論中糾正我。 如果我沒錯,您可以將您的問題更新為提及澤西島。

我認為這個問題是使用JERSEY輸入和輸出二進制流的重復 然而,評論似乎顯示出如何在OP案例中實現它的一些混亂。 當您在域模型中加載PDF時(如果這是一件好事,我會讓其他人爭論),不需要流式傳輸。 您需要做的就是創建一個Response ,將實體設置為數據層返回的字節數組。

@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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM