使用SSH操作Oracle中BLOB大对象

package entity;

/**
 * Bigobject entity. @author MyEclipse Persistence Tools
 */

public class Bigobject implements java.io.Serializable {

    // Fields

    private Integer id;
    private byte[] tblob;
    private String filename;

    // Constructors

    /** default constructor */
    public Bigobject() {
    }

    /** minimal constructor */
    public Bigobject(Integer id) {
        this.id = id;
    }

    /** full constructor */
    public Bigobject(Integer id, byte[] tblob, String filename) {
        this.id = id;
        this.tblob = tblob;
        this.filename = filename;
    }

    // Property accessors

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public byte[] getTblob() {
        return this.tblob;
    }

    public void setTblob(byte[]tblob) {
        this.tblob = tblob;
    }

    public String getFilename() {
        return this.filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

}

翻转表生成实体类 默认生成为String类型 需要把String 类型改为 byte[]

当然映射文件也要记得改

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="entity.Bigobject" table="BIGOBJECT" schema="SCOTT">
        <id name="id" type="java.lang.Integer">
            <column name="ID" precision="6" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="tblob" type="byte[]">  
            <column name="TBLOB" />
        </property>
        <property name="filename" type="java.lang.String">
            <column name="FILENAME" length="20" />
        </property>
    </class>
</hibernate-mapping>

接下来就开始写数据访问层代码

package dao;

import java.util.List;
 
import entity.Bigobject;
/**
  * 数据访问层接口
  * @author 尹涛
  *
  */
public interface BigobjectDao {
    /**
     * 获取所有信息
     * @return 信息列表
     */
  public List<Bigobject> find();
   /**
    * 添加信息
    * @param bigobject 实体对象
    * @return 添加结果(成功&失败)
    */
  public Integer addBigobject(Bigobject bigobject);
}

数据访问层接口实现类

package dao.impl;


import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import dao.BigobjectDao;
import entity.Bigobject;
 /**
  * 数据访问接口实现类
  * @author 尹涛
  *
  */
public class BigobjectDaoImpl extends HibernateDaoSupport implements
        BigobjectDao {

    @Override
    public List<Bigobject> find() {
        List<Bigobject> list=super.getHibernateTemplate().find("from Bigobject");    
        return list;
    }


    
    @Override
    public Integer addBigobject(Bigobject bigobject) {        
        return (Integer)super.getHibernateTemplate().save(bigobject);
    }


    
}

业务逻辑层代码

package service;

import java.util.List;

import entity.Bigobject;
 /**
  * 业务逻辑层接口
  * @author 尹涛
  *
  */
public interface BigobjectService {
    /**
     * 获取所有信息
     * @return 信息列表
     */
  public List<Bigobject> find();
   /**
    * 添加信息
    * @param bigobject 实体对象
    * @return 添加结果(成功&失败)
    */
  public Integer addBigobject(Bigobject bigobject);
}

业务逻辑层接口实现类

package service.impl;

import java.util.List;

import dao.BigobjectDao;

import entity.Bigobject;
import service.BigobjectService;
 /**
  * 业务逻辑层接口实现类
  * @author 尹涛
  *
  */
public class BigobjectServiceImpl implements BigobjectService {
    private BigobjectDao bd;  //数据访问层接口
    
    public BigobjectDao getBd() {
        return bd;
    }

    public void setBd(BigobjectDao bd) {
        this.bd = bd;
    }

    @Override
    public List<Bigobject> find() {
        // TODO Auto-generated method stub
        return bd.find();
    }

    @Override
    public Integer addBigobject(Bigobject bigobject) {
        
        return bd.addBigobject(bigobject);
    }

}

接下来就是action层代码

package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.List;

import org.apache.struts2.ServletActionContext;

import service.BigobjectService;

import com.opensymphony.xwork2.ActionSupport;


import entity.Bigobject;
 /**
  * action处理类
  * @author 尹涛
  *
  */
public class BigobjectAction extends ActionSupport {
    
    private BigobjectService bs; //业务逻辑层对象
    private List<Bigobject> list; //信息列表
    private Bigobject bj;   //实体对象
    private File upload;  //封装上传文件属性
    private String uploadContenType; //上传文件类型
    private String  uploadFileName; //上传文件名称
    FileOutputStream  fos=null;  //输出流对象
    FileInputStream fis=null;   //文件输入流对象
    //存储图片路径
    String path=ServletActionContext.getServletContext().getRealPath("/img/");
    //获取所有信息
    public String find() throws IOException{
        list=bs.find();  //获取列表信息
        if(list.size()>0){  //判断当前列表是否为空
            for (Bigobject lists : list) {
                try {
                     //将文件输出到WebRoot下img文件夹中
                    fos=new FileOutputStream(path+"\\"+lists.getFilename());
                    fos.write(lists.getTblob());                    
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    fos.close();
                }
            }            
        }
        return "doIndex";
   }
   //添加信息
  public String toAdd() throws IOException{
      
    try {
        bj=new Bigobject();
         //读取文件
        fis=new FileInputStream(upload);
        //保存文件,并设置保存路径 
        fos=new FileOutputStream(path+"\\"+this.uploadFileName); 
        //存储二进制文件的字节码
        byte [] buf=new byte[fis.available()];
         //获取读取到的文件的字节大小
         int length=fis.read(buf); 
         while (length>0) {
            fos.write(buf, 0, length);
            length=fis.read(buf);            
        }
        //读入类路径下的file文件的二进制数据
        InputStream in=new FileInputStream(path+"\\"+this.uploadFileName);
        byte[] byteArray=new byte[in.available()];
        in.read(byteArray);
        in.close();     
      bj.setId(7);
      bj.setTblob(byteArray);
      bj.setFilename(uploadFileName);
     int id= bs.addBigobject(bj);
    } catch (FileNotFoundException e) {        
        e.printStackTrace();
    }finally{
        fos.close();
        fis.close();
        
    }
      
      return "doAdd";
  }    
    //以下为 get 和 set方法..
    public BigobjectService getBs() {
        return bs;
    }
    public void setBs(BigobjectService bs) {
        this.bs = bs;
    }
    public List<Bigobject> getList() {
        return list;
    }
    public void setList(List<Bigobject> list) {
        this.list = list;
    }
    public Bigobject getBj() {
        return bj;
    }
    public void setBj(Bigobject bj) {
        this.bj = bj;
    }


    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContenType() {
        return uploadContenType;
    }


    public void setUploadContenType(String uploadContenType) {
        this.uploadContenType = uploadContenType;
    }


    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    
}

要获取blob大对象中中存储的图片首先应该将图片先读取到WebRoot的指定文件夹下然后在显示到页面上

在添加的时候也先将文件上传到WebRoot的指定文件夹下然后在存储到数据库中 这里需要注意的是

web.xml文件中OpenSessionInViewFilter中如果没有配置

<init-param>   
           <param-name>flushMode</param-name>   
           <param-value>AUTO</param-value>   
   </init-param>

或者是 声明式事务配置有问题

则会有可能出现异常

org.springframework.dao.InvalidDataAccessApiUsageException:

Write operations are not allowed in read-only mode (FlushMode.NEVER) turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition;

 

接下来就是web.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts Blank</display-name>
    <!-- 上下文参数 : Spring配置文件存储路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 监听器 :负责初始化spring配置文件/启用spring容器-->
    <listener>
        <!-- 注意:要导入spring-web.xxx.jar文件包 -->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- OpenSessionInViewFilter -->
    <filter>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>        
    </filter>
    <filter-mapping>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>    
    <!-- Struts2核心控制器 -->
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>  
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Spring配置文件

<?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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.1.xsd
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
     ">

   <!--配置数据源  -->
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
      <property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
      <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
      <property name="username" value="scott"></property>
      <property name="password" value="bdqn"></property>
   </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
         <!-- 添加hibernate配置参数 -->
        <!--  <property name="hibernateProperties">
            <props>
             <prop key="hibernate.show_sql">true</prop>
             <prop key="hibernate.format_sql">true</prop>
           </props>
         </property> -->
        <!--添加对象关系映射文件信息  -->
        <property name="mappingDirectoryLocations">
         <list>
          <value>classpath:entity/</value>
         </list>
        </property>
    </bean>
    <!--配置事务管理器 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 通过tx标签定义事务管理增强,并指定事务管理器 -->
     <tx:advice id="txAdvice" transaction-manager="txManager">
      <tx:attributes>
        <tx:method name="get*" read-only="true"/>
        <tx:method name="select*" read-only="true"/>
        <tx:method name="add*" propagation="REQUIRED"/>
        <tx:method name="update*" propagation="REQUIRED"/>
        <tx:method name="delete*" propagation="REQUIRED"/>
        <tx:method name="*" propagation="REQUIRED" read-only="true"/>
      </tx:attributes>
     </tx:advice>
     <!-- 定义切面 -->
     <aop:config>
       <!-- 切入点 -->
       <aop:pointcut expression="execution(* service.impl.*.*(..))" id="pointcut"/>
       <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
     </aop:config>
    <!-- dao层 -->
    <bean id="bigobjectDao" class="dao.impl.BigobjectDaoImpl" p:sessionFactory-ref="sessionFactory">    </bean>
    <!--service  -->
    <bean id="bigobjectService" class="service.impl.BigobjectServiceImpl" p:bd-ref="bigobjectDao"></bean>
    <!-- action -->
    <bean id="bigobjectAction" class="action.BigobjectAction" p:bs-ref="bigobjectService" scope="prototype"></bean>
    </beans>

struts2配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">
     <action name="big_*" class="bigobjectAction" method="{1}">
      <result name="doIndex">index.jsp</result>
       <result name="doAdd" type="redirectAction">big_find</result>
     </action>
    </package>

</struts>

添加信息的jsp页面 这里也需要注意的是 form表单提交的方式 一定要设置为多部分提交

 

 <body>
      <form action="big_toAdd" method="post" enctype="multipart/form-data">
                请选择文件:<input type="file" name="upload">
        <input type="submit" value="添加">            
      </form>
  </body>

一个简单的使用SSH操作Oracle数据库BLOB大对象图片上传 及显示就实现了

如果不是SSH框架组合需要注意的是要导入两个jar文件

commons-fileupload-1.2.2.jar

commons-io-2.4.jar

转载于:https://www.cnblogs.com/AnotherEon001/p/6917147.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值