Spring Java Config. Transaction problems - java

I have a spring application with java config:
#Controller
#RequestMapping("/")
public class MainController {
#Inject
#Named("dbDaoService")
IDaoService dbDaoService;
#RequestMapping(value="/saveNoteAsync", method = RequestMethod.POST)
public #ResponseBody String saveNoteAsync(#RequestBody CreateRequest createRequest, HttpServletRequest request) {
Notes newNote = new Notes(
createRequest.getTitle(),
createRequest.getNote(),
tagService.getTagMask(createRequest.getTags())
);
Long newId = dbDaoService.createNotes(newNote);
return ""+newId;
}
}
DBService:
#Service("dbDaoService")
public class DBDaoService implements IDaoService {
#PersistenceContext(unitName = "MyEntityManager")
private EntityManager entityManager;
private List<Tags> tags = null;
#Override
#Transactional
public Long createNotes(Notes data) {
entityManager.persist(data);
return data.getId();
}
}
Configuration class
#Configuration
#EnableWebMvc
#ComponentScan("ru.mypackage")
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/WEB-INF/views/**").addResourceLocations("/views/");
}
#Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Bean
public BasicDataSource getBasicDataSource(){
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost:3306/test");
bds.setUsername("root");
bds.setPassword("root");
return bds;
}
#Bean
public HibernateJpaVendorAdapter getHibernateJpaVendorAdapter(){
HibernateJpaVendorAdapter hjva = new HibernateJpaVendorAdapter();
hjva.setShowSql(true);
hjva.setGenerateDdl(true);
hjva.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
return hjva;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName("MyEntityManager");
em.setDataSource(getBasicDataSource());
em.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
em.setPackagesToScan("ru.eastwind.persistance");
return em;
}
#Bean
public HibernateJpaDialect getHibernateJpaDialect(){
return new HibernateJpaDialect();
}
#Bean
public JpaTransactionManager getJpaTransactionManager(){
JpaTransactionManager jtm = new JpaTransactionManager();
jtm.setEntityManagerFactory(getEntityManagerFactory().getObject());
jtm.setJpaDialect(getHibernateJpaDialect());
return jtm;
}
}
In line entityManager.persist(data); I get the error:
javax.persistence.TransactionRequiredException: No transactional EntityManager available
But all select queries are woking correct! Please, help.

Use #EnableTransactionManagement on #Configuration class
#Configuration
#EnableWebMvc
#ComponentScan("ru.mypackage")
#EnableTransactionManagement
public class WebConfig extends WebMvcConfigurerAdapter {
// ... Your code
}
See Also : http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html

Related

Spring MVC backend returns 404 (Rest)

I hope someone can help me with my problem. I write at the moment a Spring MVC Server and a client. Unfortunatly my Rest Controller only returns a 404. I am using a Tomcat 8. What I know is that the Spring Application is deployed correctly because I can visit my index.jsp page. The context, under which it is deployed is /backend. So my base url is localhost:8080/backend. Now I have a restcontroller whitch looks like this.
#Controller
#RequestMapping("/api/developer")
public class DeveloperController {
#Autowired
private DeveloperOutboundDipatcher service;
#RequestMapping(method = RequestMethod.GET, value = "/getAll")
public List<DeveloperDTO> findAll() {
return service.findAllDeveloper();
}
#RequestMapping(method = RequestMethod.GET, value = "/get/{name}")
public DeveloperDTO findByName(#PathVariable String name) {
return service.findOneByName(name);
}
#RequestMapping(method = RequestMethod.DELETE, value = "/delete/{name}")
public void deleteDeveloper(#PathVariable String name) {
service.deleteDeveloper(name);
}
#RequestMapping(method = RequestMethod.POST, value = "/save/")
public void saveDeveloper(#RequestBody DeveloperDTO developer) {
service.save(developer);
}
#RequestMapping(method = RequestMethod.PUT, value = "/edit/")
public void editDeveloper(#RequestBody DeveloperDTO developer) {
service.edit(developer);
}
}
my config class looks like this:
package gamescreation;
#Configuration
#ComponentScan(basePackages= "gamescreation")
#EnableJpaRepositories("gamescreation")
#EnableTransactionManagement
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
private final String PROPERTY_DRIVER = "driver";
private final String PROPERTY_URL = "url";
private final String PROPERTY_USERNAME = "user";
private final String PROPERTY_PASSWORD = "password";
private final String PROPERTY_SHOW_SQL = "hibernate.show_sql";
private final String PROPERTY_DIALECT = "hibernate.dialect";
#Autowired
Environment environment;
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("gamescreation.entity" );
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(hibernateProperties());
return em;
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource ();
dataSource.setDriverClassName("org.postgresql.Driver");
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(
EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto",
"false");
setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL82Dialect");
setProperty("hibernate.globally_quoted_identifiers",
"true");
}
};
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
#Bean
public SpringLiquibase liquibase() {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setChangeLog("classpath:/db-changelog-master.xml");
liquibase.setDataSource(dataSource());
return liquibase;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
I hope someone can tell me what is missing.
My client class looks like this:
#Service
public class DeveloperService {
private static final String DEVELOPER_BASEURL = "http://localhost:8080/backend/api/developer";
public List<DeveloperDTO> getDeveloperList() {
RestTemplate restTemplate = new RestTemplate();
DeveloperList response = restTemplate.getForObject(DEVELOPER_BASEURL + "/getAll", DeveloperList.class);
return response.getDevelopers();
}
public DeveloperDTO getSelectedDeveloper(String name) {
String url = DEVELOPER_BASEURL + "/get/{name}";
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParam("name", name);
RestTemplate restTemplate = new RestTemplate();
DeveloperDTO response = restTemplate.getForObject(builder.toUriString(), DeveloperDTO.class);
return response;
}
public void delete(String name) {
String url = DEVELOPER_BASEURL + "/delete/{name}";
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParam("name", name);
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(builder.toUriString());
}
public DeveloperDTO save(DeveloperDTO dto) {
String url = DEVELOPER_BASEURL + "/save";
HttpEntity<DeveloperDTO> request = new HttpEntity<>(dto);
RestTemplate restTemplate = new RestTemplate();
DeveloperDTO response = restTemplate.postForObject(url, request, DeveloperDTO.class);
return response;
}
}
Thank you in advance for your help. If you need any other information from my project, feel free to ask.
#Controller alone will not work please use #Responsebody to get the response in REST or use the #RestController.

How I need to configure PersistenceJPAConfig?

I have a class with config. And I have a method entityManagerFactory() that tagged like Bean.
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:hibernate.properties" })
#EnableJpaRepositories
public class PersistenceJPAConfig {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "java.entities" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/carpark?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTCx`");
dataSource.setUsername( "root" );
dataSource.setPassword( "1111" );
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
public Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
}
And I have a service that use EntityManager. EntityManager tagged like #Autowired, and spring create EntityManager is null. Where I'm configured incorrectly. I need to entityManager with fields from method entityManagerFactory() (in class PersistenceJPAConfig).
#Service
public class BusService {
#Autowired
private BusRepository busRepository;
#Autowired
private EntityManager entityManager;
public void getBus(){
try{
entityManager.getTransaction().begin();
Query query = entityManager.createNativeQuery("SELECT ID, NUMBER , Rote_ID FROM bus", Bus.class);
busRepository.save(query.getResultList());
System.out.println(busRepository.toString());
}finally {
entityManager.getTransaction().commit();
}
}
}
my packages are located like this
thanks in advance
You should use the `#PersistenceContext' annotation to inject the entity manager:
#Service
public class BusService {
#Autowired
private BusRepository busRepository;
#PersistenceContext
private EntityManager entityManager;
public void getBus(){
try{
entityManager.getTransaction().begin();
Query query = entityManager.createNativeQuery("SELECT ID, NUMBER , Rote_ID FROM bus", Bus.class);
busRepository.save(query.getResultList());
System.out.println(busRepository.toString());
} finally {
entityManager.getTransaction().commit();
}
}
there are several reasons to do that, you can get an overview here
and update you configuration class with the #ComponentScan annotation
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:hibernate.properties" })
#EnableJpaRepositories
#ComponentScan(basePackages = {
"model.service"})
public class PersistenceJPAConfig {
....
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new
LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "model.entities" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
....

HibernateException: createQuery is not valid without active transaction

The programmatic configuration seems in place but for some reason the application throws exception:
org.springframework.orm.jpa.JpaSystemException: createQuery is not valid without active transaction; nested exception is org.hibernate.HibernateException: createQuery is not valid without active transaction
Code:
#Repository
public class FilmDAOImpl implements FilmDAO {
#Autowired
private HibernateUtil hibernateUtil;
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Film> findFilms(int actorId, int categoryId, int languageId, int releaseYear) {
Query searchQuery = sessionFactory.getCurrentSession().createQuery("from Film " +
"join Actor " +
"join Category " +
"where Category.categoryId=:categoryId " +
"and Film.language.id=:languageId " +
"and Film.releaseYear=:releaseYear " +
"and Actor.actorId=:actorId");
searchQuery.setParameter("categoryId", categoryId);
searchQuery.setParameter("languageId", languageId);
searchQuery.setParameter("releaseYear", releaseYear);
searchQuery.setParameter("actorId", actorId);
return (List<Film>)searchQuery.list();
}
}
Configuration:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories (basePackages = { "com.hibernate.query.performance.persistence" }, transactionManagerRef = "jpaTransactionManager")
#EnableJpaAuditing
#PropertySource({ "classpath:persistence-postgresql.properties" })
#ComponentScan(basePackages = { "com.hibernate.query.performance" })
public class ApplicationConfig {
#Autowired
private Environment env;
public ApplicationConfig() {
super();
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(applicationDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.hibernate.query.performance.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(applicationDataSource());
emf.setPackagesToScan(new String[] { "com.hibernate.query.performance.persistence.model" });
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(vendorAdapter);
emf.setJpaProperties(hibernateProperties());
return emf;
}
#Primary
#Bean
public DriverManagerDataSource applicationDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
#Bean
#Primary
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
transactionManager.setDataSource(applicationDataSource());
return transactionManager;
}
#Bean
public PlatformTransactionManager jpaTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
hibernateProperties.setProperty("hibernate.current_session_context_class", "managed");
hibernateProperties.setProperty("hibernate.current_session_context_class", "org.hibernate.context.internal.ThreadLocalSessionContext");
return hibernateProperties;
}
}
UPDATE
#Service
#Transactional
public class FilmServiceImpl implements FilmService {
#Autowired
private FilmDAO filmDAO;
#Override
public int createFilm(Film film) {
return filmDAO.createFilm(film);
}
#Override
public Film updateFilm(Film film) {
return filmDAO.updateFilm(film);
}
#Override
public void deleteFilm(int id) {
filmDAO.deleteFilm(id);
}
#Override
public List<Film> getAllFilms() {
return filmDAO.getAllFilms();
}
#Override
public Film getFilm(int id) {
return filmDAO.getFilm(id);
}
#Override
public List<Film> findFilms(int actorId, int categoryId, int languageId, int releaseYear) {
return filmDAO.findFilms(actorId, categoryId, languageId, releaseYear);
}
}
Try using openSession() as below, Since getCurrentSession() just attaches to the current session:
Query searchQuery = sessionFactory.openSession().createQuery(...
Also, you need to surround code with proper try..catch..finally block and in finally close the session using session.close()

Not active transaction: javax.persistence.TransactionRequiredException: Executing an update/delete query

I have the same problem. I am using spring 4.2.2.RELEASE
I have a Java Based configuration.
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages={"com.mypackage"})
public class InfrastructureConfig {
#Autowired Environment env;
#Autowired private DataSource dataSource;
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
return jpaTransactionManager;
}
#Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPersistenceUnitName("javaconfigPU");
em.setPackagesToScan("com.mypackage");
em.setJpaVendorAdapter(jpaVendorAdaper());
em.setJpaPropertyMap(additionalProperties());
em.afterPropertiesSet();
return em.getObject();
}
public JpaVendorAdapter jpaVendorAdaper() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
...
return vendorAdapter;
}
private Map<String, Object> additionalProperties() {
Map<String, Object> properties = new HashMap<String, Object>();
...
return properties;
}
}
The service where I call the update query
#Service
public class MyService {
#Autowired private MyRepository myRepo;
#Transactional
public void myMethod(MyEntity myEntity){
myRepo.save(myEntity);
}
}
the #transactional is from spring
I have a javax.persitence.TransactionRequiredException when I don't use the #transactional or I put it without attributes or I put it with attributes.
My code works fine in an other application and in this one, it worked fine 3 weeks ago.

Spring + Hibernate : No Session Found For Current Thread

I'm having difficulties solving this problem:
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:993)
at com.veram.dao.UsuariosDaoImp.findByUserName(UsuariosDaoImp.java:23)
at com.veram.servicos.ServicosUsuario.loadUserByUsername(ServicosUsuario.java:31)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:101)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
Classes:
AppConfig
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "com.ver.*"})
#Import({ SecurityConfig.class, DataBaseConfig.class })
public class AppConfig extends WebMvcConfigurerAdapter
{
//Adiciona a pasta resources ao dispatcher do MVC
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
//Localização das views da minha aplicação
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
DataBaseConfig:
#Configuration
#Import({ SecurityConfig.class })
public class DataBaseConfig
{
#Bean
public SessionFactory sessionFactory()
{
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.ver.entid").addProperties(getHibernateProperties());
return builder.buildSessionFactory();
}
private Properties getHibernateProperties()
{
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/veram_prod");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
#Bean
public HibernateTransactionManager txManager()
{
return new HibernateTransactionManager(sessionFactory());
}
}
UserServices:
#Service("userDetailsService")
public class ServicosUsuario implements UserDetailsService
{
#Autowired
private UsuariosDao userDao;
#Transactional(readOnly=true)
#Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException
{
com.veram.entidades.Usuarios user = userDao.findByUserName(username);
}
}
UserDaoImp
#Repository
public class UsuariosDaoImp implements UsuariosDao
{
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public Usuarios findByUserName(String username)
{
List<Usuarios> users = new ArrayList<Usuarios>();
users = sessionFactory.getCurrentSession()
.createQuery("from usuarios where usuario=?")
.setParameter(0, username)
.list();
if (users.size() > 0)
{
return users.get(0);
}
else
{
return null;
}
}
}
I'm trying to understand the configuration for Spring and Hibernate. Every time I try to access the current session, I get a no session found for current thread error in my console (doesn't stop the app).
If anyone can help, I appreciate!
Try adding #EnableTransactionManagement to DataBaseConfig

Categories