[一步是咫尺,一步即天涯]
本文与前文的需求类似,废话不表,开始我们的正文部分吧
准备工作:
a.操作系统 :win7 x64
b.基本软件:MySQL,Mybatis,SQLyog
-------------------------------------------------------------------------------------------------------------------------------------一。插入操作
1.在我们的userinfo数据表中增加一个headpic字段,类型为longblob,如下:
2.我们沿用上文工程,原有内容保持不变,需要修改的地方见下文。
3.在UserInfo中增加属性,如下:
@SuppressWarnings("serial") public class UserInfo implements Serializable { private String userid; private String department; private String position; private String mobile; private String gender; private String email; private byte[] headpic; private String cv; //其他内容请自行补充。 }4.在Mapper文件中,增加如下内容:
<insert id="insertUserInfoByBlob" parameterType="userInfo"> insert into userinfo values(#{userid},#{department},#{position},#{mobile},#{gender},#{email},#{headpic},#{cv}) </insert>
5.在UserInfoDao中,增加对应接口:
int insertUserInfoByBlob(UserInfo ui);
6.新增单元测试方法如下:
@Test public void testInsertBlob() { try { UserInfo ui = new UserInfo("clob2", "3", "clob", "77778888", "0", "[email protected]", "你好"); File file = new File("C://Temp/temp.jpg"); InputStream is = new FileInputStream(file); byte[] headpic = new byte[is.available()]; is.read(headpic); is.close(); ui.setHeadpic(headpic); UserInfoDao userInfo = sqlSession.getMapper(UserInfoDao.class); int re = userInfo.insertUserInfoByBlob(ui); if (re == 1) { System.out.println("success"); } sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } }
</pre><p></p><pre>7.运行单元测试方法,观察数据库变化即可。
【注意】这里如果提示packet超长,请在my.ini文件中修改对应长度,或者新增对应配置,然后重新启动mysql服务即可。
-------------------------------------------------------------------------------------------------------------------------------------二。查询操作。
1.在Mapper中增加查询语句,如下:
<select id="selectUserInfoBlobById" parameterType="String" resultType="userInfo"> select * from userinfo where userid=#{id} </select>2.在UserInfoDao中增加对应接口,如下:
UserInfo selectUserInfoBlobById(String id);3.增加单元测试方法,如下:
@Test public void testSelectBlob() { try { String id = "clob1"; UserInfoDao userInfo = sqlSession.getMapper(UserInfoDao.class); UserInfo re = userInfo.selectUserInfoBlobById(id); byte[] buff=re.getHeadpic(); File file = new File("C://Temp/outpic.jpg"); OutputStream out=new FileOutputStream(file); out.write(buff); out.close(); System.out.println(re); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); } }4.运行单元测试方法,观察输出目标路径中是否正确生成文件即可。
-------------------------------------------------------------------------------------------------------------------------------------
【注意】
1.数据类型为longblob是以二进制流的形式进行存储,因此,该类型也能够存储更多类型文件。【博主亲测可行】
2.与前文类似,实际应用时,大量的文件最好不要存储在数据库中,推荐的做法是:将文件单独的存储在文件系统,数据库中保存路径即可。这样能够使得数据库的单表体积迅速降低,提高CRUD的效率。但是,如果确实存在需要将大文本存储在数据库中,也建议采取分表措施,即主体的其他信息是一张表,文本信息是一张表,再通过主外键等方法确定关联关系即可。上面的例子只是为了说明读写的操作步骤,从设计上,是非常不推荐的。请特别留意。
-------------------------------------------------------------------------------------------------------------------------------------
至此,Mybatis最入门---多媒体文件存储结束