Persistence doesn't create table from entity in database - database
I build a web application using hibernate JPA 2 + spring. I have problem with creation of domain model. In persistence I declared the automatic creation of database tables from entity. Here is my persistence.xml file:
<persistence-unit name="basicPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
</properties>
</persistence-unit>
In domain model I have two classes. One Is abstract which provide the persistence properties to inherited classes:
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.type.UUIDBinaryType;
import javax.persistence.*;
#MappedSuperclass
abstract class AbstractDomainObject implements DomainObject {
private static final long serialVersionUID = 1L;
private UUIDBinaryType id;
private Long version;
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid")
#Column(length = 16, unique = true, nullable = false)
public final UUIDBinaryType getId() {
return id;
}
public final void setId(UUIDBinaryType id) {
this.id = id;
}
#Version
public final Long getVersion() {
return version;
}
public final void setVersion(Long version) {
this.version = version;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AbstractDomainObject)) return false;
AbstractDomainObject that = (AbstractDomainObject) o;
return !(id != null ? !id.equals(that.id) : that.id != null) &&
!(version != null ? !version.equals(that.version) : that.version != null);
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
Here is the concrete class which represent the entity:
import javax.persistence.Entity;
#Entity
public class Person extends AbstractDomainObject {
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private Integer identifier;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Integer getIdentifier() {
return identifier;
}
public void setIdentifier(Integer identifier) {
this.identifier = identifier;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
if (!super.equals(o)) return false;
Person test = (Person) o;
return !(name != null ? !name.equals(test.name) : test.name != null) &&
!(surname != null ? !surname.equals(test.surname) : test.surname != null) &&
!(identifier != null ? !identifier.equals(test.identifier) : test.identifier != null);
}
#Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (surname != null ? surname.hashCode() : 0);
result = 31 * result + (identifier != null ? identifier.hashCode() : 0);
return result;
}
}
Here is the interface which I'm using in abstract class:
import org.hibernate.type.UUIDBinaryType;
import java.io.Serializable;
public interface DomainObject extends Serializable {
UUIDBinaryType getId();
void setId(UUIDBinaryType id);
Long getVersion();
void setVersion(Long version);
boolean equals(Object o);
int hashCode();
}
And here is the log from tomcat with debug mode:
Jun 28, 2011 6:23:32 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive webFrontend-1.0-SNAPSHOT.war
2011-06-28 18:23:33,495 [Thread-29] INFO org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
2011-06-28 18:23:33,530 [Thread-29] INFO org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Tue Jun 28 18:23:33 CEST 2011]; root of context hierarchy
2011-06-28 18:23:33,583 [Thread-29] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:/opt/apache-tomcat-7.0.16/webapps/webFrontend-1.0-SNAPSHOT/WEB-INF/classes/META-INF/spring/applicationContext.xml]
2011-06-28 18:23:33,709 [Thread-29] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:/opt/apache-tomcat-7.0.16/webapps/webFrontend-1.0-SNAPSHOT/WEB-INF/classes/META-INF/spring/basicDataSource.xml]
2011-06-28 18:23:33,722 [Thread-29] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:/opt/apache-tomcat-7.0.16/webapps/webFrontend-1.0-SNAPSHOT/WEB-INF/classes/META-INF/spring/applicationContext-persistence.xml]
2011-06-28 18:23:33,909 [Thread-29] INFO org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from file [/opt/apache-tomcat-7.0.16/webapps/webFrontend-1.0-SNAPSHOT/WEB-INF/classes/META-INF/spring/database.properties]
2011-06-28 18:23:33,929 [Thread-29] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2863725d: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,basicDataSource,PersonDao,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,entityManagerFactory,transactionManager,org.springframework.transaction.config.internalTransactionAspect]; root of factory hierarchy
2011-06-28 18:23:33,995 [Thread-29] INFO org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'basicPersistenceUnit'
2011-06-28 18:23:34,153 [Thread-29] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
2011-06-28 18:23:34,160 [Thread-29] INFO org.hibernate.cfg.Environment - Hibernate 3.6.3.Final
2011-06-28 18:23:34,161 [Thread-29] INFO org.hibernate.cfg.Environment - hibernate.properties not found
2011-06-28 18:23:34,164 [Thread-29] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
2011-06-28 18:23:34,167 [Thread-29] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
2011-06-28 18:23:34,243 [Thread-29] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.6.3.Final
2011-06-28 18:23:34,261 [Thread-29] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
name: basicPersistenceUnit
...]
2011-06-28 18:23:34,359 [Thread-29] INFO org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
2011-06-28 18:23:34,373 [Thread-29] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
2011-06-28 18:23:34,376 [Thread-29] INFO org.hibernate.connection.ConnectionProviderFactory - Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
2011-06-28 18:23:34,378 [Thread-29] INFO org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider - Using provided datasource
2011-06-28 18:23:34,666 [Thread-29] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2011-06-28 18:23:34,717 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Database ->
name : MySQL
version : 5.0.51a-24+lenny5
major : 5
minor : 0
2011-06-28 18:23:34,722 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Driver ->
name : MySQL-AB JDBC Driver
version : mysql-connector-java-5.1.16 ( Revision: ${bzr.revision-id} )
major : 5
minor : 1
2011-06-28 18:23:34,723 [Thread-29] INFO org.hibernate.transaction.TransactionFactoryFactory - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
2011-06-28 18:23:34,725 [Thread-29] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
2011-06-28 18:23:34,725 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
2011-06-28 18:23:34,725 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
2011-06-28 18:23:34,725 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
2011-06-28 18:23:34,725 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
2011-06-28 18:23:34,726 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
2011-06-28 18:23:34,728 [Thread-29] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
2011-06-28 18:23:34,728 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
2011-06-28 18:23:34,728 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: enabled
2011-06-28 18:23:34,728 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
2011-06-28 18:23:34,728 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
2011-06-28 18:23:34,728 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
2011-06-28 18:23:34,729 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
2011-06-28 18:23:34,730 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
2011-06-28 18:23:34,733 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
2011-06-28 18:23:34,734 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
2011-06-28 18:23:34,734 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
2011-06-28 18:23:34,734 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
2011-06-28 18:23:34,734 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
2011-06-28 18:23:34,734 [Thread-29] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
2011-06-28 18:23:34,747 [Thread-29] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
2011-06-28 18:23:34,753 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_characters_clob] overrides previous : org.hibernate.type.CharacterArrayClobType#32ee7cee
2011-06-28 18:23:34,753 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [characters_clob] overrides previous : org.hibernate.type.PrimitiveCharacterArrayClobType#474c0761
2011-06-28 18:23:34,753 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [clob] overrides previous : org.hibernate.type.ClobType#507895d8
2011-06-28 18:23:34,753 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Clob] overrides previous : org.hibernate.type.ClobType#507895d8
2011-06-28 18:23:34,753 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [blob] overrides previous : org.hibernate.type.BlobType#1cb5c12e
2011-06-28 18:23:34,754 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Blob] overrides previous : org.hibernate.type.BlobType#1cb5c12e
2011-06-28 18:23:34,754 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [materialized_clob] overrides previous : org.hibernate.type.MaterializedClobType#609dc1bb
2011-06-28 18:23:34,754 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_materialized_blob] overrides previous : org.hibernate.type.WrappedMaterializedBlobType#151a0d8b
2011-06-28 18:23:34,754 [Thread-29] INFO org.hibernate.type.BasicTypeRegistry - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType#616f2b7f
2011-06-28 18:23:34,803 [Thread-29] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
2011-06-28 18:23:34,822 [Thread-29] INFO org.hibernate.tool.hbm2ddl.SchemaExport - Running hbm2ddl schema export
2011-06-28 18:23:34,822 [Thread-29] INFO org.hibernate.tool.hbm2ddl.SchemaExport - exporting generated schema to database
2011-06-28 18:23:34,827 [Thread-29] INFO org.hibernate.tool.hbm2ddl.SchemaExport - schema export complete
2011-06-28 18:23:34,934 [Thread-29] INFO org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1438 ms
2011-06-28 18:23:34,962 [Thread-29] INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'webFrontendDispatcher': initialization started
2011-06-28 18:23:34,965 [Thread-29] INFO org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'webFrontendDispatcher-servlet': startup date [Tue Jun 28 18:23:34 CEST 2011]; parent: Root WebApplicationContext
2011-06-28 18:23:34,967 [Thread-29] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/web-config.xml]
2011-06-28 18:23:35,083 [Thread-29] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#391c3288: defining beans [org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.config.viewControllerHandlerAdapter,org.springframework.web.servlet.config.viewControllerHandlerMapping]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#2863725d
2011-06-28 18:23:35,299 [Thread-29] INFO org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/index.jsp] onto handler of type [class org.springframework.web.servlet.mvc.ParameterizableViewController]
2011-06-28 18:23:35,385 [Thread-29] INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'webFrontendDispatcher': initialization completed in 422 ms
There is no error in this log and there is information about schema export was completely, but the table Person isn't created in database. Do I anything in wrong way?
Please try
<prop key="hibernate.hbm2ddl.auto">update</prop>
It will update ecisting schema and create the new one of it does not exist.
I'm working with MySQL too and haven't got any problem with that.
I solve this problem, I add tag to my persistence.xml file which contain class name of class which has #Entity annotation. But why I must add class like this way? In spring roo when I generate code, there is no tags in persistence.xml file
I had this problem because I named an entity "Group" which is a reserved word in MySQL (the database I was using: https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html). I had to choose a different name for my entity/table/JSON object. I could see this in the Hibernate Output on startup as follows:
o.h.SQL: drop table if exists Group
o.h.t.h.SchemaExport: HHH000389: Unsuccessful: drop table if exists Group
o.h.t.h.SchemaExport: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Group' at line 1
Hibernate was otherwise silent on the problem...I think because reserved words are a bit of a swamp, though the Hibernate driver should pick it up.
Note:
the hibernate output is defined like this:
hibernate.show_sql : true
And the hibernate dialect (which ultimately determines the reserved words is defined like this:
hibernate.dialect: org.hibernate.dialect.MySQL5InnoDBDialect
Related
how to extract data from ElementCollection
I am trying to extract data from an ElementCollection that is contained in StandartFont. public class DBFonts { #Id #GeneratedValue(strategy= GenerationType.AUTO) private long id; private String nameFont; #ElementCollection #CollectionTable( name="StandartFont", joinColumns=#JoinColumn(name="Fonts_id") #Lob #Basic(fetch = FetchType.LAZY) #Column(length=100000) private List<byte[]> StandartFonts; } Repository: public interface FontRepo extends JpaRepository<DBFonts,Long> { List<byte[]> findByStandartFonts(Long fonsId); } HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect Hibernate: alter table font add constraint FKpcplr5ixrmh5lbjx0e6peoqo4 foreign key (user_id) references usr (id) Hibernate: alter table standart_font add constraint FKq7nxy6see56tp2y997fwmsewq foreign key (fonts_id) references font (id) 2018-12-06 16:15:54.338 INFO 6168 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2018-12-06 16:15:54.884 WARN 6168 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addFont': Unsatisfied dependency expressed through field 'fontRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fontRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List spring_mvc.entity.FontRepo.findByStandartFonts(java.lang.Long)! Unable to locate Attribute with the the given name [standartFonts] on this ManagedType [spring_mvc.entity.DBFonts] 2018-12-06 16:15:54.884 INFO 6168 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 2018-12-06 16:15:54.886 INFO 6168 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2018-12-06 16:15:54.896 INFO 6168 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed. 2018-12-06 16:15:54.898 INFO 6168 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2018-12-06 16:15:54.916 INFO 6168 --- [ restartedMain] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2018-12-06 16:15:54.928 ERROR 6168 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addFont': Unsatisfied dependency expressed through field 'fontRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fontRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List spring_mvc.entity.FontRepo.findByStandartFonts(java.lang.Long)! Unable to locate Attribute with the the given name [standartFonts] on this ManagedType [spring_mvc.entity.DBFonts] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.5.RELEASE.jar:2.0.5.RELEASE] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fontRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List spring_mvc.entity.FontRepo.findByStandartFonts(java.lang.Long)! Unable to locate Attribute with the the given name [standartFonts] on this ManagedType [spring_mvc.entity.DBFonts] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE] It does not work, how to extract data correctly? Will it work?: select standart_fonts FROM standart_font where fonts_id=? How to write this in #Query
Spring cant find attribute with name standartFonts in your class DBFonts and that's why it can't create been with your repository Unable to locate Attribute with the the given name [standartFonts] on this ManagedType [spring_mvc.entity.DBFonts] Spring using reflection get method name (findByStandartFonts) from your repository and parse it: findBy its means select and StandartFonts spring parse as standartFonts and it try to find this field in your #Entity PS. In id field, please, use Long instead of long. It's good practice. And use camelCase in your java code...
JTDS tries (and fails) to recreate already-existing table on application start
I'm trying to write an application to connect to a MS SQL Server database. The database already exists, the tables are already configured. All I want to do is to connect my Java Spring app to the already-existing server. However, when I try to do so, I get this error: Caused by: java.sql.SQLException: There is already an object named 'Customer' in the database. at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372) ~[jtds-1.3.1.jar:1.3.1] at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988) ~[jtds-1.3.1.jar:1.3.1] at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421) ~[jtds-1.3.1.jar:1.3.1] at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671) ~[jtds-1.3.1.jar:1.3.1] at net.sourceforge.jtds.jdbc.JtdsStatement.processResults(JtdsStatement.java:613) ~[jtds-1.3.1.jar:1.3.1] at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQL(JtdsStatement.java:572) ~[jtds-1.3.1.jar:1.3.1] at net.sourceforge.jtds.jdbc.JtdsStatement.executeImpl(JtdsStatement.java:809) ~[jtds-1.3.1.jar:1.3.1] at net.sourceforge.jtds.jdbc.JtdsStatement.execute(JtdsStatement.java:1282) ~[jtds-1.3.1.jar:1.3.1] at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.1.10.Final.jar:5.1.10.Final] ... 87 common frames omitted It seems like JTDS is trying to recreate my Customer table, and indeed if I delete the table and then run the application, it does indeed create a new table in my database called "Customer". However, I can't drop my table on every application start (for obvious reasons) so I need to configure my application to connect to a table which already exists. How do I do this? Database appconfig: #Configuration #EnableJpaRepositories #EntityScan("com.example.dbentity") public class AppConfig { #Value("${db.driver.class.name}") private String dbDriverClassName; #Value("${db.prefix}") private String dbPrefix; #Value("${db.url}") private String dbUrl; #Value("${db.name}") private String dbName; #Value("${db.username}") private String dbUsername; #Value("${db.password}") private String dbPassword; #Bean public DataSource DataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(dbDriverClassName); String connectionUrl = dbPrefix + dbUrl + "/" +dbName; dataSource.setUrl(connectionUrl); dataSource.setUsername(dbUsername); dataSource.setPassword(dbPassword); return dataSource; } #Bean public JdbcTemplate JdbcTemplate() { JdbcTemplate template = new JdbcTemplate(); template.setDataSource(DataSource()); return template; } #Bean public EntityManagerFactory entityManagerFactory() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("com.example.dbentity"); factory.setDataSource(DataSource()); factory.afterPropertiesSet(); return factory.getObject(); } #Bean public PlatformTransactionManager transactionManager() { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory()); return txManager; } } Configuration YAML: spring: application: name: sample-application jpa: hibernate: ddl-auto: validate server: port: 8080 max-http-header-size: 65536 db: driver: class: name: net.sourceforge.jtds.jdbc.Driver prefix: jdbc:jtds:sqlserver:// url: example-server.net:1433 name: example-db username: user password: password Hibernate output: 2018-07-13 10:57:56.831 INFO 15336 --- [ main] o.s.j.d.DriverManagerDataSource : Loaded JDBC driver: net.sourceforge.jtds.jdbc.Driver 2018-07-13 10:57:56.882 INFO 15336 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 2018-07-13 10:57:56.901 INFO 15336 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: default ...] 2018-07-13 10:57:57.002 INFO 15336 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.1.10.Final} 2018-07-13 10:57:57.002 INFO 15336 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 2018-07-13 10:57:57.006 INFO 15336 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist 2018-07-13 10:57:57.060 INFO 15336 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 2018-07-13 10:57:57.531 INFO 15336 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect 2018-07-13 10:57:57.672 INFO 15336 --- [ main] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 2018-07-13 10:57:58.754 WARN 15336 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement Thanks.
There is a property for Hibernate called ddl-auto where you can set whether Hibernate will create the schema on start, validate the schema that's already there, or do no validation of the existing schema. What you want to do is to just use validate (or none). See here for how to configure this in Spring Boot and here (i.e. the hibernateProperties) for how to do this in Vanilla Spring.
PlayFramework accessing secondary database data with jpa/hibernate
I am trying to connect second db to my webapplication written in PlayFramework2. I've configured correctly my app. I've added already second source callec crm. Here is my console log: --- (RELOAD) --- [info] play - datasource [jdbc:mysql://localhost/svp] bound to JNDI as DefaultDS [info] play - datasource [jdbc:mysql://192.168.0.4/scrm_customer] bound to JNDI as CRM [info] play - database [default] connected at jdbc:mysql://localhost/svp [info] play - database [CRM] connected at jdbc:mysql://192.168.0.4/scrm_customer [info] play - Application started (Dev) I've added to my persistence.xml following: <persistence-unit name="CRM" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <non-jta-data-source>CRM</non-jta-data-source> </persistence-unit> and my configuration for that: db.default.jndiName=DefaultDS db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://localhost/svp" db.default.user=root db.CRM.jndiName=CRM db.CRM.driver=com.mysql.jdbc.Driver db.CRM.url="jdbc:mysql://192.168.0.4/scrm_customer" db.CRM.user=root db.default.logStatements=true jpa.default=defaultPersistenceUnit But when I am trying to get some data from second db using code as follow: List<Customer> allCustomers = (List<Customer>) JPA.em("CRM") .createQuery("FROM Customer", Customer.class) .getResultList(); I am getting an error: [error] play - Cannot invoke the action, eventually got an error: java.lang.RuntimeException: No JPA EntityManagerFactory configured for name [CRM] [error] application - ! #6kd0136e7 - Internal server error, for (GET) [/SupraADMIN/klienci] -> play.api.Application$$anon$1: Execution exception[[RuntimeException: No JPA EntityManagerFactory configured for name [CRM]]] at play.api.Application$class.handleError(Application.scala:293) ~[play_2.10-2.2.4.jar:2.2.4] at play.api.DefaultApplication.handleError(Application.scala:399) [play_2.10-2.2.4.jar:2.2.4] at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$3.apply(PlayDefaultUpstreamHandler.scala:264) [play_2.10-2.2.4.jar:2.2.4] at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$3.apply(PlayDefaultUpstreamHandler.scala:264) [play_2.10-2.2.4.jar:2.2.4] at scala.Option.map(Option.scala:145) [scala-library.jar:na] at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3.applyOrElse(PlayDefaultUpstreamHandler.scala:264) [play_2.10-2.2.4.jar:2.2.4] Caused by: java.lang.RuntimeException: No JPA EntityManagerFactory configured for name [CRM] at play.db.jpa.JPA.em(JPA.java:34) ~[play-java-jpa_2.10-2.2.4.jar:2.2.4] at models.Customer.getCRMList(Customer.java:124) ~[na:na] at controllers.admin.CMS.Customers(CMS.java:157) ~[na:na] at admin.Routes$$anonfun$routes$1$$anonfun$applyOrElse$24$$anonfun$apply$24.apply(routes_routing.scala:429) ~[na:na] at admin.Routes$$anonfun$routes$1$$anonfun$applyOrElse$24$$anonfun$apply$24.apply(routes_routing.scala:429) ~[na:na] at play.core.Router$HandlerInvoker$$anon$7$$anon$2.invocation(Router.scala:183) ~[play_2.10-2.2.4.jar:2.2.4] [error] application - REGUEST: GET /SupraADMIN/klienci GENERATED ERROR: #6kd0136e7: Execution exception in /home/korbeldaniel/Aplikacje/Eclipse/SVP/modules/common/app/models/Customer.java:124 What do I miss? I've checked official documentation, but nothing usefull found. Please help
Annotate your controller method with following annotation: #Transactional(value = "CRM", readOnly = true) and within controller method perform: JPA.em().createQuery("FROM Customer", Customer.class).getResultList(); Or if you dont want to use annotation: List<Customer> customers = JPA.withTransaction("CRM", true, new Function0<List<Customer>>() { #Override public List<Customer> apply() throws Throwable { return JPA.em().createQuery("FROM Customer", Customer.class).getResultList(); } }); I would strongly recommend using JPA.withTransactionAsync instead.
using Hibernate and MS SQL with intelliJ IDEA
I am using Hibernate/JPA 2.0 with SQL Server and IntelliJ IDEA here's a sample code I made to test the connection: public class App { public static final String SELECT_QUERY = "select u from UsersEntity as u where u.userId = :userId"; public static void main(String[] args) { String userId = "1"; PersistenceProvider persistenceProvider = new HibernatePersistence(); EntityManagerFactory entityManagerFactory = persistenceProvider.createEntityManagerFactory("newPersistenceUnit", new HashMap()); EntityManager entityManager = entityManagerFactory.createEntityManager(); List<UsersEntity> users = entityManager.createQuery(SELECT_QUERY, UsersEntity.class).setParameter("userId", userId).getResultList(); System.out.println(users); entityManager.close(); } } And here's what I receive in the console: "C:\Program Files\Java\jdk1.6.0_29\bin\java" -Didea.launcher.port=7539 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 12.0.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.6.0_29\jre\lib\alt-rt.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\alt-string.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\jce.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\resources.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\rt.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunpkcs11.jar;D:\mobitrack\out\production\web;D:\mobitrack\lib\javax.persistence.jar;D:\mobitrack\lib\hibernate-entitymanager-4.2.0.Final.jar;D:\mobitrack\lib\jboss-logging-3.1.0.GA.jar;D:\mobitrack\lib\hibernate-core-4.2.0.Final.jar;D:\mobitrack\lib\antlr-2.7.7.jar;D:\mobitrack\lib\jboss-transaction-api_1.1_spec-1.0.0.Final.jar;D:\mobitrack\lib\dom4j-1.6.1.jar;D:\mobitrack\lib\hibernate-jpa-2.0-api-1.0.1.Final.jar;D:\mobitrack\lib\javassist-3.15.0-GA.jar;D:\mobitrack\lib\hibernate-commons-annotations-4.0.1.Final.jar;D:\mobitrack\lib\tools.jar;D:\mobitrack\lib\sqljdbc4-4.0.2206.100.jar;C:\Program Files\JetBrains\IntelliJ IDEA 12.0.4\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.mobitrack.services.App 26 mars 2013 17:44:18 org.hibernate.annotations.common.Version <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final} 26 mars 2013 17:44:18 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.2.0.Final} 26 mars 2013 17:44:18 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 26 mars 2013 17:44:18 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist 26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!) 26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000115: Hibernate connection pool size: 20 26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000006: Autocommit mode: true 26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://localhost:1433;databaseName=MOBITRACKDB] 26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000046: Connection properties: {user=sa, password=****, autocommit=true, release_mode=auto} When debugging I found that it stops at: EntityManagerFactory entityManagerFactory = persistenceProvider.createEntityManagerFactory("newPersistenceUnit", new HashMap()); Knowing that "newPersistenceUnit" is the name of my persistence unit. Edit: Yes it works outside IDEA. And when I use the console in IDEA to query the data it works. I tried using the next code: public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } I receive the same as above and the debugging stops at : sessionFactory = new Configuration().configure().buildSessionFactory(); Edit2: I used an EntityManager: EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("newPersistenceUnit"); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); List<AdminsEntity> result = entityManager.createQuery( "from AdminsEntity", AdminsEntity.class ).getResultList(); for ( AdminsEntity event : result ) { logged = event; } entityManager.getTransaction().commit(); entityManager.close(); return logged; It stops at: EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("newPersistenceUnit"); here is my persistence.xml: <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <persistence-unit name="newPersistenceUnit"> <class>com.mobitrack.entities.GroupsEntity</class> <class>com.mobitrack.entities.ZonesEntity</class> <class>com.mobitrack.entities.AdminsEntity</class> <class>com.mobitrack.entities.AlarmsEntity</class> <class>com.mobitrack.entities.LocationsEntity</class> <class>com.mobitrack.entities.UsersEntity</class> <class>com.mobitrack.entities.UserGroupsEntity</class> <class>com.mobitrack.entities.UserZonesEntity</class> <class>com.mobitrack.entities.SettingsEntity</class> <class>com.mobitrack.entities.MessagesEntity</class> <class>com.mobitrack.entities.ProfilesEntity</class> <class>com.mobitrack.entities.ProfileZonesEntity</class> <properties> <property name="hibernate.connection.url" value="jdbc:sqlserver://localhost:1433;databaseName=MOBITRACKDB"/> <property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/> <property name="hibernate.connection.username" value="admin"/> <property name="hibernate.connection.password" value="password"/> <property name="hibernate.query.factory_class" value="org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory"/> </properties> </persistence-unit> Any ideas?
This problem can be caused by the method breakpoints that slow down debugger. Please double check that you don't have any method breakpoints set. Disabling toString() evaluation and alternate collections view options in Settings | Debugger may also improve its performance.
OpenEJB 4.5.1: NameNotFoundException
Its the first time I used the OpenEJB container system. When I use the lockup-Method of the InitialContext, I get a NameNotFoundException. I've read lots of examples and tutorials and in every example the lookup method looks like: initialContext.lookup("NameOfBean"); Now I've found another solution which uses the lookup like the following code snippet which works for me too. initialContext.lookup("java:global/classpath.ear/ProjectName/NameofBean"); The question is why the first version doesn't work for me and what I've done wrong? Excerpts of the OpenEJB log: INFO - ******************************************************************************** INFO - OpenEJB http://openejb.apache.org/ INFO - Startup: Sat Dec 22 13:17:59 CET 2012 INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved. INFO - Version: 4.5.1 INFO - Build date: 20121209 INFO - Build time: 08:47 INFO - ******************************************************************************** INFO - openejb.home = D:\workspace\ProjectName INFO - openejb.base = D:\workspace\ProjectName INFO - Succeeded in installing singleton service INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed. INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service) INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager) INFO - Using 'openejb.deployments.classpath.include=.*' INFO - Found EjbModule in classpath: D:\workspace\ProjectName\build\classes INFO - Searched 17 classpath urls in 2184 milliseconds. Average 128 milliseconds per url. INFO - Beginning load: D:\workspace\ProjectName\build\classes INFO - Configuring enterprise application: D:\workspace\ProjectName\classpath.ear WARNUNG - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime. INFO - Auto-deploying ejb NameOfBean: EjbDeployment(deployment-id=NameOfBean) [... AUTHORS'S NOTE: SOME MORE BEANS] INFO - Assembling app: D:\workspace\ProjectName\classpath.ear INFO - Hibernate Validator 4.2.0.Final INFO - Ignoring XML configuration. JAVA AGENT NOT INSTALLED. The JPA Persistence Provider requested installation of a ClassFileTransformer which requires a JavaAgent. See http://openejb.apache.org/3.0/javaagent.html INFO - OpenJPA dynamically loaded a validation provider. INFO - Jndi(name=NameOfBeanRemote) --> Ejb(deployment-id=NameofBean) INFO - Jndi(name=global/classpath.ear/ProjectName/NameOfBean!de.mypath.stateless.NameOfBeanInterface) --> Ejb(deployment-id=NameofBean) INFO - Jndi(name=global/classpath.ear/ProjectName/NameofBean) --> Ejb(deployment-id=NameOfBean) [... AUTHORS'S NOTE: SOME FOR OTHER BEANS] INFO - OpenWebBeans Container is starting... INFO - Adding OpenWebBeansPlugin : [CdiPlugin] INFO - All injection points are validated successfully. INFO - OpenWebBeans Container has started, it took 250 ms. INFO - Created Ejb(deployment-id=NameOfBean, ejb-name=NameOfBean, container=Default Stateless Container) [... AUTHORS'S NOTE: SOME FOR OTHER BEANS] INFO - Quartz scheduler 'OpenEJB-TimerService-Scheduler' initialized from an externally provided properties instance. INFO - Quartz scheduler version: 2.1.6 INFO - Scheduler OpenEJB-TimerService-Scheduler_$_OpenEJB started. INFO - Started Ejb(deployment-id=NameOfBean, ejb-name=NameOfBean, container=Default Stateless Container) [... AUTHORS'S NOTE: SOME FOR OTHER BEANS] This is my TestClass: public class NamerOfBeanOpenEJBTest { private static InitialContext initialContext; #BeforeClass public static void setUp() throws Exception { Properties properties = new Properties(); properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory"); properties.setProperty("openejb.deployments.classpath.include", ".*"); initialContext = new InitialContext(properties); } #Test public void testBean() throws NamingException{ Object object = initialContext.lookup("java:global/classpath.ear/ProjectName/NameOfBean"); assertNotNull(object); assertTrue(object instanceof NameOfBean); } #AfterClass public static void afterClass() throws Exception { if (initialContext != null) { initialContext.close(); }} } Does someone have tipps or solutions for me? Thanks a lot. Edit: In JBoss AS 7.1 the lookup can places like this example: new InitialContext().lookup("ejb:/ProjectName//NameOfBean!de." + "mypath.sessionbean.stateless.NameOfBeanInterface"); Isnt that possible in OpenEJB? Do I have to change every lookup call in every bean to have a local test with OpenEJB? That wouldn't be really effective and time-saving.
Problem solved! The strukture of the lookup is {deploymentId}{interfaceType.annotationName}. Therefore in my case it must be initialContext.lookup("NameOfBeanLocal"); or initialContext.lookup("NameOfBeanRemote"); depending on the type of the interface. To get the problem with JBoss solved you can switch from default lookup new InitialContext().lookup("ejb:/ProjectName//NameOfBean!de." + "mypath.sessionbean.stateless.NameOfBeanInterface"); to something more flexible like Dependcy-Lookup or Dependency-Injection and use the #EJB annotation. Both ways are supportet by JBoss and OpenEJB.