Execute "SET ROLE" statement in eclipselink JPA - java

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

Related

Java lib to work on mySQL with object oriented syntax?

Beginner in SQL, coming from MongoDB.
I see libs that write SQL queries with Strings like:
String sql =
"SELECT id, category, duedate " +
"FROM tasks " +
"WHERE category = :category";
then one must take this sql String and write something like: List<Task> tasks = con.createQuery(sql);
My question:
Imagine a db made of tables where each line in the table is considered an object.
Is there a library for mySQL where the syntax would be more like:
List<Object> results = db.query().select(Object.oneField).where(Object.oneField.equals("myString").from(db.MyTable);
Note: the mySQL db is already created, I am not the owner.
I think Hibernate is what you are looking for.
At a very beginners level its like..
//create a user(Entity) object and set its properties
User user = new User();
user.setName("xyz");
user.setCity("New Delhi");
and then you go on persisting(saving) the object to the database which will allow you to save the user properties in the database.
//get hibernate specific SessionFactory object
session.persist(user); //this will make your object's properties persist in the database
Take a look at Hibernate docs for detailed info.

Java Connection String to query from two database

I am having a problem. I have a query that checks one database table and updates another database table. I am using MySQL 5.1
UPDATE dldd.temp,test.temp
SET test.temp.name = dldd.temp.word
WHERE dldd.temp.id = test.temp.id
this is my SQL statement that is working fine. Now I want to execute this statement using Java PreparedStatement . The problem is I don't know how to write the Connection String to select two database i.e
"jdbc:mysql://localhost:3306/"+dbname+"?characterEncoding=UTF-8"
What should come in place of dbname. Can I select multiple db there.
Have a look at http://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html.
If the database is not specified, the connection is made with no default database. In this case, either call the setCatalog() method on the Connection instance, or fully specify table names using the database name (that is, SELECT dbname.tablename.colname FROM dbname.tablename...) in your SQL. Opening a connection without specifying the database to use is generally only useful when building tools that work with multiple databases, such as GUI database managers.

How to connect two database through JDBC? Is it possible?

I have tried to connect the mysql database with the frontend with the help of JDBC driver. But i dont know how acna we implement connectivity to connect the two different databases with each other with the help of JDBC driver.
You can create two connections. One for the first database and the other for the second database. You can send commands to the first database using the first connection and you can send commands to the second database using the second connection. Your application will serve the purpose of connecting the two databases as you can select rows from one database, parse them and insert the resulting records into the other.
There is no magic in JDBC that allows you to 'connect the two database with each other'. You need to code this yourself. You create two connections, one for each database and then you write the queries and transformations to get your data from database 1 to database 2.
try (
Connection connectionToDb1 = DriverManager.getConnection(
"jdbc:firebirdsql://serverA/database1", "username", "password");
Connection connectionToDb2 = DriverManager.getConnection(
"jdbc:firebirdsql://serverB/database2", "username", "password");
Statement selectFrom1 = connectionToDb1.createStatement();
ResultSet rsFrom1 = selectFrom1.executeQuery(
"SELECT columnA, columnB FROM tableX");
PreparedStatement insertTo2 = connectionToDb2.prepareStatement(
"INSERT INTO tableY(column1, column2) VALUES (?, ?)");
) {
while (rsFrom1.next()) {
insertTo2.setString(1, rsFrom1.getString("columnA"));
insertTo2.setString(2, rsFrom1.getString("columnB"));
insertTo2.executeUpdate();
}
}
Note that this isn't a complete example: for production purposes you would disable auto commit, and use batch updates.
There are tools that can do this for you, but tool and library suggestions are off topic on SO, but I'd suggest you search for ETL (or extract, transform, load), or maybe for datapump.

How to execute a "SET ROLE XXXX..." with Hibernate

I'm developing a web app (java) and I'm using Hibernate 4.1.4 and oracle 11g. By security's rules, the dbuser (the db user that app uses) doesnt have insert privileges. Then every time my app is gonna do a insert, it must execute the query "SET ROLE XXXX ...." before the insertion-query be executed. This "set role.." will give to dbuser the privileges to insert into some tables int that transaction. How to do it with Hibernate? I don't wanna put it in a default conf because I should execute the above query only in insertions (not to selects...). I tried do it on my save method:
public Object saveOrUpdate(Object entity) {
Query query = getSessionFactory().getCurrentSession().createSQLQuery("set role XXXX identified by XXXX");
query.executeUpdate();
getSessionFactory().getCurrentSession().saveOrUpdate(entity);
return entity;
}
but it doesnt work. I get the error "view or table not exist". When I try execute only the query.executeUpdate() or the saveOrUpdate(entity) no error happened.
I guess it is all. If you need more details, please ask to me. Thanks!

Hibernate multiple native SQL statements

I want to run a native SQL from a file using Hibernate. The SQL can contain several statements creating the database structure (i.e. tables, constraints but no insert/update/delete statements).
Example, very simple query is below (which contains the following two SQL statements)
CREATE DATABASE test;
CREATE TABLE test.testtbl( id int(5));
I am using MySQL db, and when I run the above query I am gettng syntax error returned. When I run them one by one, its ok.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'CREATE TABLE test.testtbl( id int(5))' at line 1
The code to run the query is below (above statement is assigned to 'sql' variable):
session = sf.openSession();
session.beginTransaction();
Query qry = session.createSQLQuery(sql);
qry.executeUpdate();
session.getTransaction().commit();
Any help would be appreciated.
As others have explained
You must run these queries one by one.
The hibernate code gets translated into running one update statement on JDBC.
But you provided two update statements.
In addition,
I personally prefer to have the code that creates tables outside of the Java application, in some DB scripts.
The parameters of the method createSQLQuery is t-sql code;
t-sql code to ensure that in the mysql interface analyzer correctly.
You can try changed the sql :'CREATE TABLE testtbl(id int(5));'
by the way you can use JDBC Connection api (Don't recommend to do so)
Such as:
java.sql.Connection conn=session.connection();

Categories