How to save Array of Integers in SQL database? - java

I have a problem with declaration with one of my fields in Object.
public class PhotoEntity {
#SerializedName("mentions")
public Array<Integer> mentions = new ArrayList<>();
// Other fields
}
mentions - is a part of incoming JSON, looks like :
[120,55,32]
I have a question. How correctly make projection of ArrayList in SQL database?
In the best case, as I know - I need to create separate Table and setup foreign key, but in my case it not be applicable, because the structure of PhotoEntity directly related to JSON contract.

Related

Polymorphically assign a class based on a variable

I have an abstract class, Foo, which Bars, Barz, and a bunch of others that hold some bits of data.
I am storing the data into several different tables in SQLite. I also wrote a small class that basically contains the java class that it "creates", the name of the table in the sqlite master and a pair for each column's name and column's data type to help with quickly turning records into objects when the application is running.
I would like to keep things as abstract as possible for re-usability. How could I create the correct subclass of the object with the correct data types by just having the table information from above for a single record from "that table" without an O(n) loop over each class (it's fast, but it's also hard coded for each class and it's a lot of typing).
SQLiteTable class:
class SQLiteTable<T>
{
...
SQLiteTable(String name, SQLiteColumn...columns)
...
}
JDBC SQLite abstract requested help:
...
public ArrayList<Foo> query(SQLiteTable table, String statement)
{
safeString = purgeOfFilt(statement);
statement = connection.prepareStatement(safeString);
results = statement.executeQuery();
ArrayList<Foo> records = new ArrayList<>();
while(results.next())
{
... // for loop to extract field information about the object I'd like to create
records.add(/*I'm not sure how to create the correct instance of the class here
(with the extracted fields--some of which are final at creation)*/));
}
}
...

Indexing a simple Java Record

I have a Java Object, Record . It represents a single record as a result of SQL execution. Can CQEngine index collection of Record ?
My class is of the form
public class Record {
private List<String> columnNames;
private List<Object> values;
... Other getters
}
I have looked through some examples, but I have no luck there.
I want to index only specific column(s) with its name and corresponding value. Can this be achived using cqengine or is there any other alternatives to achieve the same.
Thanks.
That seems to be a strange way to model data, but you can use CQEngine with that model if you wish.
(First off, CQEngine will have no use for your column names so you can remove that field.)
To do this, you will need to define a CQEngine virtual attribute for each of the indexes in your list of values.
Each attribute will need to be declared with the data type which will be stored in that column/index, and will need to be able to cast the object at that index in your list of values, to the appropriate data type (String, Double, Integer etc.).
So let's say your Record has a column called 'price', which is of type Double, and is stored at index 5 in the list of values. You could define an attribute which reads it as follows:
public static final Attribute<Record, Double> PRICE =
attribute("PRICE", record -> ((Double) record.values.get(5));
If this sounds complicated, it's because that way of modelling data makes things a bit complicated :) It's usually easier to work with a data model which leverages the Java type system (which your model does not). As such, you will need to keep track of the data types etc. of each field programmatically yourself.
CQEngine itself will work fine with that model though, because at the end of the day CQEngine attributes don't need to read fields, the attributes are just functions which are programmed to fetch values.
There's a bunch of stuff not covered above. For example can your values be null? (if so, you should use the nullable variety of attributes as discussed in the CQEngine docs. Or, might each of your Record objects have different sets of columns? (if so, you can create attributes on-the-fly when you encounter a new column, but you should probably cache the attributes you have created somewhere).
Hope that helps,
Niall (CQEngine author)

Retrieving online server databases by keys

As a intermediate Java student I have a question regarding retrieving single data pieces with a key from a larger document, uploaded online.
My idea is to create enum objects (public static final) and associate one ArrayList to each of enums in its constructor. All of the enums (with arrayLists) would then be uploaded onto the single larger online server database.
My wish is that every enum would serve as a key to retrieve appropriate (associated) arrayList in such document; meaning I would only like to retrieve arrayList one in a time (based on the enum as a key) and not the (whole) document itself. I would then like to add or remove elements from given arrayList and upload them back online.
How can I do that in the most effective fassion possible?
Thank you for your help and have a nice day :D
As far as my understanding and Assuming you want to use Enum and Arralyslist and store the Arralylist Object in Database.Try following below
You can simply create list from array like this:
List<String> list = Arrays.asList(SomeEnum.values());
Note :- Using JDBC API you can Connect to the DB and Insert the ArrayList Object using Insert query in the Database.

MySql Json object deserialisation optimization

I am having a field of type "text" in mysql and storing json data in it.
Eg:- "["android_app","iphone_app","windows_app"]";
I am interacting with mysql using hibernate and while reading this field I am deserializing it to an arraylist in Java.
My question is, is this the best and fastest way to handle such cases or there are some better ways of doing it.
If you're able to take advantage of some JPA 2.1 features, you could use anAttributeConverter to handle this for you automatically without having to deal with this in your business code.
public class YourEntity {
// other stuff
#Convert(converter = StringArrayToJsonConverter.class)
List<String> textValues;
}
Then you just define the converter as follows:
public class StringArraytoJsonConverter
implements AttributeConverter<List<String>, String> {
#Override
public string convertToDatabaseColumn(List<String> list) {
// convert the list to a json string here and return it
}
#Override
public List<String> convertToEntityAttribute(String dbValue) {
// convert the json string to the array list here and return it
}
}
The best part is this becomes a reusable component that you can simply place anywhere you need to represent a json array as a List<> in your java classes but would rather store it as JSON in the database using a single text field.
Another alternative would be to avoid storing the data as JSON but instead use a real table where that it would allow you to actually query on the JSON values. To do this, you'd rewrite that mapping using JPA's #ElementCollection
#ElementCollection
private List<String> textValues;
Internally, Hibernate creates a secondary table where it stores the text string values for the array with a reference to the owning entity's primary key, where the entity primary key and the string value are considered the PK of this secondary table.
You then either handle serializing the List<> as a JSON array in your controller/business code to avoid mixing persistence with that type of medium, particularly given that most databases have not yet introduced a real JSON data-type yet :).

Can Oracle DBMS return a Java object from a Java stored procedure call?

Can the Oracle database return a Java object from the return values of a Java stored procedure call?
I would like to query the Oracle database with a call to a java stored procedure and receive back java objects as the results. Is this possible? If so, could someone present a very simple example?
Note: I don't want to store serialized objects in the database. I want to run the Java stored procedure, and have this procedure return a Java object. So if the database is queried, each returned record will be a Java object.
For instance:
I want the Java stored procedure to parse a binary file that is stored in a network shared drive, build a Java object with the information extracted from the binary file, and return this Java object as the query result.
I want to achieve something like this:
#Using Java or Python programming language
results = execute( Select java_procedure_call(parameter) From dual);
For java_obj in results:
print java_obj.name
print java_obj.city
Other information:
I am not using Java EE.
Thanks in advance.
What you need to do is, serialize and de-serialize java objects to and from Oracle database table. You can store the serialized object bytes in Oracle table using BLOB column type. Here is a link describing how you can store and retrieve java objects from a table.
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::p11_question_id:1285601748584
You can store any serializable data in Databases from text files, ,images to Java Objects. Basic logic here,any data is serialized to a byte stream and stored in DB. They are deserialized when fetching from DB. If you really want to this you can skip my answer. However, mapping database fields to Java classes is a better solution and my explanation will be in this direction.
You shoud use a Object Relational Mapping(ORM) framework for this purpose. It can be Hibernate, JPA or Spring JDBC Template. One of them can be used according to your requirements.
If you do not want to use any framework you can basically implement it.
Implement the structure for 2 fields such as username and password. I assume that both fields are String
First, you should have a model class which will be mapped o query results.
class Model
{
private String username;
private String password;
//setter and getters.
}
Secondly, you should implement a Factory pattern to create Java objects from query results.
class BasicModelFactory
{
public List<Model> getModels(ResultSet rs)
{
List<Model> models = new ArrayList<Model>();
while(rs.next())
{
Model m = new Model();
m.setUsername(rs.getString("username");
m.setPassword(rs.getString("password");
models.add(m);
}
return models;
}
}

Categories

Resources