首先说写入oracle的Blob字段
上一文章的实现方法没有贴出来,如下:
TempUserService.java
package org.hd.tempuser.service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.hd.tempuser.model.TempUser;
import org.rd.framework.query.support.PaginationSupport;
public interface TempUserService {
public static final String BEAN_ID = "tempUserService";
public List getTempUserList(Map queryParams,PaginationSupport paginationSupport);
public TempUser getTempUserById(String tempuserid);
public void delTempUserById(String tempuserid);
public TempUser addTempUser(TempUser tempUser);
public void editTempUser(TempUser tempUser);
public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum);
public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum);
public void editTempUserWithoutBlob(TempUser tempUser,String loginUserJobNum);
public void clearPhotoBlob(TempUser tempUser);
}
TempUserServiceImpl.java
package org.hd.tempuser.service.impl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.List;
import java.util.Map;
import oracle.sql.BLOB;
import org.hd.tempuser.model.TempUser;
import org.hd.tempuser.service.TempUserService;
import org.hd.util.BlobUtil;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.lob.SerializableBlob;
import org.rd.framework.common.container.ContainerManager;
import org.rd.framework.dao.impl.CommonServiceImpl;
import org.rd.framework.keygen.IKeyGen;
import org.rd.framework.query.support.PaginationSupport;
import org.rd.framework.util.WebUtils;
public class TempUserServiceImpl extends CommonServiceImpl implements TempUserService{
@Override
public List getTempUserList(Map queryParams,
PaginationSupport paginationSupport) {
String qualificationString = WebUtils.getQualificationString(queryParams);
String queryString = "select queryby from TempUser queryby" + qualificationString;
String countString = "select count(queryby.hduid) from TempUser queryby" + qualificationString;
paginationSupport.setTotalCount(count(countString));
return find(queryString, paginationSupport);
}
public TempUser getTempUserById(String tempuserid){
TempUser tempUser=null;
String queryString = "select queryby from TempUser queryby where queryby.hduid='"
+ tempuserid.trim()+"'";
List list=find(queryString);
if(list.size()>0){
tempUser=(TempUser)list.get(0);
}
return tempUser;
}
public void delTempUserById(String tempuserid){
TempUser tempUser=null;
String queryString = "delete from hd_user queryby where queryby.hduid='"
+ tempuserid.trim()+"'";
if(tempuserid==null||tempuserid.equals("")){
}else{
createNativeSQL(queryString);
}
}
public TempUser addTempUser(TempUser tempUser){
IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
.getComponent(IKeyGen.BEAN_ID);
String Id = keyService.getUUIDKey();
tempUser.setHduid(Id);
//默认字段
// tempUser.setCreate_date(new Date());
// tempUser.setCreator(creator)
create(tempUser);
return tempUser;
}
public void editTempUser(TempUser tempUser){
this.update(tempUser);
}
//此方法作废
public void addTempUserTt(TempUser tempUser,Blob hbblob,String pathh){
String serverLocalPath=BlobUtil.WEBCONTENT_PATH+pathh.replaceAll("/", "\\\\");
IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
.getComponent(IKeyGen.BEAN_ID);
String Id = keyService.getUUIDKey();
tempUser.setHduid(Id);
Session s = null;
byte[] buffer = new byte[1];
buffer[0] = 1;
try {
s = this.getSessionFactory().openSession();
Transaction tx = s.beginTransaction();
s.save(tempUser);
s.flush();
s.refresh(tempUser, LockMode.UPGRADE);
BLOB blob = (BLOB)hbblob;
OutputStream out = blob.getBinaryOutputStream();
// String fileName = "oraclejdbc.jar";
File f = new File(serverLocalPath);
FileInputStream fin = new FileInputStream(f);
int count = -1, total = 0;
byte[] data = new byte[(int)fin.available()];
fin.read(data);
out.write(data);
fin.close();
out.close();
s.flush();
tx.commit();
} catch (Exception e){
System.out.println(e.getMessage());
} finally {
if (s != null);
try {
s.close();;
} catch (Exception e) {}
}
}
//此方法作废
public void addTempUserTtdd(TempUser tempUser,Blob hbblob,String pathh) throws SQLException, IOException, FileNotFoundException{
String serverLocalPath=BlobUtil.WEBCONTENT_PATH+pathh.replaceAll("/", "\\\\");
IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
.getComponent(IKeyGen.BEAN_ID);
String Id = keyService.getUUIDKey();
tempUser.setHduid(Id);
//得到数据库连接(驱动包是weblogic的,没有下载任何新版本)
Connection con=null;
ResultSet rs=null;
InputStream in=null;
BufferedInputStream bis=null;
OutputStream os=null;
BufferedOutputStream bos=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@10.23.117.149:1521:direct", "helpdesk", "helpdesk");
//处理事务
con.setAutoCommit(false);
Statement st = con.createStatement();
// //插入一个空对象
// st.executeUpdate("insert into BLOBIMG values(103,empty_blob())");
String upsql="insert into hd_user(hduid,picture) values('"+Id+"',empty_blob())";
st.executeQuery(upsql);
//用for update方式锁定数据行
String sql="select picture from hd_user where hduid='"+tempUser.getHduid()+"' for update";
rs = st.executeQuery(sql);
System.out.println(sql);
// if (rs.next()) {
//得到java.sql.Blob对象,然后Cast为oracle.sql.BLOB
System.out.println(rs.getFetchSize());
rs.next();
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
//到数据库的输出流
os = blob.getBinaryOutputStream();
bos=new BufferedOutputStream(os);
//这里用一个文件模拟输入流
File file = new File(serverLocalPath);
in = new FileInputStream(file);
bis=new BufferedInputStream(new FileInputStream(file));
//将输入流写到输出流
byte[] b = new byte[1024*1024];
int len = 0;
while (-1!=(len=bis.read(b, 0, b.length))) {
bos.write(b, 0, len);
}
// }
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(os!=null){
// os.flush();
os.close();
}
if(bos!=null){
// bos.flush();
bos.close();
}
if(in!=null){
in.close();
}
if(bis!=null){
bis.close();
}
if(con!=null){
con.commit();
con.close();
}
}
}
/**
* 增加用户,把照片从临时的上传目录下写入数据库Blob
*/
public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
.getComponent(IKeyGen.BEAN_ID);
String Id = keyService.getUUIDKey();
tempUser.setHduid(Id);
//默认字段
tempUser.setCreate_date(new Date());
tempUser.setCreator(loginUserJobNum);
try {
tempUser.setPicture(BLOB.empty_lob());
} catch (SQLException e2) {
e2.printStackTrace();
}
Session s=this.getSessionFactory().openSession();
Transaction t = s.beginTransaction();
s.save(tempUser);
s.flush();
s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
try{
File uploadFile=new File(serverLocalPath);
FileInputStream fis = new FileInputStream(uploadFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n=fis.read(b)) != -1) {
out.write(b,0,n);
}
fis.close();
out.close();
byte[] content = out.toByteArray();
tempUser.setPicture(Hibernate.createBlob(content));
s.flush();
t.commit();
s.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 编辑用户,把照片从临时的上传目录下写入数据库Blob
*/
public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
//默认字段
tempUser.setCreate_date(new Date());
tempUser.setCreator(loginUserJobNum);
try {
tempUser.setPicture(BLOB.empty_lob());
} catch (SQLException e2) {
e2.printStackTrace();
}
// String nasql="update hd_user g set g.picture=null " +
// " where g.hduid='"+tempUser.getHduid().trim()+"' ";
// this.createNativeSQL(nasql);
Session s=this.getSessionFactory().openSession();
Transaction t = s.beginTransaction();
tempUser.setPicture(Hibernate.createBlob(new byte[1]));
s.saveOrUpdate(tempUser);
s.flush();
s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
try{
File uploadFile=new File(serverLocalPath);
FileInputStream fis = new FileInputStream(uploadFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n=fis.read(b)) != -1) {
out.write(b,0,n);
}
fis.close();
out.close();
byte[] content = out.toByteArray();
tempUser.setPicture(Hibernate.createBlob(content));
s.flush();
t.commit();
s.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void clearPhotoBlob(TempUser tempUser){
String nasql="update hd_user g set g.picture=null " +
" where g.hduid='"+tempUser.getHduid().trim()+"' ";
this.createNativeSQL(nasql);
}
/**
* 编辑用户,不修改照片
*/
public void editTempUserWithoutBlob(TempUser tempUser,String loginUserJobNum) {
/*
update hd_user t
set t.uname='q',
t.upass='q',
t.realname='娜美',
t.sex='女',
t.email='tt@kdk.com',
t.cellphone='45345345',
t.ext='123',
t.phone='321',
t.job_level='坐席',
t.edit_date=sysdate,
t.editor='suolong',
t.remark='editsuccess'
where t.hduid='F15E73BD0A18084A01AFB22A54946F6F'
*/
String hduid=tempUser.getHduid();
if(hduid==null||hduid.trim().equals("")){
}else{
hduid=hduid.trim();
String sql=" update hd_user t " +
" set t.uname='"+tempUser.getUname().trim()+"', " +
" t.upass='"+tempUser.getUpass().trim()+"', " +
" t.realname='"+tempUser.getRealname()+"', " +
" t.sex='"+tempUser.getSex().trim()+"', " +
" t.email='"+tempUser.getEmail()+"', " +
" t.cellphone='"+tempUser.getCellphone()+"', " +
" t.ext='"+tempUser.getExt()+"', " +
" t.phone='"+tempUser.getPhone()+"', " +
" t.job_level='"+tempUser.getJob_level()+"', " +
" t.edit_date=sysdate, " +
" t.editor='"+loginUserJobNum+"', " +
" t.remark='"+tempUser.getRemark()+"' " +
" where t.hduid='"+hduid+"' ";
this.createNativeSQL(sql);
}
}
}
BlobUtil.java
package org.hd.util;
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.sql.Blob;
import java.sql.SQLException;
import org.hibernate.Hibernate;
public class BlobUtil {
public static String WEBCONTENT_PATH="";
public static String BASE_PATH="";
public static String ODSUSER_PHOTO_PATH="";//ods用户头像目录
public static String TEMPUSER_PHOTO_PATH="";//临时长期用户头像目录
public static String TEMP_UPLOAD_PATH="";//上传时的临时目录
public static String DirTypeTempupload="tempupload";
public static String DirTypeOdsuser="odsuser";
public static String DirTypeTempuser="tempuser";
static{
String clapath=BlobUtil.class.getResource("/").getPath();
File claFile=new File(clapath);
String basePath=claFile.getParentFile().getParentFile().getPath();
WEBCONTENT_PATH=basePath;
BASE_PATH=basePath+"\\tempphoto";
File baseFile=new File(BASE_PATH);
if(!baseFile.exists()){
baseFile.mkdir();
}
ODSUSER_PHOTO_PATH=BASE_PATH+"\\odsuser";
TEMPUSER_PHOTO_PATH=BASE_PATH+"\\tempuser";
TEMP_UPLOAD_PATH=BASE_PATH+"\\tempupload";
File odsFile=new File(ODSUSER_PHOTO_PATH);
File tempFile=new File(TEMPUSER_PHOTO_PATH);
File tempUpload=new File(TEMP_UPLOAD_PATH);
if(!odsFile.exists()){
odsFile.mkdir();
}
if(!tempFile.exists()){
tempFile.mkdir();
}
if(!tempUpload.exists()){
tempUpload.mkdir();
}
System.out.println(odsFile.getPath()+"---"+odsFile.exists());
System.out.println(tempFile.getPath()+"---"+tempFile.exists());
System.out.println(tempUpload.getPath()+"---"+tempUpload.exists());
}
public static String makeLocalPhoto(Blob blob,String tergetDirName,boolean isTempUser){
String relativepath="";
tergetDirName=tergetDirName.trim();
if(blob==null){
System.out.println("无法读取图片信息!");
}else{
if(tergetDirName==null||tergetDirName.trim().equals("")){
System.out.println("无法获取工号创建目录!");
}else{
if(isTempUser){//临时长期用户
File tempFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+tergetDirName);
if(!tempFile.exists()){
tempFile.mkdir();
}
boolean falg=blobToPhoto(blob,tempFile,tergetDirName);
if(falg){
relativepath="/tempphoto/tempuser/"+tergetDirName+"/"+tergetDirName+".jpg";
}else{
}
}else{//ods用户
File odsFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+tergetDirName);
if(!odsFile.exists()){
odsFile.mkdir();
}
boolean falg=blobToPhoto(blob,odsFile,tergetDirName);
if(falg){
relativepath="/tempphoto/odsuser/"+tergetDirName+"/"+tergetDirName+".jpg";
}else{
}
}
}
}//end else
return relativepath;
}
public static boolean blobToPhoto(Blob blob,File tergetDirFile,String tergetDirName){
String photoPath=tergetDirFile.getPath().trim();
boolean issuccess=true;
if(!tergetDirFile.exists()){
System.out.println("目标路径不存在"+tergetDirFile.getPath());
issuccess=false;
}else if(!tergetDirFile.isDirectory()){
System.out.println("目标路径不是目录"+tergetDirFile.getPath());
issuccess=false;
}else{
File photo=new File(photoPath+"\\"+tergetDirName.trim()+".jpg");
FileOutputStream fos = null;
InputStream is = null;
byte[] Buffer = new byte[4096];
try {
is=blob.getBinaryStream();
fos=new FileOutputStream(photo);
int size = 0;
while ((size = is.read(Buffer)) != -1) {
fos.write(Buffer, 0, size);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}//end else
return issuccess;
}
public static Blob photoToBlob(String filePath){
Blob blob=null;
FileInputStream fis = null;
String serverLocalPath=BlobUtil.WEBCONTENT_PATH+filePath.replaceAll("/", "\\\\");
System.out.println("serverLocalPath::"+serverLocalPath);
File file=new File(serverLocalPath);
try {
fis=new FileInputStream(file);
blob=Hibernate.createBlob(fis);
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return blob;
}
public static String getUploadTempPhotoUrl(String photoUrl,String jobNumber){
String webUrl="";
String toUrl="";
File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
if(!tempUploadFile.exists()){
tempUploadFile.mkdir();
}
boolean falg=BlobUtil.isRightFileSuffix(photoUrl);
if(falg){
toUrl=BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber+"\\"+jobNumber+BlobUtil.getFileSuffix(photoUrl);
BlobUtil.copyFile(photoUrl, toUrl);
webUrl="/tempphoto/tempupload/"+jobNumber+"/"+jobNumber+BlobUtil.getFileSuffix(photoUrl);
}else{
}
return webUrl;
}
//得到文件url文件的后缀
public static String getFileSuffix(String fileUrl){
String res="";
int a=fileUrl.lastIndexOf(".");
if(a>0){
res=fileUrl.substring(a);
}
return res;
}
public static boolean isRightFileSuffix(String fileUrl){
boolean flag=false;
int a=fileUrl.lastIndexOf(".");
if(a>0){
flag=true;
}
return flag;
}
public static void copyFile(String fromUrl,String toUrl){
File fromFile=new File(fromUrl);
File toFile=new File(toUrl);
if(toFile.exists()){
toFile.delete();
}
FileOutputStream fos = null;
FileInputStream fis = null;
byte[] Buffer = new byte[4096];
try {
fis=new FileInputStream(fromFile);
fos=new FileOutputStream(toFile);
int size = 0;
while ((size = fis.read(Buffer)) != -1) {
fos.write(Buffer, 0, size);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String makeDirByParamForOds(String jobNumberold,String type){
String jobNumber=jobNumberold.trim();
String rePath="";
if(jobNumber==null||jobNumber.trim().equals("")){
}else{
if(type==BlobUtil.DirTypeTempupload){
File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
if(!tempUploadFile.exists()){
tempUploadFile.mkdir();
}
rePath="/tempupload/"+jobNumber+"/"+jobNumber;
}else if(type==BlobUtil.DirTypeOdsuser){
File tempUploadFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+jobNumber);
if(!tempUploadFile.exists()){
tempUploadFile.mkdir();
}
rePath="/odsuser/"+jobNumber+"/"+jobNumber;
}else if(type==BlobUtil.DirTypeTempuser){
File tempUploadFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+jobNumber);
if(!tempUploadFile.exists()){
tempUploadFile.mkdir();
}
rePath="/tempuser/"+jobNumber+"/"+jobNumber;
}
}
return rePath;
}
public static String makeDirByParamForOdsRealPath(String jobNumberold,String type){
String jobNumber=jobNumberold.trim();
String rePath="";
if(jobNumber==null||jobNumber.trim().equals("")){
}else{
if(type==BlobUtil.DirTypeTempupload){
File tempUploadFile=new File(BlobUtil.TEMP_UPLOAD_PATH+"\\"+jobNumber);
if(!tempUploadFile.exists()){
tempUploadFile.mkdir();
}
rePath="\\\\tempupload\\\\"+jobNumber+"\\\\"+jobNumber;
}else if(type==BlobUtil.DirTypeOdsuser){
File tempUploadFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+jobNumber);
if(!tempUploadFile.exists()){
tempUploadFile.mkdir();
}
rePath="\\\\odsuser\\\\"+jobNumber+"\\\\"+jobNumber;
}else if(type==BlobUtil.DirTypeTempuser){
File tempUploadFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+jobNumber);
if(!tempUploadFile.exists()){
tempUploadFile.mkdir();
}
rePath="\\\\tempuser\\\\"+jobNumber+"\\\\"+jobNumber;
}
}
return rePath;
}
public static String changeFileName(String fullold,String filename,String newname){
String res="";
String a=filename.substring(0,filename.lastIndexOf("."));
String b=BlobUtil.getFileSuffix(filename);
res=fullold.replaceAll(filename, newname+b);
return res;
}
public static void main(String[] ss){
String serverLocalPath=BlobUtil.BASE_PATH+"/gg/gg.jpg".replaceAll("/", "\\\\");
System.out.println("BASE_PATH::"+BlobUtil.BASE_PATH);
System.out.println("WEBCONTENT_PATH::"+BlobUtil.WEBCONTENT_PATH);
System.out.println("TEMP_UPLOAD_PATH::"+BlobUtil.TEMP_UPLOAD_PATH);
System.out.println("ODSUSER_PHOTO_PATH::"+BlobUtil.ODSUSER_PHOTO_PATH);
System.out.println("TEMPUSER_PHOTO_PATH::"+BlobUtil.TEMPUSER_PHOTO_PATH);
String aa="sfs.333.jpgg";
System.out.println(aa.substring(0,aa.lastIndexOf(".")));
System.out.println(BlobUtil.changeFileName("as/asd/3.jpg","3.jpg","nn"));
/*
BASE_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto
WEBCONTENT_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent
TEMP_UPLOAD_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\tempupload
ODSUSER_PHOTO_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\odsuser
TEMPUSER_PHOTO_PATH::D:\HelpDeskProject\helpdesk-workSpace\HelpDesk\WebContent\tempphoto\tempuser
*/
}
}
TempUser.java
package org.hd.tempuser.model;
import java.util.Date;
import java.sql.Blob;
public class TempUser {
//import oracle.sql.BLOB;
private String hduid;
private String uname;
private String upass;
private String realname;
private String sex;
private String email;
private String utype;
private String cellphone;
private String ext;
private String phone;
private String job_level;
private String valid;
private Blob picture;
private Date create_date;
private String creator;
private Date edit_date;
private String editor;
private String remark;
//虚拟字段
private String tempUrl;//照片url
private String vjob_level;//职级
public String getHduid() {
return hduid;
}
public void setHduid(String hduid) {
this.hduid = hduid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUtype() {
return utype;
}
public void setUtype(String utype) {
this.utype = utype;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getJob_level() {
return job_level;
}
public void setJob_level(String job_level) {
this.job_level = job_level;
}
public String getValid() {
return valid;
}
public void setValid(String valid) {
this.valid = valid;
}
public Blob getPicture() {
return picture;
}
public void setPicture(Blob picture) {
this.picture = picture;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getEdit_date() {
return edit_date;
}
public void setEdit_date(Date edit_date) {
this.edit_date = edit_date;
}
public String getEditor() {
return editor;
}
public void setEditor(String editor) {
this.editor = editor;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getTempUrl() {
return tempUrl;
}
public void setTempUrl(String tempUrl) {
this.tempUrl = tempUrl;
}
public String getVjob_level() {
return vjob_level;
}
public void setVjob_level(String vjob_level) {
this.vjob_level = vjob_level;
}
}
TempUser.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.hd.tempuser.model.TempUser" table="hd_user">
<id name="hduid" type="java.lang.String">
<column name="hduid" length="32" />
<generator class="assigned" />
</id>
<property name="uname" type="java.lang.String">
<column name="uname" length="50">
</column>
</property>
<property name="upass" type="java.lang.String">
<column name="upass" length="100" />
</property>
<property name="realname" type="java.lang.String">
<column name="realname" length="50">
</column>
</property>
<property name="sex" type="java.lang.String">
<column name="sex" length="50" />
</property>
<property name="email" type="java.lang.String">
<column name="email" length="100">
</column>
</property>
<property name="utype" type="java.lang.String">
<column name="utype" length="10" />
</property>
<property name="cellphone" type="java.lang.String">
<column name="cellphone" length="50">
</column>
</property>
<property name="ext" type="java.lang.String">
<column name="ext" length="50" />
</property>
<property name="phone" type="java.lang.String">
<column name="phone" length="50" />
</property>
<property name="job_level" type="java.lang.String">
<column name="job_level" length="50" />
</property>
<property name="valid" type="java.lang.String">
<column name="valid" length="10" />
</property>
<property name="picture" type="java.sql.Blob">
<column name="picture" />
</property>
<property name="create_date" type="java.util.Date">
<column name="create_date" />
</property>
<property name="creator" type="java.lang.String">
<column name="creator" length="32" />
</property>
<property name="edit_date" type="java.util.Date">
<column name="edit_date" />
</property>
<property name="editor" type="java.lang.String">
<column name="editor" length="32" />
</property>
<property name="remark" type="java.lang.String">
<column name="remark" length="200" />
</property>
</class>
</hibernate-mapping>
picture是Blob字段(照片)
从上面的代码中说说核心代码;
写入Blob。
在新增时,picture首先需要赋值一个空的值,这个空值不是null !!!而是BLOB.empty_lob()或者Hibernate.createBlob(new byte[1])
这样才算是符合Blob类型。
session需要改变更新模式s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
即for update.
这是才可以写入,二写入的内容是byte[]类型!
/**
* 增加用户,把照片从临时的上传目录下写入数据库Blob
*/
public void addTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
IKeyGen keyService = (IKeyGen) (IKeyGen) ContainerManager
.getComponent(IKeyGen.BEAN_ID);
String Id = keyService.getUUIDKey();
tempUser.setHduid(Id);
//默认字段
tempUser.setCreate_date(new Date());
tempUser.setCreator(loginUserJobNum);
try {
tempUser.setPicture(BLOB.empty_lob());
} catch (SQLException e2) {
e2.printStackTrace();
}
Session s=this.getSessionFactory().openSession();
Transaction t = s.beginTransaction();
s.save(tempUser);
s.flush();
s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
try{
File uploadFile=new File(serverLocalPath);
FileInputStream fis = new FileInputStream(uploadFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n=fis.read(b)) != -1) {
out.write(b,0,n);
}
fis.close();
out.close();
byte[] content = out.toByteArray();
tempUser.setPicture(Hibernate.createBlob(content));
s.flush();
t.commit();
s.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
编辑用户时,需要先把数据库的Blob字段置空null,然后再更新(不知有没有其他直接更新的方法)
所以在action我先tempUserService.clearPhotoBlob(getEditTempUser());
public void clearPhotoBlob(TempUser tempUser){
String nasql="update hd_user g set g.picture=null " +
" where g.hduid='"+tempUser.getHduid().trim()+"' ";
this.createNativeSQL(nasql);
}
然后再更新blob,
tempUserService.editTempUserWriteBlob(getEditTempUser(),
getLocalPhotoUrl(), loginUserJobNum);
/**
* 编辑用户,把照片从临时的上传目录下写入数据库Blob
*/
public void editTempUserWriteBlob(TempUser tempUser,String url,String loginUserJobNum) {
String serverLocalPath=BlobUtil.WEBCONTENT_PATH+url.replaceAll("/", "\\\\");
//默认字段
tempUser.setCreate_date(new Date());
tempUser.setCreator(loginUserJobNum);
try {
tempUser.setPicture(BLOB.empty_lob());
} catch (SQLException e2) {
e2.printStackTrace();
}
// String nasql="update hd_user g set g.picture=null " +
// " where g.hduid='"+tempUser.getHduid().trim()+"' ";
// this.createNativeSQL(nasql);
Session s=this.getSessionFactory().openSession();
Transaction t = s.beginTransaction();
tempUser.setPicture(Hibernate.createBlob(new byte[1]));
s.saveOrUpdate(tempUser);
s.flush();
s.refresh(tempUser,LockMode.UPGRADE); //锁定为更新模式
try{
File uploadFile=new File(serverLocalPath);
FileInputStream fis = new FileInputStream(uploadFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n=fis.read(b)) != -1) {
out.write(b,0,n);
}
fis.close();
out.close();
byte[] content = out.toByteArray();
tempUser.setPicture(Hibernate.createBlob(content));
s.flush();
t.commit();
s.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
至于读取Blob,你只需要先读取出来放到服务器下某个路径,然后返回这个路径用于页面展示。
例如,在查看用户信息的时候,需要展示照片。
//读取TempUser照片信息
public String getTempPhoto(TempUser tempUser){
String resPath="";
if(tempUser==null){
}else if(tempUser.getPicture()==null){
}else{
Blob blob=(Blob)tempUser.getPicture();
resPath=BlobUtil.makeLocalPhoto(blob, tempUser.getUname(), true);
}//end else
return resPath;
}
其中
public static String makeLocalPhoto(Blob blob,String tergetDirName,boolean isTempUser){
String relativepath="";
tergetDirName=tergetDirName.trim();
if(blob==null){
System.out.println("无法读取图片信息!");
}else{
if(tergetDirName==null||tergetDirName.trim().equals("")){
System.out.println("无法获取工号创建目录!");
}else{
if(isTempUser){//临时长期用户
File tempFile=new File(BlobUtil.TEMPUSER_PHOTO_PATH+"\\"+tergetDirName);
if(!tempFile.exists()){
tempFile.mkdir();
}
boolean falg=blobToPhoto(blob,tempFile,tergetDirName);
if(falg){
relativepath="/tempphoto/tempuser/"+tergetDirName+"/"+tergetDirName+".jpg";
}else{
}
}else{//ods用户
File odsFile=new File(BlobUtil.ODSUSER_PHOTO_PATH+"\\"+tergetDirName);
if(!odsFile.exists()){
odsFile.mkdir();
}
boolean falg=blobToPhoto(blob,odsFile,tergetDirName);
if(falg){
relativepath="/tempphoto/odsuser/"+tergetDirName+"/"+tergetDirName+".jpg";
}else{
}
}
}
}//end else
return relativepath;
}
其中
public static boolean blobToPhoto(Blob blob,File tergetDirFile,String tergetDirName){
String photoPath=tergetDirFile.getPath().trim();
boolean issuccess=true;
if(!tergetDirFile.exists()){
System.out.println("目标路径不存在"+tergetDirFile.getPath());
issuccess=false;
}else if(!tergetDirFile.isDirectory()){
System.out.println("目标路径不是目录"+tergetDirFile.getPath());
issuccess=false;
}else{
File photo=new File(photoPath+"\\"+tergetDirName.trim()+".jpg");
FileOutputStream fos = null;
InputStream is = null;
byte[] Buffer = new byte[4096];
try {
is=blob.getBinaryStream();
fos=new FileOutputStream(photo);
int size = 0;
while ((size = is.read(Buffer)) != -1) {
fos.write(Buffer, 0, size);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}//end else
return issuccess;
}
这里读出来的图片都是.jpg格式的,因为后缀我写死了,这里还不完善。
注意:你需要传入已经上传到服务器的文件的地址,这个用个工具类实现BlobUtil.java。
这样管理比较清晰。