How to set up default schema name in JPA configuration? - java

I found that in hibernate config file we could set up parameter hibernate.default_schema:
<hibernate-configuration>
<session-factory>
...
<property name="hibernate.default_schema">myschema</property>
...
</session-factory>
</hibernate-configuration>
Now I'm using JPA and I want to do the same. Otherwise I have to add parameter schema to each #Table annotation like:
#Entity
#Table (name = "projectcategory", schema = "SCHEMANAME")
public class Category implements Serializable { ... }
As I understand this parameter should be somewhere in this part of configuration:
<bean id="domainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JiraManager"/>
<property name="dataSource" ref="domainDataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false"/>
<property name="showSql" value="false"/>
<property name="databasePlatform" value="${hibernate.dialect}"/>
</bean>
</property>
</bean>
<bean id="domainDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${db.driver}" />
<property name="jdbcUrl" value="${datasource.url}" />
<property name="user" value="${datasource.username}" />
<property name="password" value="${datasource.password}" />
<property name="initialPoolSize" value="5"/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="15"/>
<property name="checkoutTimeout" value="10000"/>
<property name="maxStatements" value="150"/>
<property name="testConnectionOnCheckin" value="true"/>
<property name="idleConnectionTestPeriod" value="50"/>
</bean>
... but I can't find its name in google. Any ideas?

Don't know of JPA property for this either. But you could just add the Hibernate property (assuming you use Hibernate as provider) as
...
<property name="hibernate.default_schema" value="myschema"/>
...
Hibernate should pick that up

Just to save time of people who come to the post (like me, who looking for Spring config type and want you schema name be set by an external source (property file)). The configuration will work for you is
<bean id="domainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JiraManager"/>
<property name="dataSource" ref="domainDataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false"/>
<property name="showSql" value="false"/>
<property name="databasePlatform" value="${hibernate.dialect}"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.default_schema">${yourSchema}</prop>
</props>
</property>
</bean>
Ps :
For the hibernate.hdm2ddl.auto, you could look in the post Hibernate hbm2ddl.auto possible values and what they do?
I have used to set create-update,because it is convenient. However, in production, I think it is better to take control of the ddl, so I take whatever ddl generate first time, save it, rather than let it automatically create and update.

For others who use spring-boot, java based configuration,
I set the schema value in application.properties
spring.jpa.properties.hibernate.dialect=...
spring.jpa.properties.hibernate.default_schema=...

In order to avoid hardcoding schema in JPA Entity Java Classes we used orm.xml mapping file in Java EE application deployed in OracleApplicationServer10 (OC4J,Orion).
It lays in model.jar/META-INF/ as well as persistence.xml. Mapping file orm.xml is referenced from peresistence.xml with tag
...
<persistence-unit name="MySchemaPU" transaction-type="JTA">
<provider>...</provider>
<mapping-file>META-INF/orm.xml</mapping-file>
...
File orm.xml content is cited below:
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
version="1.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema>myschema</schema>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>

For those who uses last versions of spring boot will help this:
.properties:
spring.jpa.properties.hibernate.default_schema=<name of your schema>
.yml:
spring:
jpa:
properties:
hibernate:
default_schema: <name of your schema>

I had to set the value in '' and ""
spring:
jpa:
properties:
hibernate:
default_schema: '"schema"'

Use this
#Table (name = "Test", schema = "\"schema\"")
insteade of #Table (name = "Test", schema = "schema")
If you are on postgresql the request is :
SELECT * FROM "schema".test
not :
SELECT * FROM schema.test
PS: Test is a table

If you are using (org.springframework.jdbc.datasource.DriverManagerDataSource) in ApplicationContext.xml to specify Database details then use below simple property to specify the schema.
<property name="schema" value="schemaName" />

Related

Inject multiple datasources to single EntityManagerFactory?

I am trying to fetch data from two different tables of two different schemas (logical db) in same database server using innerjoin query +JPA nativesql. How can I inject multiple datasources to same entity manager?
my config file looks like this
<bean id="userDataSource" class="org.jdbcdslog.DataSourceProxy">
<description>Data source for User database</description>
<property name="targetDSDirect">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/cUser" />
<property name="resourceRef" value="true" />
</bean>
</property>
</bean>
<bean id="masterDataSource" class="org.jdbcdslog.DataSourceProxy">
<description>Data source for User database</description>
<property name="targetDSDirect">
<bean class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/Master" />
<property name="resourceRef" value="true" />
</bean>
</property>
</bean>
<bean id="entitymanager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation"
value="classpath:com/jpa_persistence.xml" />
<property name= "persistenceUnitName" value= "CP"/>
<property name="dataSource" ref="userDataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false"/>
</map>
</property>
</bean>
Most of the database engines i know do not required these kind of evil double datasource tricks, you can just grant read (or write) access to both schema on the same user.
This way the user will have access to both of those schemas and be able to cross query.
Finally use the Entity anotation to define which schema to use
#Entity
#Table(name = "author", schema = "bookstore")
public class Author { ... }

In which scenario do i need to provide spring class name as bean id value?

I need to configure xml file for DAO. So in my xml file, I have declared two entityManager Factory and I want to set one of them as default persistence unit. I have declared that part as below in my dao.xml
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
property name="defaultPersistenceUnitName" value="pumps-jpa"/>
</bean>
But, it didn't not work for me, it was not taking default persistence unit. I was getting error like this
No unique bean of type is defined: expected single bean but found 2:
After lot of searching, I found one code snippet in which they have mentioned bean id as spring class name i.e. org.springframework.context.annotation.internalPersistenceAnnotationProcessor, as shown below
<bean id="org.springframework.context.annotation.internalPersistenceAnnotationProcessor"
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
property name="defaultPersistenceUnitName" value="pumps-jpa"/>
</bean>
So, after mentioning this bean id, it is taking default persistence unit name. I want to know, why do I need to mention spring class (org.springframework.context.annotation.internalPersistenceAnnotationProcessor) as bean id? Is it a kind of hack or something?
Whole dao.xml is declared below
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="file:${catalina.base}/conf/pumps-dbconfig.properties"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
<value>${jdbc.driver}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.user}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<property name="initialPoolSize"><value>10</value></property>
<property name="minPoolSize"><value>10</value></property>
<property name="maxPoolSize"><value>${jdbc.maxConnections}</value></property>
<property name="maxIdleTimeExcessConnections"><value>600</value></property>
<!-- <property name="timeout"><value>0</value></property> --> <!-- 0 means: no timeout -->
<property name="idleConnectionTestPeriod"><value>60</value></property>
<property name="acquireIncrement"><value>5</value></property>
<property name="maxStatements"><value>0</value></property> <!-- 0 means: statement caching is turned off. -->
<property name="numHelperThreads"><value>3</value></property> <!-- 3 is default -->
<property name="unreturnedConnectionTimeout"><value>0</value></property>
<property name="debugUnreturnedConnectionStackTraces"><value>true</value></property>
<property name="testConnectionOnCheckout"><value>true</value></property>
</bean>
<!--
Configuration for Hibernate/JPA
-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="pumps-jpa" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
<!-- DEFAULT PERSISTENCE UNIT DECLARATION -->
<bean id="org.springframework.context.annotation.internalPersistenceAnnotationProcessor"
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="defaultPersistenceUnitName" value="pumps-jpa"/>
</bean>
<bean id="r-dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
<value>${r-jdbc.driver}</value>
</property>
<property name="jdbcUrl">
<value>${r-jdbc.url}</value>
</property>
<property name="user">
<value>${r-jdbc.user}</value>
</property>
<property name="password">
<value>${r-jdbc.password}</value>
</property>
<property name="initialPoolSize"><value>10</value></property>
<property name="minPoolSize"><value>10</value></property>
<property name="maxPoolSize"><value>${r-jdbc.maxConnections}</value></property>
<!-- <property name="timeout"><value>0</value></property> --> <!-- 0 means: no timeout -->
<property name="maxIdleTimeExcessConnections"><value>600</value></property>
<property name="idleConnectionTestPeriod"><value>60</value></property>
<property name="acquireIncrement"><value>5</value></property>
<property name="maxStatements"><value>0</value></property> <!-- 0 means: statement caching is turned off. -->
<property name="numHelperThreads"><value>3</value></property> <!-- 3 is default -->
<property name="acquireRetryAttempts"><value>3</value></property>
<property name="testConnectionOnCheckout"><value>true</value></property>
</bean>
<!--
Configuration for Hibernate/JPA
-->
<bean id="r-entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="pumps-jpa" />
<property name="dataSource" ref="r-dataSource" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="BaseDataConnection" class="com.myntra.commons.dao.impl.BaseDataConnection">
<property name="roEntityManagerFactory" ref="r-entityManagerFactory" />
</bean>
I think your original problem was not what you meant! By configuration you can refer to one of your Entity Manager's existing Persistence Unit implementations as 'the default persistence unit'! You can do this in your XML config! persistence.xml in JPA is your persistence config your beans (configuration) xml is an other option to point to some of the defined persistence units. Please post your whole config xml ...
For the rest of your problem with the Bean ID:
There is already a Bean in your container initialised with the same name.
The Container is using the Bean Id as a unique Id of your identifiable code fragment! If you use another name then your container will initialise another bean instance of the same class and give it the other name. However as I pointed out above this is not related to your problem! (Even if you can bypass your existing bean implementations and redefine your config if you do not have other options!)

UserType / Hibernate / JodaMoney error : PersistentMoneyAmount requires currencyCode to be defined as a parameter

I'm using UserType 3.0.0.RC1 to map JodaMoney to Hibernate.
I'm stuck with an error when the SessionFactory initialises:
PersistentMoneyAmount requires currencyCode to be defined as a
parameter, or the defaultCurrencyCode Hibernate property to be defined
I'm sure I must have some configuration issue — here's the relevant snippets.
Persistence.xml:
<persistence-unit name="spring-jpa">
<properties>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="jadira.usertype.autoRegisterUserTypes" value="true"/>
</properties>
</persistence-unit>
The relevant spring config:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.mangofactory.concorde</value>
<value>com.mangofactory.moolah</value>
</list>
</property>
<property name="persistenceUnitName" value="spring-jpa" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
Any tips on what I'm missing?
I ended up solving this using the following configuration in my persistence.xml:
<persistence-unit name="spring-jpa">
<properties>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="jadira.usertype.autoRegisterUserTypes" value="true"/>
<property name="jadira.usertype.currencyCode" value="AUD"/>
<property name="jadira.usertype.seed" value="org.jadira.usertype.spi.shared.JvmTimestampSeed"/>
</properties>
</persistence-unit>
The tricky part is that I needed to provide a jadira.usertype.seed in order for the jadira.usertype.currencyCode to be detected.
if you're looking for an annotation based solution, you may try this
#Type(type = "org.jadira.usertype.moneyandcurrency.joda.PersistentMoneyAmount", parameters = { #Parameter(name="currencyCode", value="USD") })
private Money price;
found here
Email Archive: usertype-discuss (read-only)
Regarding the need to configure seed - this is due to a bug in 3.0.0-RC1 and will be fixed in future.

Discover JPA annotated classes when using Spring 3+Hibernate JPA

I have a web application using the Spring 3 + Hibernate JPA stack.
I would like to know if there is a way to have Hibernate to automatically discover #Entity annotated classes, so that I don't have to list them in the persistence.xml file.
My #Entity annotated classes "live" in a separate jar, located in the WEB-INF/lib of my web application.
This is a snippet from my Spring configuration file:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="mypersistence"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect"/>
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="url" value="jdbc:derby://localhost:1527/library;create=true"/>
<property name="username" value="app"/>
<property name="password" value="app"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean id="persistenceAnnotation" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
You can put the persistence.xml file inside the jar where your entities live. Don't need to specify anything then, it works automagically.
you can also specify your #Entity annotated classes in applicationContext.xml like this
<property name="packagesToScan">
<list>
<value>com.vattikutiirf.nucleus.domain</value>
<value>com.vattikutiirf.nucleus.domain.generated.secondtime</value>
</list>
</property>
The separate jar files to scan for entities are specified using <jar-file> elements in persistence.xml. So, if you entities are located in /WEB-INF/lib/entities.jar, you need
<jar-file>lib/entities.jar</jar-file>

Hibernate: Automatically creating/updating the db tables based on entity classes

I have the following entity class (in Groovy):
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
#Entity
public class ServerNode {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id
String firstName
String lastName
}
and my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="NewPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/Icarus"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="create"/>
</properties>
<class>net.interaxia.icarus.data.models.ServerNode</class>
</persistence-unit>
</persistence>
and the script:
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.Persistence
import net.interaxia.icarus.data.models.ServerNode
def factory = Persistence.createEntityManagerFactory("NewPersistenceUnit")
def manager = factory.createEntityManager()
manager.getTransaction().begin()
manager.persist new ServerNode(firstName: "Test", lastName: "Server")
manager.getTransaction().commit()
the database Icarus exists, but currently has no tables. I would like Hibernate to automatically create and/or update the tables based on the entity classes. How would I accomplish this?
I don't know if leaving hibernate off the front makes a difference.
The reference suggests it should be hibernate.hbm2ddl.auto
A value of create will create your tables at sessionFactory creation, and leave them intact.
A value of create-drop will create your tables, and then drop them when you close the sessionFactory.
Perhaps you should set the javax.persistence.Table annotation explicitly?
You might try changing this line in your persistence.xml from
<property name="hbm2ddl.auto" value="create"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.
Got this from JavaRanch
Sometimes depending on how the configuration is set, the long form and the short form of the property tag can also make the difference.
e.g. if you have it like:
<property name="hibernate.hbm2ddl.auto" value="create"/>
try changing it to:
<property name="hibernate.hbm2ddl.auto">create</property>
In my case table was not created for the first time without last property listed below:
<properties>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="create-drop"/>
<!-- without below table was not created -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
</properties>
used Wildfly's in-memory H2 database
There is one very important detail, than can possibly stop your hibernate from generating tables (assuming You already have set the hibernate.hbm2ddl.auto). You will also need the #Table annotation!
#Entity
#Table(name = "test_entity")
public class TestEntity {
}
It has already helped in my case at least 3 times - still cannot remember it ;)
PS. Read the hibernate docs - in most cases You will probably not want to set hibernate.hbm2ddl.auto to create-drop, because it deletes Your tables after stopping the app.
TO CREATING TABLE AUTOMATIC , NO CONNECTION WITH ANNOTATIONS
FOR THAT WE NEED TO CHANGE "hibernate.cfg.xml" as like.
<property name="hbm2ddl.auto">update</property>
In applicationContext.xml file:
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.howtodoinjava.demo.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager.
Exposes Hibernate's persistence provider and EntityManager extension interface -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
In support to #thorinkor's answer I would extend my answer to use not only #Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with #Column(name = "col_name"). This results into seamless updation to the table on the go.
For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.

Categories

Resources