我正在尝试将图像添加到我的MySQL数据库的Blob中。
我正在使用Spring Boot作为后端,AngularJs作为前端。
所以, AngularJs 发送到我的RestController:
var fd = new FormData();
fd.append("file", this.credentials.avatar);
$http.post(
'/register-user-blob',
fd,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}
)
然后,我的 @RestController 收到一个Spring MultipartFile:
import java.sql.Blob;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;
//[...others imports]
@RestController
public class RegisterRest {
@Autowired
private SessionFactory sessionFactory;
@RequestMapping(value = "/register-user-blob", produces = "application/json")
public FormRegisterResponseDto registerUserWithBlob(@RequestParam(value="file", required=false) MultipartFile file){
Blob avatar = null;
System.out.println(file.getOriginalFilename()); // It works so I receive the MultipartFile correctly.
System.out.println(sessionFactory); // It works, so SessionFactory is not null
try {
avatar = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(file.getInputStream(),file.getSize());
} catch (HibernateException e) {
// ...
} catch (IOException e) {
// ...
}
try{
// try to insert into databases
} catch (Exception ex){
// ...
}
return new FormRegisterResponseDto();
}
}
如您所见,我正在使用org.hibernate.Hibernate.getLobCreator(...)将我的MultipartFile强制转换为java.sql.Blob 这个方法需要Hibernate Session,所以我为它配置了Spring Boot(如果我理解的话,Spring Boot初始化一个JPA Session,所以我必须配置它来获得一个Hibernate Session):
我的 application.properties :
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
我的 Spring Boot配置类:
@SpringBootApplication
public class BusinessBootApplication {
public static void main(String[] args) {
SpringApplication.run(BusinessBootApplication.class, args);
}
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(){
return new HibernateJpaSessionFactoryBean();
}
}
所以,我不明白为什么会出现这个错误:
org.hibernate.HibernateException:无法获取当前线程的事务同步会话
请问您有什么想法吗?谢谢:))