org.hibernate.AnnotationException: No identifier specified for entity - even when it was - spring

I have the following configuration:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="jpaDataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.example.domain</value>
<value>com.example.repositories</value>
</list>
</property>
</bean>
I have my Geoname class in com.example.domain:
#Entity
#Table(name="geonames")
public class Geoname implements Serializable {
#Id
#Column(name="geonameid")
private Long geonameid = null;
}
yet, when running, I get the following exception:
Caused by: org.hibernate.AnnotationException: No identifier specified
for entity: com.example.domain.Geoname at
org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:277)
at
org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:224)
at
org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:664)
at
org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3449)
at
org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3403)
at
org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1330)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1730)
Any ideas why?
side note: I am combining both mongodb and hibernate/ mysql on this project.

I had the following
import org.springframework.data.annotation.Id;
Naturally, it should be:
import javax.persistence.Id;
Thanks to #JB Nizet

I faced the same error.I solved it and figured out i didn't put #Id annotations in id field in my Entity class.
#Entity
#Table(name="geonames")
public class Geoname implements Serializable {
#Column(name="geonameid")
private Long geonameid = null;
}

try this
#Column(name="geonameid",unique=true,nullable=false)

Related

Exception Illegal Argument - unknown entity JPA - Additional package to scan for entities in application-context.xml is not taken into consideration

I am working on a Spring application which has a persistence unit configured in the application-context.xml. I need to add an additional package in in order to use new entities.
Even though this part of the persistence.xml file looks like below, my entities from the additional package are not seen by the application and I get an exception saying that the entity is unknown.
<bean id="transactionManager_students" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryStudents" />
<qualifier value="clientTransaction" />
</bean>
<bean id="entityManagerFactoryStudents"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource_College" />
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
<property name="packagesToScan">
<list>
<value>com.load.model</value>
<value>com.students.entity</value>
</list>
</property>
<property name="persistenceUnitName" value="unit_stud" />
<property name="jpaProperties">
<props>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>  
I also have to mention that I annotated the entities with #Entity and in the class where I am operating on the entities I have this ( the row with em.persist(student) is giving me the error )
#PersistenceContext(unitName = "unit_stud")
public EntityManager em;
public Student student;
#Transactional(value = "clientTransaction", propagation = Propagation.REQUIRED)
public long persistStudentObject() {
long studentId = 0;
try
{
logger.debug("Start Persisting...");
em.persist(student);
// unique ID
studentId = student.getId();
logger.debug("Persisting OK...");
}
catch (PersistenceException persistenceException)
{
logger.error("PersistenceException occur", persistenceException);
}
}
return studentId ;
}
The entity:
package com.students.entity;
#Entity
#Table(name = "STUDENTS", schema = "DEMO", catalog = "")
public class Student{
private long id;
private String firstname;
private String name;
private String streetnumber;
private String zipcodecity;
Can anyone help me? I do not know what to do in order to make my entities visible.

Bean property 'sessionFactoy' is not writable or has an invalid setter method

Working on spring+hibernate+maven code.
here's my StockDaoImpl class..
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.Stock;
public class StockDaoImpl extends HibernateDaoSupport implements StockDao{
public void save(Stock stock){
getHibernateTemplate().save(stock);
}
...
My sessionfactory defined in an xml..
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibenate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>/Hibernate/Stock.hbm.xml</value>
</list>
</property>
</bean>
I get the following error in console..Bean property 'sessionFactoy' is not writable or has an invalid setter method...
I tried writing a setter function for sessionfactory in StockDaoImpl...But I get an error saying 'setSessionFactory() in HibernateDaoSupport cannot be overridden'.
Can anyone pls tell me how to resolve the issue..

Spring Data JPA + Hibernate : Inject Catalog/Schema at runtime in to JPA Entities

We have a scenario where in the catalog/schema combination is different for the entity classes inside certain package from the default one used by all others. I am trying to set Catalog and Schema on #Table annotation using PersistenceUnitPostProcessors callback at runtime using javaassist as below.
The issue: The added member values on javaassist annotation are NOT getting reflected on to the actual class associated with it. Please help me in finding the wrong lines of code; OR if there are other ways to achieve this, more than happy to know.
Note: I do not want to create a separate EntityManagerFactory for each catalog/schema combination - it is not really required in our case as the datasource is same.
related content in spring context :
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean name="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="mainUnit" />
<property name="packagesToScan" value="com.mycompany.lob.domain" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="persistenceUnitPostProcessors">
<list>
<bean class="com.mycompany.lob.jpa.CustomPersistenceUnitPostProcessor"/>
</list>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SqlmxDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">100</prop>
<prop key="hibernate.order_inserts">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.connection.autocommit">true</prop>
<prop key="hibernate.default_schema">DEFAULT_SCHEMA</prop>
<prop key="hibernate.default_catalog">DEFAULT_CATALOG</prop>
</props>
</property>
</bean>
PersistenceUnitPostProcessors callback :
public class CustomPersistenceUnitPostProcessor implements PersistenceUnitPostProcessor {
#Value("${user.schema}")
private String userSchema;
#Value("${user.catalog}")
private String userCatalog;
private static final Logger LOGGER = LoggerFactory.getLogger(CustomPersistenceUnitPostProcessor.class);
#SuppressWarnings("unchecked")
#Override
public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
LOGGER.info("MutablePersistenceUnitInfo : {} ",pui);
List<String> jpadomains = pui.getManagedClassNames();
for (Iterator<?> iterator = jpadomains.iterator(); iterator.hasNext();) {
String clazzName = (String) iterator.next();
if(clazzName.startsWith("com.mycompany.lob.domain.user")){
try {
//modify annotation attributes using JavaAssist
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.get(clazzName);
ClassFile classFile = ctClass.getClassFile();
ConstPool constPool = classFile.getConstPool();
AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute)classFile.getAttribute(AnnotationsAttribute.visibleTag);
if(annotationsAttribute!=null){
//Get hold of #Table annotation
Annotation tableAnnotation = annotationsAttribute.getAnnotation("javax.persistence.Table");
if(tableAnnotation!=null){
tableAnnotation.addMemberValue("catalog", new StringMemberValue(userCatalog, constPool));
tableAnnotation.addMemberValue("schema", new StringMemberValue(userSchema, constPool));
annotationsAttribute.addAnnotation(tableAnnotation);
LOGGER.debug("Schema-Table : {} - {} ", ((StringMemberValue)tableAnnotation.getMemberValue("schema")).getValue(),
((StringMemberValue)tableAnnotation.getMemberValue("name")).getValue() );
//write the file back
ctClass.writeFile();
}
}
} catch (Exception e) {
LOGGER.error("Schema/Catalog could not be altered for {} ",clazzName);
}
}
}
}
}
Simple answer:
19. Multitenancy
Complex catalog mapping:
interface PhysicalNamingStrategy in Hibernate v5 is helpful.
public interface PhysicalNamingStrategy {
public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment);
public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment);
....
}
Check the Example 2. Example PhysicalNamingStrategy implementation in Hibernate 5 User Guide and how to config it

Spring + Hibernate annotations error "is not mapped"

I use Spring + Hibernate with annotations and i got the following error :
org.hibernate.hql.ast.QuerySyntaxException: Produit is not mapped [from Produit]
it appens when i call this function :
public List<Produit> getListeProduit() {
return sessionFactory.getCurrentSession().createQuery("from Produit").list();
}
This is my hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="port.domain.Produit" />
</session-factory>
</hibernate-configuration>
Produit class are annoted well with #Entity, #Table
ID with #Id, #Column, #GeneratedValue
The others columns with #Column
Here is my bean SessionFactory in my XXX-servlet.xml :
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
EDIT : Entity Code
#Entity
#Table(name="produit")
public class Produit implements Serializable{
#Id
#Column(name="produit_id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int produitId;
#Column(name="produit_nom")
private String produitNom;
public void setProduitId(int i) {
produitId = i;
}
public int getProduitId() {
return produitId;
}
public void setProduitNom(String s) {
produitNom = s;
}
public String getProduitNom() {
return produitNom;
}
}
I know there are many threads about this problem but i don't find any correct issues.
I understand that Hibernate can't mapped my class but i don't know why ...
Where could the problem come from ?
Thanks a lot.
Usually the problem is trivial: you should use javax.persistence.Entity instead of Hibernate-specific org.hibernate.annotations.Entity. The latter was deprecated in Hibernate in favour of JPA annotations where possible.
That's exactly what you didn't show, so hope it's a lucky shot :)

Spring's Java Based configuration not working for me

I am new to Spring programming and currently struggling with Spring 3.1's Java Based Configuraion" I have created following Configuration class
#Configuration
#ImportResource("classpath:/resources/jdbc.properties")
public class AppConfig {
#Autowired
Environment env;
private #Value("${jdbc.url}")
String url;
private #Value("${jdbc.username}")
String username;
private #Value("${jdbc.password}")
String password;
#Bean
public DataSource dataSource() {
System.out.println("Creating data Source.");
return new DriverManagerDataSource(url, username, password);
}
#Bean
public SessionFactory sessionFactory () throws Exception {
return new AnnotationSessionFactoryBuilder().setDataSource(dataSource()).setPackagesToScan("com.argusoft.loginmodule.domain").buildSessionFactory();
}
}
now when I try to run the project I get following error.
OUTPUT
SEVERE: Exception while loading the app :
java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException:
java.lang.IllegalArgumentException: javax.servlet.ServletException:
java.lang.NoClassDefFoundError:
org/springframework/core/env/EnvironmentCapable
stuck into it, Cant solve it..... I am following Spring Source Blog.
please also suggest some good tutorial in which Spring's latest Java based configuration is explained by easy to understand examples...
Thanks in advance,
From the perspective of the exception:
java.lang.NoClassDefFoundError: org/springframework/core/env/EnvironmentCapable
This question is equals to the question: Spring class EnvironmentCapable
So the correct answer might be:
I think that need use version 3.1.0 - in package
org.springframework.core-3.1.0.M2.jar this class presents.
given by user810430 here: original answer.
you can puth configuration like this
inside application context:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<import resource="db-config.xml" />
and
db-config.xml is:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver.className}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" autowire="byName">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="packagesToScan" value="com.huawei.sa.album" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- uncomment this for first time run-->
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:annotation-driven />
</beans>

Resources