mybatis CLOB/BLOBタイプデータの処理
8274 ワード
BLOBもCLOBも大きなフィールドタイプです.
BLOBはバイナリで保存され、CLOBは文字を直接保存することができます.
通常、画像、ファイル、音楽などの情報はBLOBフィールドで格納され、ファイルをバイナリに変換して格納されます.文章や長い文字はCLOBで保存する.
BLOBとCLOBは、データベースによって対応するタイプが異なります.MySQLではclobがtext/longtext、blobがblob Oracleではclobがclob、blobがblob MyBatisに対応してCLOB/BLOBタイプ列のマッピング処理がサポートされています.
テーブル文:
写真(pic)は、PNG、JPG、または他のフォーマットであってもよい.プロフィール情報(bio)は、比較的長い文字記述を学ぶことができる.デフォルトでは、MyBatisはCLOBタイプのカラムをjavaにマッピングします.lang.Stringタイプで、BLOB列をbyte[]タイプにマッピングします.
ファイルのマッピング:
マッピングインタフェース:
テスト方法:
次のgetUserPic()メソッドはCLOBタイプのデータをStringタイプに読み込み、BLOBタイプのデータをbyte[]プロパティに読み込みます.
BLOBはバイナリで保存され、CLOBは文字を直接保存することができます.
通常、画像、ファイル、音楽などの情報はBLOBフィールドで格納され、ファイルをバイナリに変換して格納されます.文章や長い文字はCLOBで保存する.
BLOBとCLOBは、データベースによって対応するタイプが異なります.MySQLではclobがtext/longtext、blobがblob Oracleではclobがclob、blobがblob MyBatisに対応してCLOB/BLOBタイプ列のマッピング処理がサポートされています.
テーブル文:
create table user_pics(
id number primary key,
name varchar2(50) ,
pic blob,
bio clob
);
写真(pic)は、PNG、JPG、または他のフォーマットであってもよい.プロフィール情報(bio)は、比較的長い文字記述を学ぶことができる.デフォルトでは、MyBatisはCLOBタイプのカラムをjavaにマッピングします.lang.Stringタイプで、BLOB列をbyte[]タイプにマッピングします.
public class UserPic{
private int id;
private String name;
private byte[] pic;
private String bio;
//setters & getters
}
ファイルのマッピング:
<insert id="insertUserPic" parameterType="UserPic">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select my_seq.nextval from dual
selectKey>
insert into user_pics(id,name, pic,bio)
values(#{id},#{name},#{pic},#{bio})
insert>
<select id="getUserPicById" parameterType="int" resultType="UserPic">
select * from user_pics where id=#{id}
select>
マッピングインタフェース:
public interface PicMapper {
int insertUserPic(UserPic userPic);
UserPic getUserPicById(int id);
}
テスト方法:
public void test_insertUserPic(){
String name = "tom";
String bio = " ";
byte[] pic = null;
try {
//
File file = new File("src/com/briup/special/1.gif");
InputStream is = new FileInputStream(file);
pic = new byte[is.available()];
is.read(pic);
is.close();
} catch (Exception e){
e.printStackTrace();
}
//
UserPic userPic = new UserPic(name, pic , bio);
SqlSession sqlSession = null;
try{
sqlSession = MyBatisSqlSessionFactory.openSession();
SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class);
mapper.insertUserPic(userPic);
sqlSession.commit();
}catch (Exception e) {
e.printStackTrace();
}
}
次のgetUserPic()メソッドはCLOBタイプのデータをStringタイプに読み込み、BLOBタイプのデータをbyte[]プロパティに読み込みます.
@Test
public void test_getUserPicById(){
SqlSession sqlSession = null;
try {
sqlSession = MyBatisSqlSessionFactory.openSession();
SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class);
UserPic userPic = mapper.getUserPicById(59);
System.out.println(userPic.getId());
System.out.println(userPic.getName());
System.out.println(userPic.getBio());
System.out.println(userPic.getPic().length);
} catch (Exception e) {
e.printStackTrace();
}
}