I wanted to use Ormlite in my java project so I created two beans :
#DatabaseTable(tableName = "worker")
public class Worker {
#DatabaseField(columnName="wo_id" , generatedId=true , id=true)
private Integer woId;
#DatabaseField(columnName="wo_nom")
private String woNom;
}
#DatabaseTable(tableName = "qualification")
public class Qualification {
#DatabaseField(columnName="qu_id" , generatedId=true , id=true)
private Integer quId;
#DatabaseField(columnName="qu_nom")
private String quNom;
}
When creating the tables, I figured out (too late maybe?) that I needed SQLlite or something like that...
Is it possible to create and use a database from my Java project without using JDBC or anything else of the kind?
without using JDBC or anything else of the kind
JDBC is the way that Java interacts with databases of any kind unless you care to write your own database driver. Assuming you don't want to do that and what you're really looking for is an in-memory or file-based database, use H2. It's superior to both HSQL, which is its predecessor, and Derby.
#RyanStewart is correct that if you are talking about connecting to a SQL database, the was to do with is through JDBC which is how Java communicates with SQL databases like H2, Sqlite, MySQL, Postgres, Derby, etc.. All of those database types are supported by ORMLite.
Is it possible to create and use a database from my Java project without using JDBC or anything else of the kind?
Just for posterity, one way to use ORMLite without JDBC is to implement the backend database interfaces:
ConnectionSource
DatabaseConnection
CompiledStatement
DatabaseResults
This would allow you to implement a backend. But I suspect that you should use JDBC but maybe this information is helpful to others.
An in memory database : http://db.apache.org/derby/
You can use HSQLDB.
HSQLDB - 100% Java Database
Running and Using Hsqldb
Related
I have a JAVA POJO class with hibernate annotation for postgresql database.
Now, I have a requirement that we support multiple databases in our application. My question is : Should we use the same class with other databases (Oracle, MySQL, SQL Server) or should I write separate annotated class for each different database ?
Reason: To support special characters we are using database proprietary types instead of hibernate types like
// for oracle
#Column(sql-type="nvarchar2")
private String name;
// for sql server
#Column(sql-type="nvarchar")
private String name;
// hibernate doesn't support different proprietary sql types at same type like this
#Column(sql-type={"nvarchar","nvarchar2"})
private String name;
If it's ok to use nvarchar for all String typed columns by default, you could extend Oracle and MS SQLServer dialects and do something like this:
public class CustomOracleDialect extends org.hibernate.dialect.Oracle10gDialect {
#Override
protected void registerCharacterTypeMappings() {
super.registerCharacterTypeMappings();
registerColumnType(Types.VARCHAR, "nvarchar2");
}
}
public class CustomSQLServerDialect extends org.hibernate.dialect.SQLServer2012Dialect {
public CustomSQLServerDialect() {
super();
registerColumnType(Types.VARCHAR, "nvarchar");
}
}
Then configure these dialects in dependence to the database type used.
The same exact class WILL work with other DB engines, as far as Hibernate is concerned all it cares about is the dialect for the most part. However, some DB engines don't support the identity generation strategy for ID fields for example (from past experience). Depending on what DB engines you are required to work with you may have to get creative a bit but, for the most part, as long as you don't have any DB-engine-specific code in your entity classes, everything should work just fine. I for example switched a project from HSQLDB to SQLite and the only thing that did not work was the identity generation i mentioned earlier. If i were you i would experiment with different dialects and thoroughly test everything.
EDIT
Just saw your edit and that is definitely engine-specific code. In this case you might indeed need different entities to accommodate the specific data type you want to explicitly assign to each column.
Good luck!
I am using Oracle as my database, Spring Boot as my framework.
I don't know how to write a test case to check database query?
I have heard that it is possible through In-Memory Database. But don't find a proper example.
Suppose in my code I have written a SQL query that SELECT * FROM tableName and it is returning me a ResultSet Object.
So in while writing test case how can I check that?
Every time I don't want to go into the database and fetch a query.
I know that is possible but my question is how can I replace my query's result with a dummy result which I will store in any file.
Thanks in advance
You should initialize your Hibernate SessionFactory with another hibernate config, that uses H2 in-memory database, example test-hibenate.properties:
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.connection.url=jdbc:h2:mem:orm
javax.persistence.schema-generation.database.action=drop-and-create
Then in your tests you can use your DAO's just in regular way.
If you use plain JDBC, you can create connection to H2 in-memory database this way:
Connection connection = DriverManager.getConnection("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "", "");
And you will need H2 database dependency:
https://mvnrepository.com/artifact/com.h2database/h2
I already have an existing code base, where schema(like db_1, db_2..) are created at run time.
We are currently using JdbcTemplate, using that its quite easy to append schema in the native SQL queries some thing like :-
sql = " Select * from "+schema+".user";
jdbcTemplate.query(sql, new UserMapper());
Now I want to know is how to provide schema to hibernate at runtime like I did with the jdbcTemplate?
What connection url should I provide in hibernate.cfg.xml so that it doesn't connects to a single schema rather whole database?
Any suggestions will be helpfull.
P.S: I am new to hibernate (So I might have missed something stupid)
I know of two options:
Use native SQL query binding results to JPA entities. Details here.
Use Hibernate multi-tenancy. Details here and here.
Although I haven't tried either.
I started learning Cassandra using java, after completing hibernate. I am really surprised by the way in which data is inserted/pulled/deleted from cassandra through java while java is moving backwards these days. Because, hibernate gives a very easy way to communicate with the database, a java developer has no need to know the database query syntax,etc. It is mostly method based operations which are used to communicate with the database. But if i want to communicate with cassandra through java, everything is in an SQL format i mean they named it as CQL but i am really surprised by the way in which things are happening when i compare it to the hibernate.
My question here is, is there any way to communicate/do CRUD operations on cassandra through java in O-R mapping style or can hibernate supports cassandra connectivity?
Cassandra is not a relational database, using a relational mapper isn't going to be as straight forward. There are no joins and it does not support SQL.
The java drivers object mapper is probably closest to what your looking for though. For basic CRUD mappings on Cassandra tables.
See documentation here: https://docs.datastax.com/en/developer/java-driver/3.0/supplemental/manual/object_mapper
ie
#Table(name = "posts")
public static class Post {
private String title;
private String content;
private InetAddress device;
#ClusteringColumn
#Column(name = "post_id")
private UUID postId;
#PartitionKey
#Column(name = "user_id")
private UUID userId;
private Set<String> tags;
...
}
You can perform crud operation with Cassandra using Solr or Spark. Example
Now, do not compare Cassandra with any RDBMS. There is no concept of Relational in Cassandra. So, be careful. If you want to fetch data from Cassandra without much knowledge of Cassandra (similar to Hibernate), you may try Spark:
JavaRDD<Student> studentObj = CassandraJavaUtil.javaFunctions(sc).cassandraTable("schema", "student_table",CassandraJavaUtil.mapRowTo(Student.class)).where("id=1");
Remember, Spark is mainly for Analytics purpose.
I also found some new OGM tools that you may try:
http://hibernate.org/ogm/
https://github.com/impetus-opensource/Kundera
Yes Hibernate is supporting cassandra but it is still under experimental stage!!
so read the below notes carefully before you use it.
This implementation uses CQL3 over the native wire protocol with java-driver. The currently supported version is Cassandra 2.1.
To add the dependencies via Maven, add the following module:
<dependency>
<groupId>org.hibernate.ogm</groupId>
<artifactId>hibernate-ogm-cassandra</artifactId>
<version>5.0.4.Final</version>
To get started you will need to configure the following properties:
hibernate.ogm.datastore.provider
hibernate.ogm.datastore.host
hibernate.ogm.datastore.database
source
I have a system that uses a Oracle database, with a schema that is different from the application user. The schema name itself is not known in advance, so we can't just hardcode it. It's a system property.
Most of the data access is through Hibernate, which can specify the default schema on connection so this is not a problem in those cases.
However, there are a few places where plain SQL queries are used (using spring jdbcTemplate). So right now we have something that boils down to:
Map<String,Object> result = jdbcTemplate.queryForMap("SELECT A, B, C FROM "+schema+".TABLE WHERE blablablah");
And this, of course, is an open SQL injection vulnerability. We're planning security audits and this will be flagged for sure.
So the question is: How do I specify the schema on the query, be it with jdbcTemplate, another Sprint data access utility, or even plain jdbc?
Thank you,
JGN
You can use Connection.setSchema to specify the schema for a JDBC connection. This should be done before you create the Statement to execute a SQL command.