how to dynamically query database via web? - java

Can you recommend on a framework which enable querying of data via web?
Requirements:
ORM capabilities - I want that the representation of the model at the server & client will not be dependent.
For example: let's say that the server will return to the client layer the following model: transaction (firstName, lastName, description, amount). While in the dal-layer it's being saved like this: Customer(Id, fName, lName, address) , Transaction(id, CustomerId, description, amount)
Option to write my own query provider (For example: HiveQL, SQL & etc).
I have tried to use the following frameworks (but it's seems like it, that the first demand is not supported):
JayData: http://jaydata.org/
breezejs: http://www.breezejs.com/
Thanks in advance.

Breeze does provide this but you will need to write the server side code that translates an OData query into a query that your chosen server implements. We already provide several implementations of this code for different server/database technologies and plan on doing more in the future.
To date we have done this for .NET servers with both Entity Framework and NHibernate ORM's and against Node servers with MongoDB backends. We also have other developers working on a Ruby server implementation. If you want to write your own, you should probably take a look at the Breeeze/MongoDB source to see how this is done.
Alternately, if your chosen server tech already has an OData provider, then Breeze can talk to it.

OData does provide a way to query database via web, such as
GET http://myservice/Products?$filter=Id gt 3 and contains(Name,'abc')
GET http://myservice/Products?$select=Id,Name,Provider&$orderby=ManufactureDate desc
Here are some odata samples https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/. In a controller, you can use what ever framework/provider you like to retrieve data from persistence.
If you want to use Entity Framework please follow this one:https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataActionsSample/.

Related

Spring Data CosmosTemplate create query with System Functions

We are trying to implement a query with cosmosTemplate from spring-data-cosmosdb project.
The query has the following syntax:
"select * from movie where ARRAY_CONTAINS(movie.countries, #country)".
CosmosTemplate accepts DocumentQuery object, that is build upon Criteria object. Criteria object supports a small subset of basic predicates like in, or, is equal and etc., but doesn't have array_contains predicate.
At the moment the query is performed by using cosmos client(from sdk), instead of cosmosTemplate.
This brings us two issues:
We have to mix the code by using cosmosTemplate and cosmos client together.
Since we have complex parameterized queries that use system functions, we have to concatenate sql query string and gather sql parameters.
How queries like this should be handled with cosmosTemplate and is that even possible?
P.S we are using com.microsoft.azure:azure-cosmosdb-spring-boot-starter:2.2.5 library.
In the current GA release you will have to use the Client and template together like you mentioned.
The latest beta release includes support for QueryAnnotation Using annotated queries in repositories. Following is an example:
#Query(value = "select * from c where c.firstName = #firstName and c.lastName = #lastName")
List<User> getUsersByTitleAndValue(#Param("firstName") int firstName, #Param("lastName") String lastName);
Ravi's answer is correct. To create custom queries directly from Spring Data connector, there are current two options.
First, you can follow the instructions in the "Custom Query" section of this document
https://learn.microsoft.com/en-us/azure/developer/java/spring-framework/how-to-guides-spring-data-cosmosdb
which guide you through using the Java SDK CosmosClient directly. The current GA release of Spring Data connector does not have #Query annotation which would enable custom query annotation, that is why you need to use the Java SDK directly.
Second, upgrade to the latest beta which enables #Query annotation
https://mvnrepository.com/artifact/com.azure/azure-spring-data-cosmos
Sample code for this will be released in the next few days, and the GA release is scheduled for 9/30 so it is not a long wait.
After a research in azure sdk, I've found that at the moment not all system functions are supported by cosmosTemplate.
List of supported system functions can be found there:
https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CriteriaType.java
If you wan't to write query that uses system function, that isn't in the list in the link above, you can use either #Query annotation or directly use cosmos client instead of cosmosTemplate.

How to make a connection between an external mysql database and then call in for specific data queries

I am working on a springboot project and I am a total newbie in this. We are told to complete the project within a given time period and the deadline is in 3 days. I have a string which will contain the username. I am said that there will be an external database from where we have to fetch the data of that user and return that to the application. We are working on a web api.
Till now I have somehow extracted the username from the encoded data but now I am unable to proceed further. All the resources available online are related to building a repository and their own data and use that in the program but I have to use it from an external database. I don't know anything about this and is completely stuck.
The external database is a sample and includes an id , username and data. From the username we have to search the database and return all the three details as a JSON format of that user.
Well that was simple in SQL but I don't know how that can be performed from the point where I am now.
Thank You.
There is a special file called application.properties in Spring Boot, where you can define your authorization data to get connection with your remote database.
Usually, you should specify basic data:
spring.datasource.url=jdbc:mysql://url-to-your-external-db/name-of-db
spring.datasource.username=your_username
spring.datasource.password=your_pasword
After that, you could retrieve your data from database using JpaRepository for example. There is plenty of frameworks that will serialize/deserialize your Java objects/entities to JSON (Jackson for example).
Example of fetching users from a database using JpaRepository:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByFirstName(String firstName)
}
where User could be your POJO which represents a table with users in database.

Query with dynamic schema without using string concatenation

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.

Spring Data Rest API dependance and problems in n-tier

I like what Spring Data Rest provides out of the box but I see a few design problems that I'd like to address prior to using it for my next project:
SDR's main drift seems to be to expose data repositories straight out over MVC. I consider this to be a flawed approach because you end up tying your API to whatever your DB says. Consider this in your DB:
TABLE customer {
fullName TEXT
}
Under spring data rest that will end up being exported to for eg:
{
"fullname": "foo"
}
now suppose I decide to change my DB table to say:
TABLE customer {
firstName TEXT
lastName TEXT
}
that is, I split the field in two: suddenly my client-facing API has been modified. If I had better control I'd be delivering ApiCustomer object which contains:
ApiCustomer{
String fullname;
}
and during mapping I get the chance to say that fullName is now firstName + lastName leaving my customer-facing API unchanged. Is it possible for me to hook into a conversion process so as to make sure this doesn't occur?
Let's say I want to develop an N-tier application where I have an MVC module that handles all HTTP/REST/validation bits and a core module which has links to DB. The two modules live in different JVMs and are connected to each other with, for eg, rabbitmq or whatever.
Unless I'm missing something, Spring Data Rest wants me to place repositories in the MVC module where I do not have any database components at all. I cannot figure out a way to tell it: these are the repositories you will have somewhere else, whenever you need to do something on them, ask me first so I get a chance to proxy to the Core module.
Am I going down the wrong path here?
This new spring project seems to fit the bill very well for this:
http://docs.spring.io/spring-data/keyvalue/docs/current/reference/html/

Java - Sync different entities between Client-Server database (JPA2+EJB3)

can someone help me plz?
i am trying to get a synchronization between N "clients" database to 1 Big "Server" database (kind of repository/backup database).
Its ok, i got a way to make their sync fine.
but, it was demanded the "Server" will be a "Client" application too, with same Java classes, models, entities, business, etc..
I am trying to find a solution to this Server database holds all database content from all Clients without making major changes to my entities (cause i will need to apply then on Client too)
This is an example of what i tried, but no success how to implement it on JPA and Serialization through EJB remotes.
#Entity
#Table(name="crud_sync")
public class CrudSync implements Serialization{
private static final long serialVersionUID = 1L;
#Id private Long id;
private String data;
//...ommited...
}
supposing i have this CrudSync entity.
On the N clients side database, i would have a table with columns:
ID - Number - PK
Data - Varchar
etc...
on the 1 Server side, i would like to have a table with:
ID - Number - PK
ClientPK - Number // the ID on Client database table
ClientId - Number // the Client code (1,2,3,4.. etc..)
// UQ (ClientPK,ClientID)
Data - Varchar
etc...
or even a composite PK
ClientPK - Number - PK // the ID on Client database table
ClientId - Number - PK // the Client code (1,2,3,4.. etc..)
Data - Varchar
etc...
but i am not sure how to achieve that using the same Entities on both sides, if its even possible..
another solution could maybe create separated JAR/EAR for Client and Server.
doing that, what should i change in Entities/JPA annotations?
what class should be separated to Client/Server JAR/EAR ?
Any other suggestion on how to make a (N Client <-> 1 Server) database?
Its mandatory to Clients work offline, so they need to have their own Database running, also its mandatory to have the same application on Server, because it will be possible to create entities on Server and those will be sent to Client (vice-versa).
I am using JBoss AS 7.1, JPA 2, EJB 3.1.
Thanks in advance.
Anon.
Off the cuff, not sure if it's possible to use the same JPA entities to do that. The logic is probably going to be sophisticated enough where you might want it to reside in the application and not the database.
That said, you could use a decorator pattern so the server/client application can use the same core JPA entities. Then have server-specific JPA entities that decorate the core entities and persist the data required to manage the synchronization between the client and server applications. The decorator objects simply contain a reference to the core object. Then whatever data it requires to facilitate the push and pull of data between server and client.
Hope this helps

Categories

Resources