JTDS tries (and fails) to recreate already-existing table on application start - sql-server

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.

Related

Why is CamelExchangesFailed_total metrics not increased?

I have a Apache Camel application which is monitored by Prometheus. Therefore, I added Micrometer to my POM (see Spring Boot Auto-Configuration) and MicrometerRoutePolicyFactory to my application (see Using Micrometer Route Policy Factory). But the metric CamelExchangesFailed_total doesn't change, althought a route failed.
Source
#SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
#Bean
public MicrometerRoutePolicyFactory micrometerRoutePolicyFactory() {
return new MicrometerRoutePolicyFactory();
}
#Bean
public EndpointRouteBuilder route() {
return new EndpointRouteBuilder() {
#Override
public void configure() throws Exception {
errorHandler(deadLetterChannel("log:dead"));
from(timer("testTimer").repeatCount(1)).throwException(new RuntimeException());
}
};
}
}
Logs
INFO 5060 --- [ restartedMain] o.a.c.i.e.InternalRouteStartupManager : Route: route1 started and consuming from: timer://testTimer
INFO 5060 --- [ restartedMain] o.a.c.impl.engine.AbstractCamelContext : Total 1 routes, of which 1 are started
INFO 5060 --- [ restartedMain] o.a.c.impl.engine.AbstractCamelContext : Apache Camel 3.5.0 (camel-1) started in 0.007 seconds
INFO 5060 --- [ restartedMain] test.TestApplication : Started TestApplication in 6.626 seconds (JVM running for 7.503)
INFO 5060 --- [on(3)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 5060 --- [on(3)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
INFO 5060 --- [on(3)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms
INFO 5060 --- [mer://testTimer] dead : Exchange[ExchangePattern: InOnly, BodyType: null, Body: [Body is null]]
Metrics
# HELP CamelExchangesFailed_total
# TYPE CamelExchangesFailed_total counter
CamelExchangesFailed_total{application="test",camelContext="camel-1",routeId="route1",serviceName="MicrometerRoutePolicyService",} 0.0
# HELP CamelExchangesSucceeded_total
# TYPE CamelExchangesSucceeded_total counter
CamelExchangesSucceeded_total{application="test",camelContext="camel-1",routeId="route1",serviceName="MicrometerRoutePolicyService",} 1.0
Resaerch
If I remove the custom error handler, the metric CamelExchangesFailed_total is increased, but then the default error handler is used, which is not desired for some reasons.
Question
Why is CamelExchangesFailed_total metrics not increased? Is there any way to count all failed routes with a custom error handler?
Apache Camel LTS version 3.7.0 added a new metric CamelExchangesFailuresHandled_total, which is a counter of handled errors, see CAMEL-15908:
Similar to CAMEL-15255, there are some additional counter metrics we could add to the MicrometerRoutePolicy for:
Total exchanges processed
Number of failures handled
Number of external redeliveries
Metrics
# HELP CamelExchangesFailed_total
# TYPE CamelExchangesFailed_total counter
CamelExchangesFailed_total{application="test",camelContext="camel-1",routeId="route1",serviceName="MicrometerRoutePolicyService",} 0.0
# HELP CamelExchangesSucceeded_total
# TYPE CamelExchangesSucceeded_total counter
CamelExchangesSucceeded_total{application="test",camelContext="camel-1",routeId="route1",serviceName="MicrometerRoutePolicyService",} 1.0
# HELP CamelExchangesFailuresHandled_total
# TYPE CamelExchangesFailuresHandled_total counter
CamelExchangesFailuresHandled_total{application="test",camelContext="camel-1",routeId="route1",serviceName="MicrometerRoutePolicyService",} 1.0

HHH000339: Could not obtain connection metadata net.snowflake.client.jdbc.SnowflakeLoggedFeatureNotSupportedException

Getting exception in spring boot while connecting snowflake:**
```2021-12-22 17:14:24.956 WARN 43624 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000339: Could not obtain connection metadata: net.snowflake.client.jdbc.SnowflakeLoggedFeatureNotSupportedException
net.snowflake.client.jdbc.SnowflakeLoggedFeatureNotSupportedException: null
at net.snowflake.client.jdbc.SnowflakeDatabaseMetaData.getSQLStateType(SnowflakeDatabaseMetaData.java:2774) ~[snowflake-jdbc-3.13.12.jar:3.13.12]```
Connection Details:
spring.datasource.password={}
spring.datasource.driverClassName=net.snowflake.client.jdbc.SnowflakeDriver
spring.datasource.url=jdbc:snowflake://{}.snowflakecomputing.com/?
private_key_file=&private_key_file_pwd=&db=&warehouse=&schema=public
spring.jpa.properties.hibernate.dialect=com.example.demo_snowflex_springboot.EmptyDialect
spring.jpa.properties.hibernate.jdbc.batch_size=10
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.hibernate.naming.physical- strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl```
I have downgraded the starter parent(spring-boot-starter-parent) version to 2.2.5.RELEASE and could make the connection. Not sure about the rootcause.
Try the following Configuration:
spring.datasource.username=${snowflake.username}
spring.datasource.password=${snowflake.password}
spring.datasource.driverClassName=net.snowflake.client.jdbc.SnowflakeDriver
spring.datasource.url=jdbc:snowflake://${snowflake.account}.snowflakecomputing.com/?warehouse=${snowflake.warehouse}&db=${snowflake.database.name}&schema=${snowflake.schema}&TIMEZONE=${snowflake.timezone:UTC}&CLIENT_RESULT_COLUMN_CASE_INSENSITIVE=true&CLIENT_TIMESTAMP_TYPE_MAPPING=TIMESTAMP_NTZ
spring.jpa.properties.hibernate.dialect=my.company.repositories.EmptyDialect
spring.jpa.properties.hibernate.jdbc.batch_size=10
spring.jpa.properties.hibernate.order_inserts=true

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...

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.

Persistence doesn't create table from entity in 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

Resources