Create database with JPA? - java

When I create (using JPA - java persistence api) a persistence unit and then persistence entities they auto create the corresponding tables and fields in the database.
Can I also make it to auto create the database (if it doesn't exist)?
My objectif is :
I mean it creates inside the database the tables and fields, but not the database, and if the database hasn't been created before (by hand) - everything fails. So before running the project (which will auto generate the tables and fields if needed) I first must create (by hand) a database.
I use : Eclipse (Java, Hibernate, Flex/Air), MySQL
Thanks for all information

The database has to be created manually (Fortunatly you didn't ask why ;-). Which is similar to the user/password combination you use to connect to your database server, which must already exist in order to connect to the DB.

My solution to this problem was to add the following right before I create my entity manager:
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost/?user=" + DB_USER);
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + DB_NAME);
You'll need to either surround that with a try/catch block or add a throws SQLException notation to the function in which it exists. So, for example, here is my initEntityManager function:
public static void initEntityManager() throws SQLException {
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost/?user=" + DB_USER);
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + DB_NAME);
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
}

Related

Why connection still commits automatically after putting setAutoCommit(false)?

I'm using a MySQL database.
I have a code like this :
public class Test {
public static void main(String[] args) throws SQLException {
String url = "....";
String username = "...";
String password = "...";
DriverManager.registerDriver(new Driver());
Connection connection = DriverManager.getConnection(url, username, password);
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
stmt.execute("create table if not exists customer1\r\n" + "(\r\n"
+ "customer_name varchar(20) not null primary key,\r\n" + "customer_street varchar(20),\r\n"
+ "customer_city varchar(10)\r\n" + ")");
// connection.commit();
connection.close();
}
}
Problem: When I execute this, it creates the table and commits it automatically but it should not.
I did connection.setAutoCommit(false) and commented out connection.commit() for testing, then why it is committing ?
This question (jdbc autocommit(false) doesnt work) didn't help.
Problem: When I execute this, it creates the table and commits it
automatically but it should not.
Right, any DDL will always be committed regardless of autocommit setting.
This behavior is not specific to MySQL, see Autocommit.
Most DBMS (e.g. MariaDB) force autocommit for every DDL statement,
even in non-autocommit mode. In this case, before each DDL statement,
previous DML statements in transaction are autocommitted. Each DDL
statement is executed in its own new autocommit transaction.
Maybe TEMPORARY TABLE might help you.
You can use the TEMPORARY keyword when creating a table. A TEMPORARY
table is visible only within the current session, and is dropped
automatically when the session is closed. This means that two
different sessions can use the same temporary table name without
conflicting with each other or with an existing non-TEMPORARY table of
the same name. (The existing table is hidden until the temporary table
is dropped.)
MySQL DDL, i.e. creating table isn't transactional
ref transactions that cause implicit commit
Data Manipulation statements are transactional, not Data definition statements.
so create/alter table or drop table are still committed.

Copying a Clob in another Clob with different implementation

In my company we are performing a database migration. For lots of reasons we cannot use a database migration tool, so we had to develop our migration tool to copy from a DB to another all rows contained in some specific tables. We have developed a tool using JDBC of multiple database. At the moment, we are migrating from DB2 to Oracle, with an intermediate step to H2. Same tables ha a Clob column. When we export this column from DB2 to H2 we get no errors or issues, but when we try to copy the Clob from H2 to Oracle using JDBC we get the following exception:
ClassCastException: cannot cast from org.h2.jdbc.JdbcClob to oracle.jdbc.Clob
Is there a way or a procedure to perform this kind of conversion? Something like a ClobCopy utility within different Clob types? Unfortunately we can do this task only using Java and Jdbc, no JPA or DB migration tools due to customer specifications.
This is an example of what I'm trying to do:
public class CopyTable {
public void doCopy(){
Connection h2 = getH2Connection(); //suppose this exists and works
Connection oracle = getOracleConnection(); //suppose this exists and works
String sqlSelect = "select * from tabletoexport";
String sqlInsert = "insert into tabletofill(ID, DATA) values (?,?)";
PreparedStatement select = h2.prepareStatement(sqlSelect);
PreparedStatement insert = oracle.prepareStatement(sqlInsert);
ResultSet rs = select.executeQuery();
while (rs.next()){
insert.setLong(1, rs.getLong("ID"));
insert.setClob(2, rs.getClob("DATA")); //this throws an exception
insert.executeUpdate();
}
}
}
The Clob interface has a getCharacterStream() method which returns a Reader, and the PreparedStatement interface has a setClob() method which takes a Reader. All you need to do to get the copy working is to use these methods.
In other words, replace the line
insert.setClob(2, rs.getClob("DATA")); //this throws an exception
with
insert.setClob(2, rs.getClob("DATA").getCharacterStream());
As for why the import from DB/2 to H2 didn't complain, perhaps the H2 JDBC driver doesn't assume that Clob values passed in to setClob come from H2, but the Oracle JDBC driver does assume that Clobs passed in in the same way are from Oracle. However, the Oracle JDBC can't reasonably make any such assumptions about a Reader, as these could come from anywhere

Execute "SET ROLE" statement in eclipselink JPA

I am using EclipseLink JPA to connect to vertica database and fetch results. Before running the below piece of code
EntityManager em = ...
Query q = em.createQuery ("SELECT x FROM Table x");
List results = q.getResultList ();
I need to first run the "SET ROLES ALL" statement for the user id. How to run such statements in JPA.
Please guide me.
for Vertica, you can do two things:
set your default role for the user:
alter user myuser default role myrole;
use connection string property "ConnSettings" as described in the Vertica connection string docs (https://my.vertica.com/docs/6.1.x/HTML/index.htm#13173.htm):
A string containing SQL statements that the JDBC driver automatically
runs after it connects to the database. This property is useful to set
the locale, set the schema search path, or perform other configuration
that the connection requires.
Your connection string could look like something like this:
jdbc:vertica://myverticaserver/mydb?ConnSettings=SET+ROLE+myrole

Creating a "Java DB" database and associated tables in main checking to see if they exist?

I'm creating an applicaation on Netbeans 7! I'd like my application to have a little code in main so that it can create a Java DB connection checking to see if the database and the associate tables exist, if not create the database and the tables in it. If you could provide a sample code, it'd be just as great! I have already looked at http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/ but I'm still not sure how to check for an existing database before creating it!
I'd like my application to have a little code in main so that it can create a Java DB connection checking to see if the database and the associate tables exist, if not create the database and the tables in it.
You can add the create=true property, in the JDBC URL. This creates a Derby database instance if the database specified by the databaseName does not exist at the time of connection. A warning is issued if the database already exists, but as far as I know, no SQLException will be thrown.
As far as creation of the tables is concerned, this is best done on application startup before you access the database for typical transactional activity. You will need to query the SYSTABLES system table in Derby/JavaDB to ascertain whether your tables exist.
Connection conn;
try
{
String[] tableNames = {"tableA", "tableB"};
String[] createTableStmts = ... // read the CREATE TABLE SQL statements from a file into this String array. First statement is for the tableA, and so on.
conn = DriverManager.getConnection("jdbc:derby:sampleDB;create=true");
for(int ctr =0 ; ctr < tableNames.length; ctr++)
{
PreparedStatement pStmt = conn.prepareStatement("SELECT t.tablename FROM sys.systables t WHERE t.tablename = ?");
pStmt.setString(1, tableNames[ctr]);
ResultSet rs = pStmt.executeQuery();
if(!rs.next())
{
// Create the table
Statement stmt = conn.createStatement();
stmt.executeUpdate(createTableStmts[ctr]);
stmt.close();
}
rs.close();
pStmt.close();
}
}
catch (SQLException e)
{
throw new RuntimeException("Problem starting the app...", e);
}
Any non-existent tables may then be created. This is of course, not a good practice, if your application has multiple versions, and the schema varies from one version of the application to another. If you must handle such a scenario, you should store the version of the application in a distinct table (that will usually not change across versions), and then apply database delta scripts specific to the newer version, to migrate your database from the older version. Using database change management tools like DbDeploy or LiquiBase is recommended. Under the hood, the tools perform the same operation by storing the version number of the application in a table, and execute delta scripts having versions greater than the one in the database.
On a final note, there is no significant difference between JavaDB and Apache Derby.
I don't know how much Oracle changed Derby before rebranding it, but if they didn't change too much then you might be helped by Delete all tables in Derby DB. The answers to that question list several ways to check what tables exist within a database.
You will specify the database when you create your DB connection; otherwise the connection will not be created successfully. (The exact syntax of this is up to how you are connecting to your db, but the logic of it is the same as in shree's answer.)
The create=true property will create a new database if it is not exists. You may use DatabaseMetadata.getTables() method to check the existence of Tables.
Connection cn=DriverManager.getConnection("jdbc:derby://localhost:1527/testdb3;create=true", "testdb3", "testdb3");
ResultSet mrs=cn.getMetaData().getTables(null, null, null, new String[]{"TABLE"});
while(mrs.next())
{
if(!"EMP".equals(mrs.getString("TABLE_NAME")))
{
Statement st=cn.createStatement();
st.executeUpdate("create table emp (eno int primary key, ename varchar(30))");
st.close();;
}
}
mrs.close();
cn.close();
Connection conn = getMySqlConnection();
System.out.println("Got Connection.");
Statement st = conn.createStatement();
String tableName = ur table name ;
String query = ur query;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
System.out.println("Exist");;
}
catch (Exception e ) {
// table does not exist or some other problem
//e.printStackTrace();
System.out.println("Not Exist");
}
st.close();
conn.close();

Mysql read data immediately after writing?

I am using a MySQL DB and a Java JDBC client to access it.
I have a Table that contains session information. Each session is associated with a SessionToken. This token is a Base64 encoded String of a Hash of some of the session values. It should be unique. And is defined as varchar(50) in the db.
When I try to lookup a session by its token I query the database using an sql statement like this:
select SessionId, ClientIP, PersonId, LastAccessTime, SessionCreateTime from InkaSession where SessionToken like 'exK/Xw0imW/qOtN39uw5bddeeMg='
I have a UnitTest that tests this functionality, and it consistently fails, because the query does not return any Session, even tough, I have just written the session to the DB.
My Unit test does the following:
Create Connection via DriverManager.getConnection
Add a session via Sql Insert query
close the connection
create Connection via DriverManager.getConnection
look for the session via sql select
unit test fails, because nothing found
When I step through this UnitTest with the debugger and copy past the select sql that is about to be sent to the db into a mysql command line, it works fine, and I get the session row back.
I also tried to retrive an older session from the db by asking for an older SessionToken. This works fine as well. It only fails, if I ask for the SessionToken immediately after I inserted it.
All connections are on AutoCommit. Nevertheless I tried to set the Transaction Level to "Read Uncommited". This did not work either.
Has anyone any further suggestions?
This is typically caused by the connection not being committed between insert and select.
Did you basically do the following?
statement.executeUpdate("INSERT INTO session (...) VALUES (...)");
connection.commit();
resultSet = statement.executeQuery("SELECT ... FROM session WHERE ...");
Edit I tried the following SSCCE on MySQL 5.1.30 with Connector/J 5.1.7:
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/javabase", "root", null);
statement = connection.createStatement();
statement.executeUpdate("INSERT INTO foo (foo) VALUES ('foo')");
resultSet = statement.executeQuery("SELECT id FROM foo WHERE foo = 'foo'");
if (resultSet.next()) {
System.out.println(resultSet.getLong("id"));
} else {
System.out.println("Not inserted?");
}
} finally {
SQLUtil.close(connection, statement, resultSet);
}
}
Works flawlessly. Maybe an issue with your JDBC driver. Try upgrading.
Solved: The two token strings where not identical. One of them had a couple of Zero bytes at the end. (Due to the encrypting and decrypting and padding...) The two strings where visually identical, but MySQL and Java both said, they where not. (And they where right as usual)

Categories