Spring Data - NoSuchMethodError JpaRepositoryFactoryBean.setMappingContext() - java

I wrote a DAL following this guide. In particular this is my DALConfig.java configuration file
package my.pack;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.hibernate.ejb.HibernatePersistence;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.Repository;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#ComponentScan(basePackages = { "my.pack" })
#PropertySource("classpath:dbconnection.properties")
#EnableJpaRepositories("my.pack.repository")
#EnableTransactionManagement
public class DALConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver_class";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_POOL_INITIAL_SIZE = "pool.initialsize";
private static final String PROPERTY_NAME_POOL_MAX_IDLE = "pool.maxidle";
private static final String PROPERTY_NAME_DAL_CLASSES_PACKAGE = "entities.packages_to_scan";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.showsql";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
#Resource
private Environment environment;
#Bean
public DataSource dataSource()
{
Properties props = new Properties();
props.put("driverClassName", environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
props.put("url", environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
props.put("username", environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
props.put("password", environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
props.put("initialSize", environment.getRequiredProperty(PROPERTY_NAME_POOL_INITIAL_SIZE));
props.put("maxIdle", environment.getRequiredProperty(PROPERTY_NAME_POOL_MAX_IDLE));
BasicDataSource bds = null;
try {
bds = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bds;
}
#Bean
public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor()
{
PersistenceExceptionTranslationPostProcessor b = new PersistenceExceptionTranslationPostProcessor();
return b;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
#Bean
public PlatformTransactionManager transactionManager() throws ClassNotFoundException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_DAL_CLASSES_PACKAGE));
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
Properties jpaProterties = new Properties();
jpaProterties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
jpaProterties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
entityManagerFactoryBean.setJpaProperties(jpaProterties);
return entityManagerFactoryBean;
}
}
This is the Repository I wrote
package my.pack.repository;
import my.pack.entity.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface IUserRepository extends CrudRepository<User, String>{
}
Finally this is the test I run
package my.pack.tests;
import static org.junit.Assert.assertTrue;
import futureservice.UserService;
import my.pack.DALConfig;
import my.pack.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#ContextConfiguration(classes = { DALConfig.class})
#RunWith(SpringJUnit4ClassRunner.class)
public class DALTest {
#Autowired
UserService userService;
#Test
public void testGetUser() {
User user = null;
user = userService.findOne("mrossi");
assertTrue(null != user);
}
}
When I run the test I get the following exception stack and the test fails.
...
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'entityManager' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.setMappingContext(Lorg/springframework/data/mapping/context/MappingContext;)V
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:108)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:62)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1489)
... 41 more
It seems like the JpaRepositoryFactoryBean misses the setMappingContext method but as you can see from the documentation the method is supported. I'm using the 1.5.1.RELEASE version of spring-data-jpa artifact.
What can be the issue?
Thank you

Related

can we create two session factory of same database with different users in spring boot application

I am new to spring boot and I need to use same postgreSQL sql database with two different users in same package in same class
please suggest me the ways which I can do to make it work in my application
I have tried creating two configuration classes and calling session factory in the service class
these are the two configurtion classes
1: Mastercongig file
package com.demo.config;
import java.util.HashMap;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "masterSessionFactory", transactionManagerRef
= "masterPostgrsTransactionManager", basePackages = {
"com.demo.*" })
public class MasterPostgreSqlConfig {
/*
* #Autowired private EntityManagerFactory entityManagerFactory;
*/
#Value("${spring.database.driverClassName}")
private String driverClassName;
#Value("${spring.datasource.url}")
private String dataSourceUrl;
#Value("${spring.datasource.username}")
private String dataSourceUserName;
#Value("${spring.datasource.password}")
private String dataSourcePassword;
#Value("${spring.jpa.database-platform}")
private String hibernateDialect;
#Bean(name = "masterPostgrsEntityManagerFactory")
#Primary
public LocalContainerEntityManagerFactoryBean masterSessionFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(masterPostgresqlDataSource());
em.setPackagesToScan(new String[] { "com.demo.entity" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", hibernateDialect);
properties.put("hibernate.physical_naming_strategy",
SpringPhysicalNamingStrategy.class.getName());
properties.put("hibernate.implicit_naming_strategy",
SpringImplicitNamingStrategy.class.getName());
properties.put("hibernate.id.new_generator_mappings", false);
em.setJpaPropertyMap(properties);
return em;
}
#Primary
#Bean
public DataSource masterPostgresqlDataSource() {
DriverManagerDataSource masterdataSource = new DriverManagerDataSource();
masterdataSource.setDriverClassName(driverClassName);
masterdataSource.setUrl(dataSourceUrl);
masterdataSource.setUsername(dataSourceUserName);
masterdataSource.setPassword(dataSourcePassword);
return masterdataSource;
}
#Primary
#Bean(name = "masterPostgrsTransactionManager")
public PlatformTransactionManager masterPostgresTransactionManagerFactory() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(masterSessionFactory().getObject());
return transactionManager;
}
/*
* #Bean public SessionFactory getSessionFactory(){
* if(entityManagerFactory.unwrap(SessionFactory.class)== null){ throw new
* NullPointerException("factory is not a hibernate factory"); } return
* entityManagerFactory.unwrap(SessionFactory.class); }
*/
#Bean(name = "masterSessionFactory")
public SessionFactory masterSessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
}
2 common config file and i made it as primary
package com.demo.config;
import java.util.HashMap;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "commonSessionFactory", transactionManagerRef
= "commonPostgrsTransactionManager", basePackages = {
"com.demo" })
public class CommonPostgreSqlConfig {
/*
* #Autowired private EntityManagerFactory entityManagerFactory;
*/
#Value("${common.connection.driver_class}")
private String driverClassName;
#Value("${common.connection.url}")
private String dataSourceUrl;
#Value("${common.connection.username}")
private String dataSourceUserName;
#Value("${common.connection.password}")
private String dataSourcePassword;
#Value("${spring.jpa.database-platform}")
private String hibernateDialect;
#Bean(name = "commonPostgrsEntityManagerFactory")
#Primary
public LocalContainerEntityManagerFactoryBean commonSessionFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(commonPostgresqlDataSource());
em.setPackagesToScan(new String[] { "com.demo.entity" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", hibernateDialect);
properties.put("hibernate.physical_naming_strategy",
SpringPhysicalNamingStrategy.class.getName());
properties.put("hibernate.implicit_naming_strategy",
SpringImplicitNamingStrategy.class.getName());
properties.put("hibernate.id.new_generator_mappings", false);
em.setJpaPropertyMap(properties);
return em;
}
#Primary
#Bean
public DataSource commonPostgresqlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(dataSourceUrl);
dataSource.setUsername(dataSourceUserName);
dataSource.setPassword(dataSourcePassword);
return dataSource;
}
#Primary
#Bean(name = "commonPostgrsTransactionManager")
public PlatformTransactionManager commonPostgresTransactionManagerFactory() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(commonSessionFactory().getObject());
return transactionManager;
}
#Bean
public SessionFactory commonSessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
}
i am trying to create session factory object in my class level like this
#Autowired
#Setter
private SessionFactory commonSessionFactory;
#Autowired
#Setter
private SessionFactory masterSessionFactory;
getting this error
Description:
Field session in com.demo.dao.impl.democlass required a bean of type 'org.hibernate.SessionFactory' that could not be found.
Action:
Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.

JdbcTemplate returns NullPointerException in my Implementation Class

Hello I'm totally new to Spring Framework. I wanted to #Autowired the JdbcTemplate inside MasterDaoImpl but it returns NullPointerException.
I believe #Autowired objects are created after constructor.
It returns an address if i tried to print in one of the Configuration classes. I don't know what to do ? What should i do in order to make the
JdbcTemplate work inside of MasterDaoImpl.
Can anyone explain why this is happening ? Any Suggestions with the Configurations are appreciated.
AppConfig.java
package com.upeg.requisition.config;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.upeg.requisition")
public class AppConfig implements WebMvcConfigurer {
private static final Logger logger = Logger.getLogger(AppConfig.class);
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/tiles.xml", "/WEB-INF/loginTiles.xml" });
tilesConfigurer.setCheckRefresh(true);
return tilesConfigurer;
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// registry.jsp("/WEB-INF/pages/", ".jsp");
TilesViewResolver tilesViewResolver = new TilesViewResolver();
registry.viewResolver(tilesViewResolver);
}
#Bean("messageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("languages/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
return new CookieLocaleResolver();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}
}
AppInitialiser.java
package com.upeg.requisition.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SecurityConfig.class,AppConfig.class,DatabaseConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
DatabaseConfig.java
package com.upeg.requisition.config;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#PropertySource(value = { "classpath:application.properties" })
#EnableTransactionManagement
#ComponentScan("com.upeg.requisition")
public class DatabaseConfig {
private static final Logger logger = Logger.getLogger(DatabaseConfig.class);
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
jdbcTemplate.setResultsMapCaseInsensitive(true);
return jdbcTemplate;
}
}
SecurityConfig.java
package com.upeg.requisition.config;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
#ComponentScan("com.upeg.requisition")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomSuccesHandler customSuccesHandler;
private static final Logger logger = Logger.getLogger(SecurityConfig.class);
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/css/**", "/javascript/**", "/images/**", "/fonts/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll().antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").hasRole("USER").anyRequest().authenticated().and().formLogin().loginPage("/login")
.usernameParameter("username").passwordParameter("password").successHandler(customSuccesHandler).and()
.httpBasic().and().logout().invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/login").permitAll().and().csrf().disable();
http.sessionManagement().maximumSessions(1);
http.exceptionHandling().accessDeniedPage("/denied");
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user#user.com").password("{noop}Password1234!").roles("USER").and()
.withUser("approver#approver.com").password("{noop}Password1234!").roles("ADMIN");
}
}
MasterTableDao.java
public interface MasterTableDao {
List<MasterCategory> getCategory();
}
MasterDaoImpl.java
package com.upeg.requisition.daoimpl;
import java.util.List;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.upeg.requisition.config.AppConfig;
import com.upeg.requisition.config.CustomRowMapper;
import com.upeg.requisition.dao.MasterTableDao;
import com.upeg.requisition.model.MasterCategory;
#Repository
public class MasterDaoImpl implements MasterTableDao {
private static final Logger logger = Logger.getLogger(MasterDaoImpl.class);
#Autowired
JdbcTemplate jdbcTemplate;
#Override
public List<MasterCategory> getCategory() {
return jdbcTemplate.query("select * from category",new CustomRowMapper());
}
}
```[enter image description here][1]
[1]: https://i.stack.imgur.com/xTSc4.png
#Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(datasource);
jdbcTemplate.setResultsMapCaseInsensitive(true);
return jdbcTemplate;
}
jdbcTemplate.setDataSource(datasource); can be more appropriate but that's not the answer so you can put DatabaseConfig to AppIntializer
return new Class[]{SecurityConfig.class,AppConfig.class, DatabaseConfig.class};
I guess ComponentScan didn't work.
I just made these changes and it worked just gave my Bean a name and worked :)
#Bean("dataSource")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl(" jdbc:postgresql://localhost:5432/test");
dataSource.setUsername("postgres");
dataSource.setPassword("sillicon");
return dataSource;
}
#Bean("jdbcTemplate")
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}

How to test Spring's Cacheable on a method?

Recently in my project I was asked to use Spring's #Cacheable annotation for one of the method which returns static referenceData from the database. I followed this blog https://medium.com/#d.lopez.j/configuring-multiple-ttl-caches-in-spring-boot-dinamically-75f4aa6809f3 which guides to have caches created dynamically. I am trying to test this implementation by following this SO answer How to test Spring's declarative caching support on Spring Data repositories? and I am facing issues. I am not able to load the properties from the application-test.properties into my test class.
My CachingConfig Class
package org.vinodh.testing;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.Data;
#Configuration
#ConfigurationProperties(prefix = "caching")
#Data
public class CachingConfig {
private Map<String, CacheSpec> specs;
#Data
public static class CacheSpec {
private int minutesToExpire;
private int maximumSize;
public int getMaximumSize() {
return maximumSize;
}
public void setMaximumSize(int maximumSize) {
this.maximumSize = maximumSize;
}
public int getMinutesToExpire() {
return minutesToExpire;
}
public void setMinutesToExpire(int minutesToExpire) {
this.minutesToExpire = minutesToExpire;
}
}
public Map<String, CacheSpec> getSpecs() {
return specs;
}
#Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
if (specs != null) {
List<CaffeineCache> caches = specs.entrySet().stream()
.map(entry -> buildCache(entry.getKey(), entry.getValue())).collect(Collectors.toList());
cacheManager.setCaches(caches);
}
return cacheManager;
}
private CaffeineCache buildCache(String name, CacheSpec specs) {
Caffeine<Object, Object> caffeineBuilder = Caffeine.newBuilder()
.expireAfterWrite(specs.getMinutesToExpire(), TimeUnit.MINUTES).maximumSize(specs.getMaximumSize());
return new CaffeineCache(name, caffeineBuilder.build());
}
}
My Test Class
package org.vinodh.testing;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
#ConfigurationProperties(prefix = "caching")
#ActiveProfiles("test")
#Profile("test")
public class CachingConfigTest {
#Configuration
#EnableCaching
static class NestedCacheConfiguration {
static class CacheSpec {
#SuppressWarnings("unused")
private int minutesToExpire;
#SuppressWarnings("unused")
private int maximumSize;
}
private Map<String, CacheSpec> specs;
public Map<String, CacheSpec> getSpecs() {
return specs;
}
#Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
System.out.println(getSpecs()); // Is null
return cacheManager;
}
}
#Test
public void test() {
System.out.println("Inside Test");
}
}
application-test.properties
caching.specs.test.minutesToExpire=10
caching.specs.test.maximumSize=10

Spring mutliple datasources with Hibernate gives: No Session found error

I am using Spring 4 with Hibernate 4 and trying to have multiple datasources configured. When I use the new second one, I always get an error.
package org.miso.vre.config;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan("org.miso.vre")
#PropertySource("classpath:database.properties")
public class DatabaseConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_DATABASE_MISOFT_DRIVER = "db.misoft.driver";
private static final String PROPERTY_NAME_DATABASE_MISOFT_PASSWORD = "db.misoft.password";
private static final String PROPERTY_NAME_DATABASE_MISOFT_URL = "db.misoft.url";
private static final String PROPERTY_NAME_DATABASE_MISOFT_USERNAME = "db.misoft.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public DataSource dataSourceMISOFT() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_MISOFT_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_MISOFT_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_MISOFT_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_MISOFT_PASSWORD));
return dataSource;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
#Bean
public LocalSessionFactoryBean sessionFactoryMISOFT() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSourceMISOFT());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.miso.vre.model.VRE_Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
#Repository
public class VRETestTableDAOImpl implements VRETestTableDAO {
#Autowired
#Qualifier(value="sessionFactoryMISOFT")
private SessionFactory sessionFactoryMISOFT;
private Session getCurrentSession() {
return sessionFactoryMISOFT.getCurrentSession();
}
public VRE_Record getVRE_Record(int id) {
VRE_Record vRE_Record = (VRE_Record) getCurrentSession().get(VRE_Record.class, id);
return vRE_Record;
}
}
>
package org.miso.vre.service;
import org.miso.vre.dao.VRETestTableDAO;
import org.miso.vre.model.VRE_Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by PDuer on 12/29/2015.
*/
#Service
#Transactional
public class TestServiceImpl implements TestService {
#Autowired
private VRETestTableDAO vreTestTableDAO;
#Override
public VRE_Record getVRERecord (int id) {
return vreTestTableDAO.getVRE_Record(id);
}
}
exception org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.hibernate.HibernateException: No Session found for current thread
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:943)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
com.github.dandelion.datatables.core.web.filter.DatatablesFilter.doFilter(DatatablesFilter.java:73)
root cause org.hibernate.HibernateException: No Session found for
current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1013)
org.miso.vre.dao.VRETestTableDAOImpl.getCurrentSession(VRETestTableDAOImpl.java:18)
org.miso.vre.dao.VRETestTableDAOImpl.getVRE_Record(VRETestTableDAOImpl.java:22)
org.miso.vre.service.TestServiceImpl.getVRERecord(TestServiceImpl.java:22)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
The reason being, the sessionFactoryMISOFT is not associated with any transaction manager. Only the sessionFactory is associated with a transaction manager through transactionManager() method.
You need to create a similar method, say, transactionManagerMISOFT() and associate sessionFactoryMISOFT with this new transactionManager.
And when using the #Transaction attribute we need to specify which transactionManager needs to be used.
In my case, I have defined two sessionFactories and two transactionManager methods as below:
#Bean
public HibernateTransactionManager transactionManagerABC() {
return new HibernateTransactionManager(sessionFactoryABC().getObject());
}
#Bean
public HibernateTransactionManager transactionManagerXYZ() {
return new HibernateTransactionManager(sessionFactoryXYZ().getObject());
}
And while using it I specify either transactionManagerABC or transactionManagerXYZ along with Transactional attribute in you service classes, as below:
#Transactional(transactionManager="transactionManagerABC")
public Forest getForestById(int id) {
return forestDAO.getForestById(id);
}
You need to use Qualifier with Autowired annotation for sessionFactory, which I believe you already have:
#Qualifier("sessionFactoryABC")
private SessionFactory sessionFactory;

org.hibernate.hql.internal.ast.QuerySyntaxException: is not mapped [from Team]

I'm working on little Spring MVC CRUD application. Got some strange problems:
configuration class:
package sbk.spring.simplejc.config;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration //Specifies the class as configuration
#ComponentScan("sbk.spring.simplejc") //Specifies which package to scan
//#Import({DataBaseConfig.class})
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
#EnableWebMvc //Enables to use Spring's annotations in the code
public class WebAppConfig extends WebMvcConfigurerAdapter{
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
application.properties:
#DB properties:
db.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
db.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=Examples
db.username=sa
db.password=
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.SQLServerDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=sbk.spring.simplejc.entity
#Entity class:
package sbk.spring.simplejc.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Team")
public class Team {
#Id
#GeneratedValue
private Integer id;
private String name;
private Integer rating;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
}
Controller class:
package sbk.spring.simplejc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import sbk.spring.simplejc.service.ITeamService;
#Controller
public class TeamController {
#Autowired
ITeamService service;
#RequestMapping(value="/")
public ModelAndView goToHelloPage() {
ModelAndView view = new ModelAndView();
view.addObject("teamList", service.listTeams());
return view;
}
}
Error stack trace:
org.hibernate.hql.internal.ast.QuerySyntaxException: Team is not mapped [from Team]
org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3420)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3309)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1777)
sbk.spring.simplejc.dao.HibTeamDAO.listTeams(HibTeamDAO.java:23)
sbk.spring.simplejc.service.TeamService.listTeams(TeamService.java:27)
I haven't got a clue about this issue.
Update
DAO class:
package sbk.spring.simplejc.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sbk.spring.simplejc.entity.Team;
#Repository
public class HibTeamDAO implements TeamDAO {
#Autowired
private SessionFactory sessionFactory;
public void addTeam(Team team) {
sessionFactory.getCurrentSession().save(team);
}
public void updateTeam(Team team) {
sessionFactory.getCurrentSession().update(team);
}
#SuppressWarnings("unchecked")
public List<Team> listTeams() {
return sessionFactory.getCurrentSession().createQuery("from Team").list();
}
#SuppressWarnings("unchecked")
public Team getTeamById(Integer teamID) {
Session session = sessionFactory.getCurrentSession();
List<Team> listTeam = session.createQuery("from Team t where t.id = :teamID")
.setParameter("teamID", teamID)
.list();
return listTeam.size() > 0 ? (Team)listTeam.get(0) : null;
}
public void removeTeam(Integer teamID) {
Team team = (Team) sessionFactory.getCurrentSession().load(Team.class, teamID);
if(team != null){
sessionFactory.getCurrentSession().delete(team);
}
}
#Override
public Integer count() {
return (Integer) sessionFactory.getCurrentSession().createQuery("select count(t) from Team t").uniqueResult();
}
}
TeamController class:
package sbk.spring.simplejc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import sbk.spring.simplejc.service.ITeamService;
#Controller
public class TeamController {
#Autowired
ITeamService service;
#RequestMapping(value="/")
public ModelAndView goToHelloPage() {
ModelAndView view = new ModelAndView();
view.addObject("teamList", service.listTeams());
return view;
}
}
Update
Now I got rid from this problem by changing DAO method from
return sessionFactory.getCurrentSession().createQuery("from Team").list();
to
return sessionFactory.getCurrentSession().createQuery("from sbk.spring.simplejc.entity.Team").list();
But received another issue: every query return null despite of existing rows in Team table.
Update
Finally I noticed warning messages:
Feb 15, 2014 7:01:05 PM org.hibernate.hql.internal.QuerySplitter concreteQueries
WARN: HHH000183: no persistent classes found for query class: from sbk.spring.simplejc.entity.Team
Update
At least I've sorted out this issue by adding next row of code in dataSource bean definition in WebAppConfig:
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setAnnotatedClasses(new Class[]{Team.class});//new row!!!
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
In my case it was because I didn't have the hibernate packagesToScan property. I see that you have it. May be this comment will be useful for someone who missed it.
"No, in this instance I've got org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: * near line 1, column 8 [select * from Team] – Sobik Feb 15 at 10:29"
Instead "Select * from Team" try write "from Team". Because Hibernate works with java entity.

Categories