JPA VS JDBC - 2 questions - java

I'm using Eclipse Juno IDE
In phpMyAdmin I created my own database and my Table.
Now with the JDBC I entered some recoreds.
Next I tried to implement some queries with the JPA, I created an Entity
with the same columns and the persistence.xml connected to my database.
but when I was running the program it's delete the all the recoreds and created
a new empty table (with the same name) in my database.
So my question is : how can i connect to existed table in the database but not create
a new one.
another question is: i didn't give to my table a primary key because my table it's
about drivers travels, so each driver can travel many times... so if I use the primary
key it will not add the new data about the driver. with the JDBC it works fine.
but with the JPA the entity needs some field to be a Primary Key.. so how can I add
a new data about the same driver in JPA?
the persistence file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit transaction-type="RESOURCE_LOCAL" name="MyJPA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>pack.bl.Travels</class>
<properties> <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/drivers"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
Code:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyJPA");
EntityManager em = emf.createEntityManager();
List<Travels> allTravels = em.createQuery("SELECT t FROM travels t",Travels.class).getResultList();
for (Travels s : allTravels)
System.out.println(s.toString());
em.close();

Add an id autoincrement field to your table. It will be the primary key.
About auto-creation of tables, look here(I assume you are using Hibernate as JPA implementation):
Hibernate hbm2ddl.auto possible values and what they do?

in your hibernate configuration, make sure hibernate.hbm2ddl.auto isnt set to create-drop (because thats what it sounds like).
try setting it to validate
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html

follow the link for jpa configuration
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html
add code in your configuration xml file
<property name="hibernate.hbm2ddl.auto" value="validate"/>

Related

H2 database console: how to connect to an embedded H2 JPA database?

I have a couple of unit tests for an application's JPA layer. This JPA layer consists in JPA entities and a service providing the basic API required in order to persist the entities. The unit tets directly use the javax.persistence classes in order to handle the PersistenceManager. Then it tests the persistence API and I can see in the log the SQL statements to create tables and sequences, etc.
The relevant part of the persistence.xml file looks like:
<persistence-unit name="..." transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
...
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
...
I have downloaded H2 1.4.200, the Windows installer, and I installed it on Windows 10. Now using the H2 console I want to connect to the database and inspect the tables, sequences, etc. that were created automatically by Hibernate.
So, going to http://localhost:8082 I get the following:
But when I try to connect to my database, using the defined JDBC connection string, I get the following:
What am I doing wrong here ?
Many thanks in advance.
Nicolas
Finally, I've replaced H2 with Oracle.

hibernate with JPA to generate entity in other schema

I have created two entities in my JAVA code one is Account entity, another is AccountLog entity. These two entities mapped to the corresponding table in same schema named testdb. We use hibernate and JPA to handle the insert/update and table generation.
Since the performance issue, I would like to separate the AccountLog into other schema named testdb_log. So that the AccountLog table will be generated in schema testdb_log and the next insert/update event will be stored in the schema testdb_log.
What is the best solution to handle the above cases? Add #table annotation with schema name? or others?
How to generate the entity to other schema?
For this entity, how to save/update this entity information to other schema?
I will probably use different persistence units in the persistence xml, something like this:
<persistence version="2.1"
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_1.xsd">
<persistence-unit name="oneschema" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="driverClass" value="${db.driver}" />
<property name="jdbcUrl" value="${datasource.baseurl}/SCHEMAONE" />
<property name="user" value="${datasource.username}" />
<property name="password" value="${datasource.password}" />
</properties>
</persistence-unit>
<persistence-unit name="anotherchema" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.company.AccountLog</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="driverClass" value="${db.driver}" />
<property name="jdbcUrl" value="${datasource.baseurl}/SCHEMANOTHER" />
<property name="user" value="${datasource.username}" />
<property name="password" value="${datasource.password}" />
</properties>
</persistence-unit>
</persistence>
In the second persistence unit you declare explicitly what classes belong to it, so the entity manager will know how to deal with them.
Schema, connections, connection pools are usually transparent to the java code so you shouldn't change anything in java.

how to automatic create table in jpa persistence xml file?

I am using eclipse IDE.I also try following two .but failed..when i manually create table in my mysql database then my complete program run fine... I want create table automatic with respect to entity class.
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.hbm2ddl.auto">update</property>
here my persistence file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 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_1.xsd">
<persistence-unit name="JpaTest2" transaction-type="RESOURCE_LOCAL">
<class>com.jpa.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="javax.persistence.jdbc.user" value="umar"/>
<property name="javax.persistence.jdbc.password" value="umar"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
Dont use Hibernate specific options. JPA 2.1 provides
javax.persistence.schema-generation.database.action
that can be set to "create", "drop", "drop-and-create", "none".
That way you keep your code JPA implementation independent
Check your entity. Did you miss #Table annotation? The exception clearly says that the table is missing 'hibernate.employee':
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate.employee' doesn't exist at ...
If you defined a naming strategy that prepends all tables with hibernate., then make sure that the tables are created in MySql.

Location of the persistence.xml in a Java Client App

I am a newbie in Hibernate. In order to get the transaction by the EntityManager, I need to use EntityManager Factory. When I put this code block on my file:
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("Comment");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(obj);
transaction.commit();
I got this Exception:
javax.persistence.PersistenceException: No Persistence provider for EntityManager named Comment
Then I realized that I need to add a persistence.xml file:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="QuestionsComments" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Comment</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="root"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/sogdb"/>
<property name="hibernate.max_fetch_depth" value="3"/>
</properties>
</persistence-unit>
</persistence>
Actually, The app I am using is not a Java on Server app (I have a Client app). Which means that there is no META-INF folder that will contain the persistence.xml file.
My Questions are:
1- Where I need to put the persistence.xml file?
2- Is the code below OK? Knowing that my table in the database is QuestionsComments and my class that will be related to it using Hibernate is Comment.
If you are using Eclipse, adding the JPA facet to your project allows Eclipse to take care of setting these things up for you. It will create the META-INF folder, and can generate a stub persistence.xml file in it. You don't have to be running the code on a server to have a META-INF folder in your jar file.
When you are creating the EntityManagerFactory the string argument should be the name of the persistence unit. I'd recommend using annotations in your entity class for specifying table name, id column, etc.
Edit: fixed link.
Answered clearly in this section of the Hibernate JPA Quick Start Guide. It goes in META-INF.
Check out the same guide just linked.
Personally I prefer the Hibernate-specific configuration hibernate.cfg.xml with annotations for mappings and Hibernate's SessionFactory for transaction access; I find it easier to wrap my head around -- although that's probably because I originally learned how to use Hibernate without knowing how to use JPA.

How to generate table from entities

I am currently working on a seam project using eclipse jpa tools; is it possible to automatically generate sql tables from my entity definitions? If so, how do I achieve this?
It depends on the JPA implementation you are using.
With Hibernate you can specify 'create' or 'update' in the hibernate.hbm2ddl.auto properties in persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
<persistence-unit name="yourPersistenceUnit" transaction-type="JTA">
<description>Your Persistence Unit</description>
<jta-data-source>java:/DefaultDS</jta-data-source>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.transaction.flush_before_completion" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
</properties>
</persistence-unit>
</persistence>
Possible values for hibernate.hbm2ddl.auto property are:
create: create database tables and indexes at startup
create-drop: create database tables and indexes at startup and drop at shutdown
update: when the application starts, check the database schema and update as needed adding missing tables and columns
validate: when the application starts, check the database schema and fails if there is some missing table or column.

Categories