How to overwrite the table in JPA or Entity? - java

I have one java project. In that I use #Entity. In my project have some constraints. Tables should be created automatically. So I use JPa #Entity. what the problem is that, when ever the Program is restarting, the new table is created by the Entity. So my old data got losed. I need those type of data. Trap Entity should not overwrite my content in Database? How to solve it?

use <property name="hibernate.hbm2ddl.auto" value="update"/> in your persistence.xml . If you have not generate the schema then first use <property name="hibernate.hbm2ddl.auto" value="create"/> and the schema will be generated. Then use <property name="hibernate.hbm2ddl.auto" value="update"/> since now you have the schema.

In the persistence.xml file there should be a setting to turn off the auto generation of DLL. Here is an example of a persistence.xml file using hibernate where the hibernate.hbm2ddl.auto property has been set to validate, which will cause the tables not to be overwritten. If your relying on Hibernate to create your DDL you would not want to have this set the first time your run the application, it would be set after running once and successfully creating the DDL (Tables).
If this setting were set to create-drop the schema would recreate the tables each time the persistence context is created, causing all data to be lost. This property will be specific to your ORM vendor's implementation.
The best advice is to find the documentation for your vendor's specific setting and then choose the option which best fits your needs. This post does a good job of describing the possible values for the setting in Hibernate.
<persistence-unit name="toThought" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
</properties>
</persistence-unit>
In EclipseLink this property is:
<property name="eclipselink.ddl-generation" value="create-tables"/>

Related

Having both JPA and Liquibase: what to do with their configuration files?

My project started with JPA only and it doesn't have Spring. Later, I added Liquibase and I had some issues with the persistence unit name since it is necessary to have one to be able to use EntityManager.
entityManagerFactory = Persistence.createEntityManagerFactory("MyPU");
So, to be able to continue with the tables creation with Liquibase and persisting into the database with JPA, I kept both persistence.xml and liquibase.properties files, despite contaning the same database configuration.
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="MyPU">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/jpa_specialist?createDatabaseIfNotExist=true&useTimezone=true&serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
changeLogFile=src/main/resources/META-INF/database/dbchangelog.xml
url=jdbc:mysql://localhost/jpa_specialist?createDatabaseIfNotExist=true&useTimezone=true&serverTimezone=UTC
username=root
password=root
I've taken a look at liquibase-hibernate and I didn't understand it very well but it seems to be used to generate the diff files, which is not my need at the moment.
Are both files necessary? Is there something I can do to have only one of them?
Liquibase doesn't have a direct way to read the url/username/password information from the presistence.xml file. The liquibase-hibernate extension does add support for diff'ing a database with your java file mapping files, but doesn't change how Liquibase gets the url/username/password.
You said you were not using Spring, but if you are still in a web application, you can use the Liquibase servlet listener to run Liquibase which pulls the connection from a pre-configured datasource. JPA can pull from that same pre-configured datasource instead of re-defining the configuration as well.
Otherwise, unless you want to do a bit of custom Java coding to parse the persistence.xml file and pass it into Liquibase, you do need both files.
To avoid the repetition you could do something like defining build properties in your maven/gradle/whatever setup and have <property name="javax.persistence.jdbc.url" value="${database.url}"/>in your persistence.xml source file, and url: ${database.url} in your liquibase.properties file.

multiple persistence unit eclipselink

I m using an osgi application with postgresql connection and a persistence.xml that containt some properties like
<persistence-unit name="postgres-name"
transaction-type="JTA">
<properties>
<!-- <property name="show_sql" value="true" /> -->
<!-- <property name="hibernate.format_sql" value="true" /> -->
<property name="eclipselink.logging.level" value="FINEST"/>
<property name="eclipselink.logging.level.sql" value="FINEST"/>
...many other properties...
</properties>
</persistence-unit>
And in another bundle i want to initialize a H2database with its own unitname, so i have declared a new persistence.xml with :
<persistence-unit name="h2-unitname"
transaction-type="RESOURCE_LOCAL">
<properties>
...many properties...
<property name="eclipselink.allow-zero-id" value="true"/>
...many other properties...
Problem is when i get EntityManager for postgres database, all work fine, next i get h2 EntityManager and work fine, but next time postgres EntityManager is used, i have an error :
Detail: key (id)=(0) already exist
Call: INSERT INTO TABLE(ID, TEST) VALUES (?, ?)
bind => [0, null]
I think my property eclipselink.allow-zero-id define in h2 unitname ovveride the postgres EntityManager...
In fact if i use always postgres database with 0 id, all wark fine, because sequence is call, but if i use one time the h2 EntityManager, entity with 0 id don't work anymore because of allow-zero-id.
How can i define separate property for each persistent unitname?
Ask me if you want to see more configuration
thanks by advance

Is there a way to map same hibernate entity to multiple tables in different schemes

This is the situation. I have a table called customer and this table is repeating among different schemes in the same database. so the problem is when i'm going to map this customer table with hibernate entity do i need to create multiple classes for specifying the schema or can i dynamically change the schema in the entity. I'm a newbie to this hibernate framework please help.
You need to have more persistence unit. And use entity manager created via entity manager factory which used proper persistence unit.
In persistence.xml
<persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL">
<property name="hibernate.connection.url" value="jdbc:database://url1"/>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.password" value="pass"/>
...
</persistence-unit>
<persistence-unit name="pu2" transaction-type="RESOURCE_LOCAL">
<property name="hibernate.connection.url" value="jdbc:database://url12"/>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.password" value="pass"/>
...
</persistence-unit>
private static EntityManagerFactory emf1;
private static EntityManagerFactory emf2;
emf1 = Persistence.createEntityManagerFactory("pu1");
emf2 = Persistence.createEntityManagerFactory("pu2");
emf1.createEntityManager();//Will store to database defined in pu1
emf2.createEntityManager();//Will store to database defined in pu2

Hibernate Clearing Out Database

I'm running a Hibernate configuration (No JPA) and have inserted a test set using random name generators (for practice with the Criteria API), but on ever startup, hibernate keeps clearing out the test set, forcing me to regenerate it. Is there any way to disable this feature? I'm running only bare-bones (connection and mappings) hibernate configuration.
EDIT (hibernate.cfg.xml):
<property name="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url" >jdbc:mysql://localhost:3306/testdb?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username" >Sarah</property>
<property name="hibernate.connection.password"></property>
Ok, so actually adding <property name="hibernate.hbm2ddl.auto">validate</property> seemed to work. I guess hibernate.hbm2ddl.auto must have a default value.

JPA/Hibernate can't create Entity called Order

I'm using Hibernate/JPA and have an #Entity object called Order, pointing at a MySQL database using Hibernate's dynamic table generation i.e. generate tables at runtime for entities. When Hibernate creates the tables, it creates tables for all of my entities except the Order entity. If I rename the Order entity to something else e.g. StoreOrder, the store_order table is created no problem.
Furthermore, if I do this but then annotate the StoreOrder object to specify that the table it should create is called 'order' using #Table (name="order"), the table is no longer created.
I realise that order is a reserved word but is this the reason that it can't create the table? It seems odd given that the Hibernate docs uses an example of an entity called Order.
It doesn't look like a MySQL problem as I can manually create a table called order directly on the database.
Here's the relevant Order entity object definition...
#Entity
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Order extends PersistentEntity {
... rest of POJO def...
}
...and the corresponding Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="store" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>conf/jpa/persistence-query.xml</mapping-file>
<!-- Entities -->
...other entities...
<class>ie.wtp.store.model.Order</class>
<class>ie.wtp.store.model.OrderItem</class>
<!-- Hibernate properties -->
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/store"/>
<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.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.query.factory_class"
value="org.hibernate.hql.classic.ClassicQueryTranslatorFactory"/>
<property name="hibernate.query.substitutions" value="true 1, false 0"/>
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Any thoughts as to why this Order entity is not created but is created if I rename it to StoreOrder?
Cheers,
J :)
The ORDER word is a reserved keyword, you have to escape it.
In JPA 1.0, there is no standardized way and the Hibernate specific solution is to use backticks:
#Entity
#Table(name="`Order`")
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Order extends PersistentEntity {
... rest of POJO def...
}
JPA 2.0 standardized this and the syntax looks like this:
#Entity
#Table(name="\"Order\"")
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Order extends PersistentEntity {
... rest of POJO def...
}
References
Hibernate Core documentation
5.4. SQL quoted identifiers
JPA 2.0 specification
2.13 Naming of Database Objects
Probably because 'Order' is a keyword in SQL. When I encounter this I normally just put 'Tbl' on the end of my entity/table names to avoid the potential clash.

Categories

Resources