Bonjour à tous,
j'ai l'erreur suivante :
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
Voici le contexte: Mon application utilise Spring Boot pour le backoffice et AngularJs pour le front.
J'essai de récupérer une image uploader pour la sotcker dans un Blob de ma BDD MySQL.
Donc la première étape est d'envoyer le fichier par AngularJS :
1 2 3 4 5 6 7 8 9 10 11 12
|
var fd = new FormData();
fd.append("file", this.credentials.avatar);
$http.post(
'/register-user-blob',
fd,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}
) |
Ensuite, mon Webservice Rest (Spring @RestController) reçoit le fichier sous forme de MultipartFile (classe fournie par Spring) :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
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();
}
} |
Comme vous pouvez le voir, j'essai de "caster" mon MultipartFile en java.sql.Blob via org.hiberbate.Hibernate.getLobCreator(...) qui prend une Hibernate Session en paramètre.
D'après ce que j'ai compris, il faut configurer Spring Boot pour qu'il fournisse une session Hibernate car par défaut il fourni une session JPA.
Donc j'ai trouvé en fouillant le net les éléments suivants pour faire cette configuration :
mon fichier application.properties :
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
ma classe de configuration de Spring Boot :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
@SpringBootApplication
public class BusinessBootApplication {
public static void main(String[] args) {
SpringApplication.run(BusinessBootApplication.class, args);
}
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(){
return new HibernateJpaSessionFactoryBean();
}
} |
Malgré ces configurations, j'ai mon erreurs, vous avez une idée ? Merci d'avance
Partager