can somebody confirm me following?
I have following Entites:
public class Book {
.............
}
public class Student {
#OneToOne
Book favoriteBook
}
public class StudentOrderHistory{
Student student;
#OneToOne
Book lastBook;
}
In case if favoriteBook / lastBook is linked only to each one Student or StudentOrderHistory is both then still a #OneToOne relation or would it a #ManyToOne Relation because the same BookEntity is linked in several Entites (here Student and StudentOrderHistory)?
Is it correct that #ManyToOne would be more in case e.g the same book is the favoriteBook for different Students?
I assume that many students could have the same favourite book, this makes it a many-to-one:
public class Student {
#ManyToOne
Book favoriteBook
}
This means that two different students can have the same book as their favourites.
Example: John and Jane favourite book is "Moby Dick"
Unless a Student can have multiple order histories, I would say that that's a one-to-one:
public class StudentOrderHistory{
#OneToOne
Student student;
}
Because the history of orders is unique for each students.
Not sure about lastBook though.
If it means that a student has the book and nobody else can have it as lastBook, than it's a one-to-one:
public class StudentOrderHistory{
#OneToOne
Student student;
#OneToOne
Book lastBook;
}
This book only belongs to this StudentOrderHistory and therefore to a single student.
If you mean the last book they've ordered and in the meanwhile, somebody else has ordered the same book, than it's a many-to-one:
public class StudentOrderHistory{
#OneToOne
Student student;
#ManyToOne
Book lastBook;
}
It seems that two different students could order the same book, but without knowing more it's hard to say which solution is correct.
Related
I am using play 2.3.8 and building a program where you can ask questions and answer them. I have several different users, so I use their unique email as the ID in the database.
Questions / answers have an ownerID, to show who has written them.
My users are stored in the DB like this:
Email Name Password
bob#mail.com Bob secret
My questions are stored in the DB like this:
QUESTION_ID QUESTION_TEXT VOTE_SCORE OWNER_ID PAGE
77b7f88a-41df-4d68-9f89-de508fce8f71 How tall is tall? 1228 bob#mail.com 1
My controller class, that collects the questions / answers from the DB and sends the lists to the view class:
public static List<Question> questionListAll = new ArrayList<Question>();
public static List<Answer> answerListAll = new ArrayList<Answer>();
public static Result index() {
questionListAll.clear();
answerListAll.clear();
// Get all questions from DB
for (Question questionItem : Question.find.all()) {
questionListAll.add(questionItem);
}
// Get all answers from DB
for (Answer answerItem : Answer.find.all()) {
answerListAll.add(answerItem);
}
Collections.sort(questionListAll, Collections.reverseOrder());
Collections.sort(answerListAll, Collections.reverseOrder());
return ok(views.html.index.render(questionListAll, answerListAll));
}
User.java:
// FIXME Dont really save the password as String...
#Id
public String email;
public String name;
public String password;
(...)
Question.java:
#Entity
public class Question extends Model implements Comparable<Question> {
#Id
public String questionID;
public String questionText;
public Integer voteScore;
public String ownerID;
public Integer page;
(...)
}
In my view class I show the questions and behind them the user by using #answer.ownerID ... but as I use the email-field as ID, the entry is something like:
"How tall is tall?" - bob#mail.com
What I want is:
"How tall is tall?" - Bob Ross (using their name and not their email)
I know I could simply find all questions and their owners in my controller and put the users into another list, from where I would use #users.username, but this would mean I always have to look up all users, put them into the list, ...
So is it possible to look into the DB, use the ownerID and get the username in the view class?
Or more general: Can you look up DB entries for the view class from the view class itself?
You may add mappings with JPA 2.0 to achieve what you want in your view, then you may use #question.owner.name or #answer.owner.name.
User.java
[...]
#Id
#Column(name="user_id")
public Long userId;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "owner", cascade = CascadeType.ALL)
public List<Question> questionList;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "owner", cascade = CascadeType.ALL)
public List<Answer> answerList;
[...]
Question.java
[...]
#Id
#Column(name="question_id")
public Long questionId;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="user_id", nullable = false)
public User owner;
// #OneToMany: ORM join relationship, one Question to many Answers
// FetchType.LAZY: ORM will not fetch from db until you use it
// CascadeType.ALL: any changes to question will be propagated
// onQuestionDelete: all answers associated with the question will be deleted
// onQuestionUpdateAnswerList: any updates made will reflect on db
// mappedBy: Question object variable name on Answer object for ORM to make a connection
#OneToMany(fetch = FetchType.LAZY, mappedBy = "question", cascade = CascadeType.ALL)
public List<Answer> answerList;
[...]
Answer.java
[...]
#Id
#Column(name="answer_id")
public Long answerId;
// FetchType.EAGER: ORM will fetch this from db when Answer is fetch
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="user_id", nullable = false)
public User owner;
// #ManyToOne: ORM join relationship, many Question to one Answer
// #JoinColumn: name, pk column name of Question; nullable false, required constraint;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="question_id", nullable = false)
public Question question;
[...]
I have been trying to do that for the last hour and still can get it to work.
I'm trying to create a multi depth array. Let me explain myslef.
Boss
Manager
Employee
Employee
Employee
Manager
Employee
Employee
Employee
Boss
Manager
Employee
Employee
Employee
Manager
Employee
Employee
Employee
Boss
Manager
Employee
Employee
Employee
Manager
Employee
Employee
Employee
and they must have a label, here it would be Boss, Manager or Employee's name.
Is there any way to do this ?
Thanks
Might be better just to have a class that represent a hierarchy of a person with a list of people underneath them. Personally, a multidepth array can be a bit complicated especially for the person that is going to maintain the code.
Sub Main()
Dim bosses As New List(Of Hierarchy)
bosses.Add(New Hierarchy)
bosses(0).Person = New Person
bosses(0).Person.Name = "Boss"
bosses(0).Childs.Add(New Hierarchy)
bosses(0).Childs(0).Person = New Person
bosses(0).Childs(0).Person.Name = "Manager"
bosses(0).Childs(0).Childs.Add(New Hierarchy)
bosses(0).Childs(0).Childs(0).Person = New Person
bosses(0).Childs(0).Childs(0).Person.Name = "Employee"
bosses(0).Childs(0).Childs.Add(New Hierarchy)
bosses(0).Childs(0).Childs(1).Person = New Person
bosses(0).Childs(0).Childs(1).Person.Name = "Employee"
For Each boss In bosses
Console.WriteLine(boss.Person.Name)
For Each manager In boss.Childs
Console.WriteLine(" " & manager.Person.Name)
For Each employee In manager.Childs
Console.WriteLine(" " & employee.Person.Name)
Next
Next
Next
End Sub
Class Hierarchy
Public Person As Person
Public Childs As New List(Of Hierarchy)
End Class
Class Person
Public Name As String
End Class
Here is how I managed to do this:
Public Class sousdir
Public name As String
Public services As New List(Of String)
End Class
Public Class direction
Public name As String
Public sousdirs As New List(Of sousdir)
End Class
Dim directions As New List(Of direction)
directions.Add(New direction)
directions(0).name = "Direction 1"
directions(0).sousdirs.Add(New sousdir)
directions(0).sousdirs(0).name = "Sous Direction 1"
directions(0).sousdirs(0).services.Add("Service 1")
directions(0).sousdirs(0).services.Add("Service 2")
directions(0).sousdirs(0).services.Add("Service 3")
directions(0).sousdirs.Add(New sousdir)
directions(0).sousdirs(1).name = "Sous Direction 2"
directions(0).sousdirs(1).services.Add("Service 1")
directions(0).sousdirs(1).services.Add("Service 2")
...
With result formatting
How this will help some people
I have the following domain classes:
class Patient {
...
}
class Receipt{
#NotNull
static belongsTo = [patient:Patient]
...
}
If I try to delete a Patient instance (after creation of Receipt instances), I have a MySQLIntegrityConstraintViolationException. Notice that a patient can have zero-to-many receipts.
To complete the parent child relationship, create a has many section in the parent domain class:
class Patient {
static hasMany = [receipts: Receipt]
...
}
class Receipt{
#NotNull
static belongsTo = [patient:Patient]
...
}
I can't seem to find documentation or examples for my problem (been searching a while now). I think my problem is pretty straightforward, so here goes.
I have two tables. My primary table is called Persons and the secondary table is PersonEntries. For each person in Person table, i can have 0 or more entries in the PersonEntries table. Like this.
Table: Person
Id
Name
Table: PersonEntry
PersonId
CheckinTime
CheckoutTime
I have two objects like this
public class Person {
public string Name;
public List<PersonEntry> PersonEntries;
}
public class PersonEntry {
public DateTime CheckinTime;
public DateTime CheckoutTime;
}
If i was to get it from the database into my c# classes how would i do it? I can map a single table into my c# class and do it for each table, but then i'm left to match what entries maps to what person.
I've seen several examples of mapping ONE PersonEntry to ONE Person, the problem here is that i have a zero-to-many relation. My Person have a LIST of PersonEntry items.
You can do something like this (see https://www.tritac.com/blog/dappernet-by-example):
public class Shop {
public int? Id {get;set;}
public string Name {get;set;}
public string Url {get;set;}
public IList<Account> Accounts {get;set;}
}
public class Account {
public int? Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
public string Country {get;set;}
public int ShopId {get;set;}
}
var lookup = new Dictionary<int, Shop>()
conn.Query<Shop, Account, Shop>(#"
SELECT s.*, a.*
FROM Shop s
INNER JOIN Account a ON s.ShopId = a.ShopId
", (s, a) => {
Shop shop;
if (!lookup.TryGetValue(s.Id, out shop)) {
lookup.Add(s.Id, shop = s);
}
if (shop.Accounts == null)
shop.Accounts = new List<Account>();
shop.Accounts.Add(a);
return shop;
}
).AsQueryable();
var resultList = lookup.Values;
I had made a class in C# Windows form to represent my database.
It has a master/detail using List<>
A record with Employee profile with Trainings(master) and TrainingDetails(detail)
Now, how can I display this into 2 datagridview that whenever I select a "Training" from the first datagridview it will display the details on the 2nd datagridview.
Its easy to change the datasource of the 2nd datagridview whenever the user select a new item from the first datagridview. But im wondering how it is done professionally.
Also saving is a pain, Im thingking to iterate through the datarow and save it but It mean I have to know what are the data has been update, inserted and deleted.
Please help me. Im a newbie.
BindingSources take care of this for you.
For example say I have two classes, Teachers and Students:
public class Teacher
{
private List<Student> _students = new List<Student>();
public string Name { get; set; }
public string Class { get; set; }
public List<Student> Students { get { return _students; } }
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
You can then create a list of Teachers which represents the Master/Detail situation:
List<Teacher> teachers = new List<Teacher>();
Teacher t = new Teacher();
t.Name = "Mr. Smith";
t.Class = "A1";
teachers.Add(t);
Student s = new Student();
s.Name = "Jimmy Jones";
s.Age = 6;
t.Students.Add(s);
s = new Student();
s.Name = "Jane Doe";
s.Age = 5;
t.Students.Add(s);
t = new Teacher();
t.Name = "Ms. Allen";
t.Class = "B3";
teachers.Add(t);
s = new Student();
s.Name = "Sally Student";
s.Age = 7;
t.Students.Add(s);
On my form I have two DataGridViews, teachersDataGridView and studentsDataGridView and two binding sources teachersBindingSource and studentsBindingSource.
I wire everything up like so:
teachersBindingSource.DataSource = teachers;
studentsBindingSource.DataSource = teachersBindingSource;
studentsBindingSource.DataMember = "Students";
teachersDataGridView.DataSource = teachersBindingSource;
studentsDataGridView.DataSource = studentsBindingSource;
And as if by magic when running up on the form selecting an item from the teachers grid changes students grid.
For managing inserts, updates and deletes you will need to implement some sort of change tracking yourself (or use an ORM such as Entity Framework or nHibernate). It is a topic that deserves its own question so read up on those technologies (and look at the blog post I like below) and come back when you have some specific problems.
For this answer I borrowed heavily from this excellent post - the example I've given is complete and avoids a lot of the complexity in that authors example's, but eventually you will probably want to at least know about everything he discusses. Download his demos and have a look.