Save a list of objects to ORMLite database - java

I am looking for a way to save a list of objects to the database with ORMLite and read upon this question: Best way to store several ArrayLists in ORMLite for ApplicationSettings
And the accepted answer makes sense to me:
public class YourClass {
#GeneratedId
private int id;
#ForeignCollectionField
private Collection<MyString> bunchOfStrings = new ArrayList<MyString>();
}
public class MyString{
#DatabaseField(canBeNull = true, foreign = true)
private YourClass yourClass;
#DatabaseField
private String text;
}
And the only thing that I don't understand is this line private Collection<MyString> bunchOfStrings = new ArrayList<MyString>(). Why do we save the ForeignCollectionField as Collection<MyString> instead of as ArrayList<MyString>? When working with the bunchOfStrings object above, do we always need to cast it to ArrayList<MyString>?

Why do we save the ForeignCollectionField as Collection
instead of as ArrayList?
That was design consideration, excerpt from doc
The field type of orders must be either ForeignCollection<T> or Collection<T> – no other
collections are supported because they are much heavier with many methods to support
When working with the bunchOfStrings object above, do we always need
to cast it to ArrayList
You dont have to initialize that field, Ormlite will do that. Hence, only available methods are ones present in Collection or ForeignCollection

Related

Update java object's properties by another object of same type

can you give me example how to update values in one object by another object of same type? For example here is my class:
public class MyObj {
private int id;
private String name;
private String phone;
private String address;
// some getters and settters ...
}
And I have another class with that stuff:
private ArrayList<MyObj> objectsList; // list of some objects
public MyObj update ( MyObj newObj ) {
// here I need set new values of properties of newObj to object with same id property in objectsList;
}
Exist some way how to do that without manually setting up all properties?
You have to identify the object in the list by iterating on it or replacing by a Map<String, MyObj>
Exist some way how to do that without manually setting up all
properties?
Sure.
Reflection addresses it but reflection has a cost (it is slower) and it may fail at runtime or give a unexpected behavior.
You can do it manually or better use a library that does the task for you.
But in your case, to handle just 3 fields, it seems an overhead to use reflection.
Just use setters to set them :
MyObj existingObj = ...; // retrieved by a search
existingObj.setName(newObj.getName());
existingObj.setPhone(newObj.getPhone());
existingObj.setAddress(newObj.getAddress());
As alternative, if changing the reference of the object is not a concern, just replace the object actually in the list by which one provided in parameter :
int indexOfTheObject = ...; // retrieved by a search
objectsList.set(indexOfTheObject, newObj);

Assigning array of values to the corresponding objects dynamically

I have a question. I have 3 classes
public class cls1{
private String A;
private String B;
}
public class cls2{
private String C;
private String D;
}
public class cls3 extends cls1{
private String E;
private String F;
private cls2 cls2;
}
I have these 3 classes. cls1, cls2 are the normal classes but cls3 is extending cls1 and it has a component cls2.
I will query and get the results of cls3 from database but the output is in the form of "List". Object[] has all the cls3 parameters values. It includes cls1,cls2 parameters as well.
So here my question is how can I assign the values dynamically to all the classes. I will assign these values and I will use these values in some other place like "cls1.getA(), cls1.getB(), cls2.getC(), cls2.getD()" and so on.
So how can I assign array of values to these corresponding classes. I am thinking it's possible with BeanUtils. Is it possible with BeanUtils...?
Can anyone guide me on this please...
Use an ORM like hibernate. You need to map your domain model cls1,cl2,cls to your underlying persistence store using JPA. This is a much cleaner approach than rolling your own.

Nested generic collections

Without getting bogged down with specifics, my code represents a library whereby each book is made up of a Set of pages containing a Set of Words.
I have created my own Set implementations:
class PageSet<E> extends HashSet<E>(){
public boolean set(int index, E e){....}
....
}
and
class WordSet<E> extends HashSet<E>(){
public boolean set(int index, E e){....}
....
}
I've got stuck when I try to create a Book in my main class:
Set<Set<Word>> dictionary = new PageSet<WordSet<Word>>();
Which results in a type conversion mismatch. However it will quite happily accept
Set<Set<Word>> dictionary = new PageSet<Set<Word>>();
Could someone please shed some light as to what I'm doing wrong when using a generic setup like this?
Basically, a PageSet<WordSet<Word>> is not a Set<Set<Word>>, because X<Subclass> is not a X<Superclass>.
If you had said
Set<WordSet<Word>> dictionary = new PageSet<WordSet<Word>>();
then that would have worked also.
It's either
Set<Set<Word>> dictionary = new PageSet<Set<Word>>();
or
Set<WordSet<Word>> dictionary = new PageSet<WordSet<Word>>();
Since although WordSet is a subclass of Set, a Set<WordSet> is not a subclass of Set<Set>.
In other words, generics are not covariant, which is different from things like arrays.
In any case, you should not extend collections unless you are trying to create new collection types. Since you cannot restrict the visibilities of superclass methods in a subclass, people will be able to write
WordSet<Word> words = ...;
words.clear();
You probably do not want to give clients that power. Instead, use aggregation instead of inheritance.
class Word {
private String text;
private PartOfSpeech part;
// Constructors, getters, setters, equals, hashCode are elided.
}
class Page {
private int pageNumber;
private Set<Word> contents = new HashSet<>();
public class Book {
private String title;
private List<Page> pages = new ArrayList<>();
}
Pages in a book are ordered linearly, which is why I used lists. I'm not sure why you used sets. But in any case, by encapsulating the collections inside the classes, you can provide client code exactly the interface you want them to use. The visibilities were chosen deliberately; this looks like a cluster of related classes, but you might want to change them.

Gwt serialization

I have a class Data which implements Serializable interface. This class has such fields
private boolean q = false;
private String a = "";
private List<Someclass> m = Collections.emptyList();
private List<Object[]> d = Collections.emptyList();
Values assigned to these members are default values. Class Someclass also implements Serializable and it has such columns
private Types sqlType;
private int columnWidth;
private String columnName;
Types is an enum which also implements serializable.
In Data class I have List<Object[]> d in which I will save data fethced from database through jdbc(when iterating ResultSet i use getObject() method). I use such construction, because it can run any query(query's structure is not known). In List<Someclass> m I hold metada of query. So when I try to fetch rows with simple query I get
com.google.gwt.user.client.rpc.SerializationException: Type '[Ljava.lang.Object;' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = [Ljava.lang.Object;#127053a9
Why it occures? All my transfer objects are serializable.
edit
Ok, Object is not Serializable so it can not be passed to and returned from the server. But what I should use in this case. Generics will not help me, because I don't know the type at compile time
In order for the class to be serializable, essentially everything you can get to from it has to also be serializable. In this case Object is not serializable, which makes Object[] not serializable, which makes List not serializable, which makes Data not serializable.
Think about it this way: If you can't serialize a given Object in the Object[], how are you going to serialize the Object[]? And if you can't serialize that, how are you going to serialize a list of that? And if you can't serialize that list, how are you going to serialize something that contains that list?
Now, it could be that everything in your Object[] ends up being serializable -- but the way you've typed it, the compiler can't guarantee that.
EDIT: Regarding what you should use instead, I would create some sort of wrapper class that will hold the SQL query's results, and make that one serializable.
You can't use List here because Object[] is not serializable.
You need to create a different, Serializable class that can hold any column value you get from your query.
Perhaps something like:
public abstract class ColumnValue implements Serializable
{
public abstract Object getValue();
}
public class IntColumnValue extends ColumnValue
{
private Integer _intValue;
public Object getValue()
{
return _intValue;
}
}
.
.
.
You create a sub-class of ColumnValue for each column type that might be returned. When you have an array of Object[], you move that to an array of ColumnValue[], choosing the correct sub-type for each value based on the meta-data from the query.

Elegant way to assign object id in Java

I have a class for objects ... lat's say apples.
Each apple object mush have a unique identifier (id)... how do I ensure (elegantly and efficiently) that newly created has unique id.
Thanks
have a static int nextId in your Apple class and increment it in your constructor.
It would probably be prudent to ensure that your incrementing code is atomic, so you can do something like this (using AtomicInteger). This will guarantee that if two objects are created at exactly the same time, they do not share the same Id.
public class Apple {
static AtomicInteger nextId = new AtomicInteger();
private int id;
public Apple() {
id = nextId.incrementAndGet();
}
}
Use java.util.UUID.randomUUID()
It is not int, but it is guaranteed to be unique:
A class that represents an immutable universally unique identifier (UUID).
If your objects are somehow managed (for example by some persistence mechanism), it is often the case that the manager generates the IDs - taking the next id from the database, for example.
Related: Jeff Atwood's article on GUIDs (UUIDs). It is database-related, though, but it's not clear from your question whether you want your objects to be persisted or not.
Have you thought about using UUID class. You can call the randomUUID() function to create a new id everytime.
There is another way to get unique ID's. Instead of using an int or other data type, just make a class:
final class ID
{
#Override
public boolean equals(Object o)
{
return this==o;
}
}
public Apple
{
final private ID id=new ID();
}
Thread safe without synchronizing!

Categories