Programatically setting the db url/user/password in Hibernate - java

I need to centralize all settings for our Java web application in one .properties file. I can still have hibernate.cfg.xml for adding mappings to entity classes but I need to keep all of our settings for the database and custom paths in one .properties file.
Originally I kept my configs in hibernate.cfg.xml as follows....
<?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>
<property name="connection.url">my jdbc connection</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.username">user</property>
<property name="connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.current_session_context_class">managed</property>
<mapping class="myEntityClass"/>
</session-factory>
</hibernate-configuration>
Now I want to move"connection.url", "connection.username", and "connection.password" to my own .properties file. The code for creating my hibernate configuration class went from.
new AnnotationConfiguration().configure();
to
new AnnotationConfiguration()
.setProperty("connection.url", databaseUrl)
.setProperty("connection.username", databaseUser)
.setProperty("connection.password", databasePassword)
.configure();
Which seemed conceptually simple. Unfortunately I get the following error when I try to use my Hibernate Session that worked with the previous config.
The user must supply a JDBC connection
Any ideas? It seems to me that when Hibernate sees these properties missing in the hibernate.cfg.xml file it assumes all settings will be manually added and ignore the xml altogether.

From the Hibernate Reference Documentation:
3.3. JDBC connections
[...]
The following is an example
hibernate.properties file for c3p0:
hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
Adapt it to suit your needs and put the hibernate.properties in the root of the class path (and remove the equivalent entries from the hibernate.cfg.xml as the XML configuration file overrides properties). So there is actually no need to change the following line:
new AnnotationConfiguration().configure();
Unless you really want a programmatic configuration of course.
But from the body of your question, moving to a .properties file is something else and you can rely on Hibernate: move the relevant properties from hibernate.cfg.xml to hibernate.properties.

Try setting following properties
properties.put("hibernate.connection.driver_class", "net.sourceforge.jtds.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:jtds:sqlserver://test/dbname;SSL=REQUEST");
properties.put("hibernate.connection.username", "user");
properties.put("hibernate.connection.password", "password");
properties.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
of course this is for SQL Server so you would need to change driver to 'org.gjt.mm.mysql.Driver"'
and change dialect as well 'org.hibernate.dialect.MySQLInnoDBDialect'

spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialize=true
spring.flyway.baseline-on-migrate=true
flyway.baseline-on-migrate: true
spring.flyway.baselineVersionAsString=2
spring.quartz.job-store-type=jdbc
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true

Related

How can I configure JPA for a postgres database schema?

I have an existing postgres database with the database "testdb" and the database schema testdbschema".
If I use the default persistence.xml configuration of RESOURCE_LOCAL the following property is working:
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://server:port/testdb?currentSchema=testdbschema" />
I want to configure my database connection within my web.xml as a data-source. Everything is working well, except the configuration of the database schema.
Here is my web.xml configuration:
<data-source>
<name>java:global/myapp</name>
<class-name>org.postgresql.ds.PGSimpleDataSource</class-name>
<server-name>127.0.0.1</server-name>
<port-number>5432</port-number>
<database-name>testdb</database-name>
<user>postgres</user>
<password>postgres</password>
</data-source>
Do you now how can I configure my db schema name here?
The configuration via testdb?currentSchema=testdbschema did not work for me and I get a database not found failure.
The solution was found within the PGSimpleDataSource:
<data-source>
<name>java:global/myapp</name>
<class-name>org.postgresql.ds.PGSimpleDataSource</class-name>
<server-name>127.0.0.1</server-name>
<port-number>5432</port-number>
<database-name>testdb</database-name>
<user>postgres</user>
<password>postgres</password>
<property>
<name>currentSchema</name>
<value>testdbschema</value>
</property>

org.h2.jdbc.JdbcSQLException: Table "ALL_SEQUENCES" not found

Could someone please tell me the reasons for the below error.
I am using Hibernate in my project and face the below error during server startup
15:04:27.909 [localhost-startStop-1] ERROR o.h.tool.hbm2ddl.SchemaValidator - HHH000319: Could not get database metadata
org.h2.jdbc.JdbcSQLException: Table "ALL_SEQUENCES" not found; SQL statement:
select sequence_name from all_sequences union select synonym_name from all_synonyms us, all_sequences asq where asq.sequence_name = us.table_name and asq.sequence_owner = us.table_owner [42102-168]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329) ~[h2-1.3.168.jar:1.3.168]
at org.h2.message.DbException.get(DbException.java:169) ~[h2-1.3.168.jar:1.3.168]
at org.h2.message.DbException.get(DbException.java:146) ~[h2-1.3.168.jar:1.3.168]
at org.h2.command.Parser.readTableOrView(Parser.java:4770) ~[h2-1.3.168.jar:1.3.168]
at org.h2.command.Parser.readTableFilter(Parser.java:1084) ~[h2-1.3.168.jar:1.3.168]
at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1690) ~[h2-1.3.168.jar:1.3.168]
This happens when you use either a wrong dialect in your persistence-unit inside your persistence.xml, or you validate against the wrong database. For example, when you run your application against a local H2 database, the best choice would be to remove the dialect, since Hibernate can recognize the database without this property (if the Version of Hibernate is new enough to recognize newer databases). Another solution would be to remove the validate attribute, but I would not recommend that, since you have no database checks at startup then:
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
</properties>
I used multiple dataSources
OracleDb1Configuration
#Primary
#Bean(name = "oracleDb1EntityManager")
public LocalContainerEntityManagerFactoryBean oracleDb1EntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(oracleDb1DataSource)
.properties(hibernateProperties())
.packages("com.fengxin58.user.ddd.domain.model.oracle.db1")//设置实体类所在位置
.persistenceUnit("oracleDb1PersistenceUnit")
.build();
}
private Map<String, Object> hibernateProperties() {
String env = monitorService.env();
if(log.isDebugEnabled()) {
log.debug("current profile: {}", env);
}
Resource resource = null;
if(EnvEnum.TEST.key().equals(env)) {
resource = new ClassPathResource("hibernate-oracle-db1-test.properties");
}else {
resource = new ClassPathResource("hibernate-oracle-db1.properties");
}
try {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
return properties.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue())
);
} catch (IOException e) {
return new HashMap<String, Object>();
}
}
hibernate-oracle-db1-test.properties
hibernate.hbm2ddl.auto=update
application-test.yml
oracle:
db1:
datasource:
url: jdbc:h2:mem:test
driver-class-name: org.h2.Driver
username: root
password:
db2:
datasource:
url: jdbc:h2:mem:test
driver-class-name: org.h2.Driver
username: root
password:
You have to ensure that the table and the sequence is created. If it is created, then it will work.
The table "ALL_SEQUENCES" is not created. Please check your database is it exists or not?
Your problem is the sequence is not created as well as the table is not created.
Solution:
Check your hibernate.cfg.xml. It is not configured well.
For your clarification, I have given a cfg file below:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:database/test</property>
<property name="connection.username">sa</property>
<property name="connection.password"/>
<property name="hibernate.default_schema">PUBLIC</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="au.com.ozblog.hibernate.h2.example.User"/>
</session-factory>
</hibernate-configuration>
In my case, I was using multiple datasources in my application, and using H2 for tests.
In this case, you have to set manually the dialect in JPA properties of the datasource, not via application.properties file.
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return builder
.dataSource(ds)
.packages("com.application.demo")
.properties(properties)
.persistenceUnit("persitenceUnit1")
.build();
In every datasource used.
In case it can help someone.
regards

Eclipse and Hibernate - faster and easier way to add mapping items in hibernate.cfg.xml

I'm having a problem lately with adding mapping items to my hibernate.cfg.xml file. Just to be clear, It's not a mystery for me how to generate mapping anotations and all, but the process of adding these classes to hibernate.cfg.xml file just takes too long. For instance, "Hibernate Configuration 3.0 XML Editor" has a bult-in function to add mapping item in "Session Factory" tab. Sadly, you can add a class once on a time, which means going back to "Session Factory" tab, hitting "add" button in mapping section and choosing another class from the list.
Ex.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.password">***********</property> <-don't mind this
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/dvdrental</property>
<property name="hibernate.connection.username">postgres</property>
<mapping class="Model.Actor"/> <- here's the problem. Can you generate this automatically?
</session-factory>
</hibernate-configuration
>
Is there a more dynamic way to do this in eclipse? Couldn't "hibernate.cfg.xml" file be updated after I generated java files via "Hibernate Code Generation Configurations"? Am I missing something?
P.S. I'm not using Spring at the moment.

Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/domain

Hello I'm using the following
hibernate-core-4.1.2.Final.jar
mysql-connector-5.1.6.jar
Both can be found in my project lib directory.
I have the following hibernate.cg.xml configuration.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Defines the SQL dialect used in Hiberante's application -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--Local Database Connection-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/domain</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">test</property>
<property name="hbm2ddl.auto">validate</property>
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<property name="use_sql_comments">false</property>
<property name="hibernate.search.default.directory_provider">ram</property>
</session-factory>
</hibernate-configuration>
and I'm getting the following exception.
Caused by: java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/domain at
java.sql.DriverManager.getConnection(DriverManager.java:604) at
java.sql.DriverManager.getConnection(DriverManager.java:190) at
org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:192)
at
org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:278)
at
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
... 145 more
I do not want to use JNDI do to the fact management wants to keep the app as portable as possible, so what am I missing to get this to work with jdbc? Am I required to do any kind of configurations to tomcat?
Tomcat Lib
Try putting mysql-connector-5.1.6.jar directly into the lib folder of tomcat and restarting it.
Have you tried calling the driver class?:
Class.forName("com.mysql.jdbc.Driver");
How to call it:
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
// error out
}
Connection con = DriverManager.getConnection(/*your connection query*/);
I may have the class wrong, but if com.mysql.jdbc.Driver doesn't work, you can also try com.mysql.JDBC or com.mysql.jdbc (basing off how SQLite calls it)
Did you edit the config to obscure the connection string?
Your hibernate config has a different database name than the error:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/domain</property>
Caused by: java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/etss
In terms of portability, I package the database driver with my war, so it is self contained. This makes for deployment across multiple environments much easier and if another developer wants to build and run locally, they just have to drop the war into Tomcat and go. Place the database driver in your WEB-INF/lib folder.
Also, in terms portability, I recommend JNDI... that way you do not have to edit your hibernate config file when you deploy it to another server and it can stay packaged in your war. You just add the JNDI reference in the Tomcat config.
The exception occurs because the mysql database driver is not on your classpath. Add it to your classpath to repair the issue. Since you are using tomcat you can simply add it to the tomcat/lib directory.
I would suggest putting your drivers in/at where you have place JDK's Extension directory. Please see:http://www3.ntu.edu.sg/home/ehchua/programming/howto/ErrorMessages.html#zz-4.1
Once that is done I would encourage you to from your prompt type:
echo %CLASSPATH%

How to set Hibernate with sqlserver&jtds driver in Netbeans

I am trying to set up Netbeans to work with Hibernate using jtds driver to connect to SQLSERVER 2008.
The sqlserver 2008 is installed localy, no username or password.
This is hibernate.cfg:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
<property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:2545/MyDB</property>
</session-factory>
</hibernate-configuration>
When I try to setup Hibernate reverse engineering file with Hibernate reverse engineering wizard, I get the following error:
Unable to connect. Cannot establish a connection to
jdbc:jtds:sqlserver://localhost:2545/MyDB using
net.sourceforge.jtds.jdbc.Driver (I/O Error: SSO Failed: Native SSPI
library not loaded. Check the java.library.path system property.).
I have ntlmauth.dll in WINDOWS\system32.
jdbc:jtds:sqlserver://localhost:2545/MyDB appears to be an incomplete JDBC URL for the jTDS driver.
Going by the jTDS FAQ, you'll need to specify the username and password properties as well. Also, since you appear to be using integrated Windows authentication in MS SQL Server 2008, you would also need to set the domain property.
Note that, the username and password values will have to be provided unless you install the jTDS SSO library i.e. ntlmauth.dll; since you already have it in your PATH, you'll need to specify the domain property to login as the currently logged in user on the workstation.

Categories