I have just started working in java spring framework. Am just trying to populate a simple table with columns id and a name. But am getting :
Unknown entity: org.hibernate.MappingException
I get that it is commonly encountered exception. But I couldn't fix this. You can find the The entity, dao and hibernate config am using below.
HibernateConfig.java
@Getter @Setter
@Configuration@ConfigurationProperties(prefix = "databaseConfiguration")
public class HibernateConfig {
@Value("${driverClass}")
private String driverClass;
@Value("${url}")
private String url;
@Value("username")
private String username;
@Value("password")
private String password;
@Value("${hibernateDialect}")
private String hibernateDialect;
@Value("${hbm2ddlAuto}")
private String hbm2ddlAuto;
private Integer minSize;
private Integer maxSize;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.hbm2ddl.auto", hbm2ddlAuto);
properties.put("hibernate.dialect", hibernateDialect);
properties.put("hibernate.c3p0.min_size", minSize);
properties.put("hibernate.c3p0.max_size", maxSize);
return properties;
}
@Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public ITestDao testDao() {
ITestDao testDao = new TestDao();
return testDao;
}
}
All the properties are being taken from the .yml file. ITestDao is the interface with abstract add() method in it.
Entity class
@Getter
@Setter
@Entity
@Table(name = "test")
public class Test {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, unique = true)
private Long id;
@Column(name = "dump", nullable = false)
private String dump;
}
Dao class
@Repository
@Transactional
@Getter
@Setter
public class TestDao implements ITestDao {
@Autowired
private LocalSessionFactoryBean sessionFactoryBean;
public Test add(Test test) {
try {
sessionFactoryBean.getObject().getCurrentSession().getTransaction().begin();
sessionFactoryBean.getObject().getCurrentSession().persist(test);
} finally {
sessionFactoryBean.getObject().getCurrentSession().getTransaction().commit();
}
return test;
}
}
A service method will call this dao with @Transactional
annotated above it. But while calling this add()
dao method am getting Unknown entity:
org.hibernate.MappingException