MyBatisによる画像データの格納と読み取り

3304 ワード

開発環境:
Mybatis:3.0.5
MySQL:5.x
 
1.データベースScheme
--
-- Table structure for table `user_graphic_t`
--

DROP TABLE IF EXISTS `user_graphic_t`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_graphic_t` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `graphic_data` blob,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=360 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

2.Mapperファイル
<resultMap id="userGraphicMap" type="userGraphicVo">
		<id column="id" property="id" jdbcType="DECIMAL" />
		<result column="graphic_data" property="graphicData" jdbcType="BLOB" />



</resultMap>

<sql id="resultColumn">
		id,graphic_data
</sql>
	
<insert id="insertUserGraphic" parameterType="userGraphicVo">
		INSERT INTO user_graphic_t (
		<include refid="resultColumn" />
		)
		values (
		#{id},,#{graphicData}
		)
</insert>
	
<select id="selectUserGraphic" parameterType="java.lang.Long" resultMap="userGraphicMap">
		SELECT
		<include refid="resultColumn" />
		from user_graphic_t WHERE
		id=#{id} 
		order by id desc
</select>

3.マッピングVO:
public class UserGraphicVo {

	private Long id;
	
	private byte[] graphicData;

       //get/set  
}

4.DAO層呼び出し
public void addUserGraphic(UserGraphicVo userGraphicVo) {
		getSqlSessionTemplate().insert("userGraphicVo.insertUserGraphic",  userGraphicVo);
}

5.JSPページ展示画像
<img src="${ctxPath}/apps/showImage.action?id=${userGraphic.id}" />

 6. アクション処理
public void showReportImage() {
                response.setContentType("image/jpeg");

                if (!"".equals(id)) {
			List<UserGraphicVo> list = userGraphicService.findUserGraphicVoById(id);
			if(null != list && !list.isEmpty()){
				OutputStream os = null;
				try {
					os = response.getOutputStream();
					os.write(list.get(0).getGraphicData());
					os.flush();
				} catch (IOException e) {
					Log.info("      !" + e.getMessage());
				} finally {
					if(null != os){
						try {
							os.close();
						} catch (IOException e) {
							Log.info("         !" + e.getMessage());
						}
					}
				}				
			}
		}
	}

7.参考資料
    http://springsfeng.iteye.com/blog/1630672
    http://blog.csdn.net/pzhtpf/article/details/7400606
    http://springsfeng.iteye.com/admin/blogs/1630698
    http://hi.baidu.com/dcjob/blog/item/cd0cb809d8e43e3ce824886a.html