使用JPA,Jersey从数据库中检索Blob(pdf)

时间:2016-02-17 08:27:02

标签: java rest jpa blob

我有一个在后端使用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吗?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

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

我有一个实体;

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

答案 1 :(得分:1)

  

是否有类似的方法从数据库中检索blob?或者我必须使用servlet吗?

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

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

$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$email = mysql_real_escape_string($_POST['email']);

 $checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'");

 if(mysql_num_rows($checkusername) == 1)
 {  
     $folderPath = "/path/to/your/dir".$username;

     if (!is_dir($folderPath)) {
        //--. CODE TO CREATE FOLDER HERE
        mkdir($folderPath, 0700);
     }