LiteDb class deserialization is not working - deserialization

I have B class that has a class A as member. The LiteDb store it correctly as I see in LiteDB Studio. "As" collection is also OK. Why is it not right in the deserialization? Class A has a BsonCtor. B also
namespace ConsoleAppTestDeserializatioBug {
class Program {
public class A {
public A() { A_ID = ObjectId.NewObjectId(); }
[BsonCtor]
public A(ObjectId id, string name) { A_ID = id; Name = name; }
[BsonId]
public ObjectId A_ID { get; set; }
public string Name { get; set; }
public const string CollectionName = "As";
}
public class B {
public const string CollectionName = "Bs";
public B() { B_ID = ObjectId.NewObjectId(); }
[BsonCtor]
public B(ObjectId id, int dummy, A a) { B_ID = id; Dummy = dummy; aObj = a;}
[BsonId]
public ObjectId B_ID { get; set; }
public int Dummy { get; set; }
[BsonRef(A.CollectionName)]
public A aObj { get; set; }
}
private LiteDatabase _LiteDatabase;
static void Main(string[] args) {
var p = new Program();
p.Test();
}
private void Test() {
A a = new A(); // Create my Object
a.Name = "Name123";
var initialId = a.A_ID;
B b = new B();
b.Dummy = 123;
b.aObj = a;
_LiteDatabase = new LiteDatabase(new ConnectionString(#"C:\Temp\tst1.db") { Connection = ConnectionType.Shared });
ILiteCollection<A> aas = _LiteDatabase.GetCollection<A>(A.CollectionName);
aas.Insert(a);
ILiteCollection<B> bs = _LiteDatabase.GetCollection<B>(B.CollectionName);
bs.Insert(b);
// Get in the DB
var bb = bs.FindAll().ToArray()[0];
var aa = bb.aObj;
var aaid = aa.A_ID;
if (aaid == initialId) { Console.WriteLine("Id is correct");}
var aname = aa.Name; // aname i s null!!!!! and why
}
}
}

I found an answer in LiteSB DbRef
I must just add an "include" in my query:
var bb = bs.Include(x => x.aObj).FindAll().ToArray()[0];

Related

List not being saved

I'm trying to save a list of question options but its not being saved. Only the last row is being save.
Below is the code.
#Transactional
public void addQuestionOptions(QuestionOptionsRequest questionOptionsRequest, int questionId) {
List<QuestionOption> optionList = new ArrayList<>();
QuestionOption options = new QuestionOption();
Question question = questionRepository.findByQuestionId(questionId);
if(question != null) {
questionOptionsRequest.getQuestionOptions()
.stream()
.forEach(option -> {
options.setQuestionOption(option.getQuestionOption());
options.setQuestion(question);
options.setQuestionOptionNumber(option.getQuestionOptionNumber());
optionList.add(options);
});
questionOptionRepository.saveAll(optionList);
}
}
QuestionOption
#Entity
#JsonIgnoreProperties({"question"})
public class QuestionOption {
#Id
#GeneratedValue
private int questionOptionId;
private int questionOptionNumber;
private String questionOption;
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
#ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private Question question;
public void setQuestionOptionNumber(int questionOptionNumber)
{
this.questionOptionNumber = questionOptionNumber;
}
public void setQuestionOption(String questionOption)
{
this.questionOption = questionOption;
}
public String getQuestionOption()
{
return this.questionOption;
}
public int getQuestionOptionNumber()
{
return this.questionOptionNumber;
}
public int getQuestionOptionId() {
return questionOptionId;
}
public void setQuestionOptionId(int questionOptionId) {
this.questionOptionId = questionOptionId;
}
}
Question
#Entity
#Getter
#Setter
public class Question {
#Id
#GeneratedValue
private int questionId;
private int assessmentId;
private QuestionTypes questionType;
private String questionText;
private String questionURL;
private QuestionStatus questionStatus;
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="question")
private List<QuestionOption> questionOptions;
public void setQuestionId(int queId)
{
this.questionId = queId;
}
public void setQuestionText(String queTxt)
{
this.questionText = queTxt;
}
public void setQuestionType(QuestionTypes queType)
{
this.questionType = queType;
}
public void setQuestionURL(String queURL)
{
this.questionURL = queURL;
}
public int getQuestionId() {
return questionId;
}
public String getQuestionText() {
return questionText;
}
public QuestionStatus getQuestionStatus() {
return questionStatus;
}
public void setQuestionStatus(QuestionStatus questionStatus) {
this.questionStatus = questionStatus;
}
public QuestionTypes getQuestionTypes() {
return this.questionType;
}
public String getQuestionURL() {
return this.questionURL;
}
public int getAssessmentId() {
return this.assessmentId;
}
public void setAssessmentId(int assessmentId) {
this.assessmentId = assessmentId;
}
public QuestionTypes getQuestionType() {
return questionType;
}
}
You are creating only one object of QuestionOption
QuestionOption options = new QuestionOption();
Create this object inside for each.

Spring Data MongoDB - filtering counting and summing sub-document arrays

Given a MongoDB collection described by the following classes:
#Document(collection = "persons")
#TypeAlias("person")
public class Person {
#Id
private ObjectId _id = null;
private String personName = null;
private List<Account> accountsList = null;
public ObjectId getId()
{
return _id;
}
public void setId(ObjectId id)
{
this._id = id;
}
public String getPersonName()
{
return personName;
}
public void setPersonName(String personName)
{
this.personName = personName;
}
public List<Account> getAccountsList()
{
return accountsList;
}
public void setAccountsList(List<Account> accountsList)
{
this.accountsList = accountsList;
}
}
public class Account
{
#Indexed(unique = false)
private double amount = 0.0;
private String description = null;
public double getAmount()
{
return amount;
}
public void setAmount(double amount)
{
this.amount = amount;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
}
Using Spring Data Mongodb, how do I:
1) count the number of accounts only where the amount > x
2) retrieve only the accounts where the amount > x
3) sum the total amount of accounts only where the amount > x
Any help will be appreciated

Persisting a Joint Table in JPA

I have three entities, Trader, Portfolio and Member. Each Trader has a Portfolio and a Portfolio can have many Members. I have set up the following relationships. I'm not sure how to use the Jointable that is created, i.e. Portfolio_PORTFOLIOID and members_MEMBERID. Obviously I'd like to associate each portfolid with member id's, however I'm not sure how to go about this. How is the jointable data persisted?
My Portfolio class
#Entity
#Table(name="Portfolio")
#NamedQuery(
name="findPortfolioByTrader",
query="SELECT p FROM Portfolio p" +
" WHERE Trader = :trader"
)
public class Portfolio {
#Id
#GeneratedValue
private Integer portfolioId;
#Temporal(TIMESTAMP)
private Date lastUpdate;
private Integer balance;
private Trader trader;
private Collection<Member> members;
public Portfolio() {
this.lastUpdate = new Date();
}
public Portfolio(Integer balance, Trader trader) {
this.lastUpdate = new Date();
this.balance = balance;
this.trader = trader;
}
public Integer getPortfolioId() {
return portfolioId;
}
public void setPortfolioId(Integer portfolioId) {
this.portfolioId = portfolioId;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
#ManyToMany
#JoinTable(
name="MEMBER_PORTFOLIO",
joinColumns=
#JoinColumn(name="Member_MEMBERID", referencedColumnName="MEMBERID"),
inverseJoinColumns=
#JoinColumn(name="portfolio_PORTFOLIOID", referencedColumnName="PORTFOLIOID")
)
public Collection<Member> getMembers() {
return members;
}
public void setMembers(Collection<Member> members) {
this.members = members;
}
#OneToOne(cascade=ALL, mappedBy="portfolio")
public Trader getTrader()
{
return trader;
}
public void setTrader(Trader trader)
{
this.trader = trader;
}
public Integer getBalance() {
return balance;
}
public void setBalance(Integer balance) {
this.balance = balance;
}
}
My Member class
#Entity
#Table(name="Member")
#NamedQuery(
name="findAllMembers",
query="SELECT m FROM Member m " +
"ORDER BY m.memberId"
)
public class Member implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -468520665316481235L;
private String memberId;
private String forename;
private String surname;
private Integer position;
private Integer majority;
private Integer IPO;
private Integer questions;
private Integer answers;
private Party party;
private Date lastUpdate;
private char status;
private Collection<Portfolio> portfolios;
private Collection<AskOrder> askOrders;
private Collection<BidOrder> bidOrders;
public Member() {
this.lastUpdate = new Date();
}
public Member(String memberId,String forename, String surname, Integer position,
Integer majority, Integer IPO, Integer questions, Integer answers, Party party) {
this.memberId = memberId;
this.forename = forename;
this.surname = surname;
this.position = position;
this.majority = majority;
this.IPO = IPO;
this.questions = questions;
this.answers = answers;
this.party = party;
this.lastUpdate = new Date();
this.askOrders = new ArrayList<AskOrder>();
this.bidOrders = new ArrayList<BidOrder>();
this.portfolios = new ArrayList<Portfolio>();
}
#Id
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public char getStatus() {
return status;
}
public void setStatus(char status) {
this.status = status;
}
#Temporal(TIMESTAMP)
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public String getForename()
{
return forename;
}
public void setForename(String forename)
{
this.forename = forename;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public Integer getMajority() {
return majority;
}
public void setMajority(Integer majority) {
this.majority = majority;
}
public Integer getIPO() {
return IPO;
}
public void setIPO(Integer iPO) {
IPO = iPO;
}
public Integer getQuestions() {
return questions;
}
public void setQuestions(Integer questions) {
this.questions = questions;
}
public Integer getAnswers() {
return answers;
}
public void setAnswers(Integer answers) {
this.answers = answers;
}
#ManyToOne
public Party getParty() {
return party;
}
public void setParty(Party party) {
this.party = party;
}
#OneToMany(cascade=ALL, mappedBy="member")
public Collection<AskOrder> getAskOrders()
{
return askOrders;
}
public void setAskOrders(Collection<AskOrder> orders)
{
this.askOrders = orders;
}
#OneToMany(cascade=ALL, mappedBy="member")
public Collection<BidOrder> getBidOrders()
{
return bidOrders;
}
public void setBidOrders(Collection<BidOrder> bidOrders)
{
this.bidOrders = bidOrders;
}
#ManyToMany //FIXME should probably be many to many - done
public Collection<Portfolio> getPortfolios() {
return portfolios;
}
public void setPortfolios(Collection<Portfolio> portfolios) {
this.portfolios = portfolios;
}
}
#Entity
public class Portfolio
{
#Id
#GeneratedValue
private int id;
#ManyToMany
#JoinTable( name = "PortfolioMember",
#JoinColumns : #JoinColumn( name = "Portfolio_ID", referencedColumnName="id" ),
#InverseJoinColumns : #JoinColumn( name = "Member_ID", referencedColumnName="id" )
)
private List<Member> members;
}
#Entity
public class Member
{
#Id
#GeneratedValue
private int id;
#ManyToMany( mappedBy = members )
private List<Portfolio> portfolios;
}

JavaFX properties fail to persist

I'm using some JavaFX properties in my app:
#Entity(name = "Klanten")
#Table(name = "Klanten")
#NamedQueries({
#NamedQuery(name = "Klanten.findAll", query = "select k from Klanten k")
})
public class Klant implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int klantId;
#Transient
private final SimpleStringProperty naam = new SimpleStringProperty();
//private String naam;
//private String straat;
#Transient
private final SimpleStringProperty straat = new SimpleStringProperty();
private String telefoon;
private String huisnummer;
private String gsm;
private String woonplaats;
private String email;
private String postcode;
#OneToMany(mappedBy = "Klant", cascade = CascadeType.REMOVE)
private List<Raam> ramen;
public Klant() {
}
public Klant(String naam) {
this.naam.set(naam);
}
#Override
public String toString() {
return this.naam.get();
}
#Access(AccessType.PROPERTY)
#Column(name="naam")
public String getNaam() {
return this.naam.get();
}
public void setNaam(String naam){
this.naam.set(naam);
}
public List<Raam> getRamen() {
return this.ramen;
}
#Id
public int getKlantId() {
return klantId;
}
public void setKlantId(int klantId) {
this.klantId = klantId;
}
#Access(AccessType.PROPERTY)
#Column(name="straat")
public String getStraat() {
return straat.get();
}
public void setStraat(String straat) {
this.straat.set(straat);
}
public String getTelefoon() {
return telefoon;
}
public void setTelefoon(String telefoon) {
this.telefoon = telefoon;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer(String huisnummer) {
this.huisnummer = huisnummer;
}
public String getGsm() {
return gsm;
}
public void setGsm(String gsm) {
this.gsm = gsm;
}
public String getWoonplaats() {
return woonplaats;
}
public void setWoonplaats(String woonplaats) {
this.woonplaats = woonplaats;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public StringProperty naamProperty() {
return naam;
}
public StringProperty straatProperty() {
return straat;
}
}
However when I let JPA generate my database, the column "naam" and "straat" aren't generated. I get no error. How can I resolve this?
I tried all the things listed here:
Possible solution 1
Possible solution 2
These didn't work.
You can try to use regular properties and then have another get method which returns a new SimpleStringProperty, i.e.:
public StringProperty naamProperty() {
return new SimpleStringProperty(naam);
}
public StringProperty straatProperty() {
return new SimpleStringProperty(straat);
}

How to add & update within entity framework

my Model Entity FrameWork :
public partial class T02
{
public long ID { get; set; }
public int F01 { get; set; }
}
Table : T02
------------------------
id[Key,identity] F01
------------------------
1 a
2 b
====================================================
i have a button > Code
public void Button_Click(object Sender, EventArgs e)
{
T02 T1 = new T02 { ID = 1, F01 = "x" };
T02 T2 = new T02 { ID = 2, F01 = "y" };
T02 T3 = new T02 { ID = 0, F01 = "g" };
T02 T4 = new T02 { ID = 0, F01 = "h" };
// How ID > 1 2 Update in Table &
// because not in table, > g , h > automatic add to Table
// ???
}
my problem is : i not ontime update and if T02.ID not on the table automatic added..
Is it possible that I do added to table Records Without id and i do Update Records With id
i worked c#.NET 4.5 . Thanks
Add this method to your Context class:
protected virtual void InsertOrUpdate<T>(T entity, long id)
{
if (id == default(int))
this.Set<T>().Add(entity);
else
this.Entry(entity).State = EntityState.Modified;
}
Which can be used something like this:
public void Button_Click(object Sender, EventArgs e)
{
T02 T1 = new T02 { ID = 1, F01 = "x" };
T02 T2 = new T02 { ID = 2, F01 = "y" };
T02 T3 = new T02 { ID = 0, F01 = "g" };
T02 T4 = new T02 { ID = 0, F01 = "h" };
using(var context = new MyDbContext())
{
context.InsertOrUpdate(T1, T1.ID);
context.InsertOrUpdate(T2, T2.ID);
context.InsertOrUpdate(T3, T3.ID);
context.InsertOrUpdate(T4, T4.ID);
}
}
Once this is working you can consider implementing a standard interface across all of your POCO classes that exposes the ID property so that you no longer have to pass ID into the method:
public interface IId
{
long ID { get; }
}
public partial class T02 : IId
{
public long ID { get; set; }
public int F01 { get; set; }
}
which gives you a neater method in your Context
protected virtual void InsertOrUpdate<T>(T entity) where T : IId
{
if (entity.ID == default(int))
this.Set<T>().Add(entity);
else
this.Entry(entity).State = EntityState.Modified;
}