本地图片利用Hibernate存mysql

入口测试
import com.mobileares.dolphin.dao.ActivityDao;
import com.mobileares.dolphin.dao.CommodityDao;
import com.mobileares.dolphin.dao.UserDao;
import com.mobileares.dolphin.model.*;
import com.mobileares.dolphin.service.*;
import org.hibernate.Hibernate;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import java.io.*;

    @Test
    @Rollback(false)
    public void addAllImage() throws Exception{
        File f = new File("d://image/");
        File[] fs = f.listFiles();
        for(int i=0;i<fs.length;i++){
            File f1 = fs[i];
            String filename = f1.getName();
            String iconId = filename.substring(0,filename.indexOf("."));
            Resource resource = new Resource();
            try {
                FileInputStream inStream = new FileInputStream(f1);
                byte[] fileBytes = new byte[inStream.available()];
                inStream.read(fileBytes, 0, inStream.available());
                resource.setBody(Hibernate.createBlob(fileBytes));
                System.out.print(fileBytes.toString());
//                resource.setName(f1.getName());
                Long resourceId =  rm.saveResource(resource);
                commodityDao.updateAddTestData(iconId,resourceId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

DAO
    public void updateAddTestData(final String providerId,final Long iconId) {
        this.getHibernateTemplate().execute(new HibernateCallback(){
            public String doInHibernate(Session session) throws HibernateException,SQLException{
                String hql = "update Commodity com set com.iconId=:id where com.providerId=:id1";
                Query q = session.createQuery(hql).setLong("id",iconId).setString("id1",providerId);
                return q.executeUpdate()>0?"1":"0";
            }
        });
    }

model
public class Resource implements Serializable {
    
    private Long id;
    private String name;
    private String mimeType = "MIME";
    private Blob body;
    private Long actId;
    private String qrPassword;
}

废话没了!备份用

猜你喜欢

转载自zcw-java.iteye.com/blog/1596832