我正在开发一个应用程序,其中我将用户配置文件存储到数据库中,该数据库具有要保存的blob对象。我完成了保存部分,但现在我被检索部分困住了。
我在我的应用程序中使用Spring MVC和Hibernate,下面是我的代码片段
HTML:
<img src="${pageContext.request.contextPath}/profilemanager/image.action?username=<%=username%>" class="avatar img-circle" alt="Avatar">
模型文件:
@Entity
@Table(name="TMP_BLOB")
public class UserDetails {
private String username;
private String email;
private String password;
private CommonsMultipartFile avatar;
public UserDetails() {
super();
// TODO Auto-generated constructor stub
}
public UserDetails(String username, String email, String password,
CommonsMultipartFile avatar) {
super();
this.username = username;
this.email = email;
this.password = password;
this.avatar = avatar;
}
@Id
@Column(name="USERNAME")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name="EMAIL_ID")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name="PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name="AVATAR")
@Lob
public CommonsMultipartFile getAvatar() {
return avatar;
}
public void setAvatar(CommonsMultipartFile avatar) {
this.avatar = avatar;
}
}
控制器文件:
@Controller
public class ProfileManagerController {
private ProfileManagerService profileManagerServices;
@RequestMapping(value="/profilemanager/image.action", method=RequestMethod.GET)
public void showUserImage(@RequestParam("username") String username, HttpServletResponse response, HttpServletRequest request) throws IOException {
List<UserDetails> userAvatar = profileManagerServices.getUserImage(username);
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
response.setHeader("Content-Length", String.valueOf(userAvatar.get(0).getAvatar().getBytes().length));
response.setHeader("Content-Disposition", "attachment; filename=\"" + userAvatar.get(0).getAvatar().getName() + "\"");
response.getOutputStream().write(userAvatar.get(0).getAvatar().getBytes());
response.getOutputStream().close();
}
/**
* DEPENDENCY INJECTION
* @param profileManagerServices
*/
@Autowired
public void setProfileManagerServices(
ProfileManagerService profileManagerServices) {
this.profileManagerServices = profileManagerServices;
}
}
服务档案:
@Service
public class ProfileManagerService {
ProfileManagerDAO profileManagerDAO;
public List<UserDetails> getUserImage(String username) {
// TODO Auto-generated method stub
return profileManagerDAO.getUserAvatar(username);
}
@Autowired
public void setProfileManagerDAO(ProfileManagerDAO profileManagerDAO) {
this.profileManagerDAO = profileManagerDAO;
}
}
DAO文件:
@Repository
public class ProfileManagerDAO implements IProfileManager {
private HibernateTemplate hibernateTemplate;
/**
* @param sessionFactory
*/
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
/**
* @param username
* @return
*/
@SuppressWarnings("unchecked")
public List<UserDetails> getUserAvatar(String username) {
DetachedCriteria criteria = DetachedCriteria.forClass(UserDetails.class);
criteria.add(Restrictions.or(Restrictions.eq("username", username),Restrictions.eq("email", username)));
return hibernateTemplate.findByCriteria(criteria);
}
}
现在当从img:src属性触发服务时,它在DAO文件中提供以下堆栈跟踪,代码返回hibernateTemplate.findByCriteria(criteria);
SEVERE: Servlet.service() for servlet [blob-crud-mvc] in context with path [/Spring-BLOB-CRUD] threw exception [Request processing failed; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause
java.io.FileNotFoundException: D:\spring-tool-suite-3.6.0.RELEASE-e4.4-win32\spring-tool-suite-3.6.0.RELEASE-e4.4-win32\sts-bundle\vfabric-tc-server-developer-2.9.6.RELEASE\base-instance\work\Catalina\localhost\Spring-BLOB-CRUD\upload_71270b64_14d1e55f083__7ff0_00000004.tmp (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at org.apache.commons.fileupload.disk.DiskFileItem.readObject(DiskFileItem.java:709)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1893)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1990)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1915)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at org.hibernate.util.SerializationHelper.doDeserialize(SerializationHelper.java:244)
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:306)
at org.hibernate.type.SerializableToBlobType.fromBytes(SerializableToBlobType.java:91)
at org.hibernate.type.SerializableToBlobType.get(SerializableToBlobType.java:83)
at org.hibernate.type.AbstractLobType.nullSafeGet(AbstractLobType.java:68)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:105)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2267)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1423)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1351)
at org.hibernate.loader.Loader.getRow(Loader.java:1251)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:619)
at org.hibernate.loader.Loader.doQuery(Loader.java:745)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270)
at org.hibernate.loader.Loader.doList(Loader.java:2294)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2172)
at org.hibernate.loader.Loader.list(Loader.java:2167)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1706)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1056)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1046)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1039)
at com.datamatics.profilemanager.dao.ProfileManagerDAO.getUserAvatar(ProfileManagerDAO.java:70)
at com.datamatics.profilemanager.service.ProfileManagerService.getUserImage(ProfileManagerService.java:40)
at com.datamatics.profilemanager.service.ProfileManagerService$$FastClassByCGLIB$$e652b46c.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
at com.datamatics.profilemanager.service.ProfileManagerService$$EnhancerByCGLIB$$c558fc33.getUserImage(<generated>)
at com.datamatics.profilemanager.web.ProfileManagerController.showUserImage(ProfileManagerController.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
提前感谢任何帮助。
答案 0 :(得分:0)
您正在数据库中保存CommonsMultipartFile,但您需要将其保存在blob字段中
首先声明您的图片字段
@Lob
private byte[] avatar;
@Transient //we don't need to map a database this field
private CommonsMultipartFile avatarMPF;
当用户POST图像时保存:
byte[] bytes = userAvatar.get(0).getAvatarMPF().getBytes();
userAvatar.get(0).setAvatar(bytes);
getUserImage方法没有改变:
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
...
response.getOutputStream().write(userAvatar.get(0).getAvatar().getBytes());
response.getOutputStream().close();
希望有用。