Saving data with table associations in Grails - database

I have two database tables 'Student' and 'Course'. I want a one-to-one relation where there is foreign key of 'Course' table in 'Student' table. The foreign key 'course_id' is appearing in the Student table but whenever I try to save the Student data (after filling form), the data does not get saved and there is no error as well. I am very new to grails. Please guide me how I can save the data correctly.
The table structure is as desired but the data is not getting saved to the database. There is no issue with other code parts because the data is getting saved when I remove the association between the two tables.
Student controller
package com.grails
class studentController {
def save(Student student){
student.save()
}
}
Student domain class
class Student {
Course course
String firstName
String lastName
}
Course domain class
class Course{
String course_name
String duration
static hasOne = [student: Student]
//static belongsTo = [student: Student]
}

Note that grails 4 introduced a bug with one-to-one relationships that gives inconsistent behavior based on the owning side of the relationship: https://github.com/grails/grails-core/issues/11606
I'm not sure if this is the same problem you may be seeing without more information on your error, or even if you're on this version of grails.

Related

How to handle linked models?

I have two models, using Go 1.19:
type User struct {
Name string
ID int
}
type Order struct {
ID int
Name string
User *User
// or
UserID int
}
Of course, the database orders table has a foreign key to the users table via user_id.
Probably in different situations I have to use one of these models. When exactly?
Mb only user_id in DTO models, the user in responses from the server?
I will be glad for any information :)
It depends on your purpose. As usual, you have to use id when a table to include has meta info about your entity (often it's tables with a lot of rows and so heavy), therefore it will be better to use id, otherwise if it's table which describe some fields in initial table, you can use full entity.

Relationships on Cakephp 2.0

I have two models : Absence, Students;
Absence fetch name and absence number from Students, now i want to linking model together, but i have been struggling to figure out how to map those relationships,
i dont have groups table, cause works well before, but now cake php said error by not have linking model., i used this following line before and work fine!
$this->loadModel("Student");
$siswas=$this->Student->find('all');
$this->set('students', $siswas);
but now i have error detected, named Internal server 500, and i don't know what i have to do.,
before my application is fine, but now is something wrong happens, now i need to linking model together, i need help for it..
any help would appreciated..
EDIT :
"My Problems has been Solved, the problem is because database is not working well thank for the answers"
Table structure would be :
Students Table
id student_name other fields
absents table
id student_id other fields
student Model realationship
$hasMany = array('Absent');
Absent Model realationship
$belongsTo = array('Student');

A Simple One-To-Many Relationship in JPA on Google App Engine

Even after reading the documentation, I seem to have a fundamental misunderstanding about Google App Engine's entity groups. My goal is a trivial example of ORM: I've got some Employees assigned to Departments. An employee can only be assigned to one department, but a department can have many employees. It's your standard one-to-many relationship.
Given the employee's key (email) and a department name, I want to look up both the employee and department objects, and if they don't exist, to create them.
What follows is pseudocode, not meant to compile. If producing code that will compile would help you help me, I'd be happy to do so, but I think my problem is conceptual.
Data Objects:
#Entity
public class Department {
private Key key;
private String name;
// getters and setters
}
#Entity
#NamedQuery(name="getEmployeesInDept", query="SELECT a from Employee a WHERE a.dept=:dept")
public class Employee {
private Key key;
private String firstName;
#ManyToOne
private Department dept;
// getters and setters
}
Look Up or Create
Key employeeKey = KeyFactory.createKey("Employee", email);
Employee employee = entityManager.find(Employee.class, employeeKey);
if(employee == null)
{
Key deptKey = KeyFactory.createKey("Department", deptName);
Department dept = entityManager.find(Department.class, deptKey);
if(dept == null)
{
dept = new Department();
dept.setKey(deptKey);
dept.setName(deptName);
entityManager.persist(dept);
}
employee = new Employee();
employee.setKey(employeeKey);
employee.setFirstName(firstName);
employee.setDept(dept);
entityManager.persist(employee);
}
entityManager.close();
print("Found employee " + employee.getFirstName() + " from " + dept.getName() + " department!");
That's the logic that worked perfectly when I was using ye olde generic ORM before I tried migrating to Google App Engine.
However, on GAE, I get an exception like:
javax.persistence.PersistenceException: Detected attempt to establish
Employee("bob#mycompany.com") as the parent of Department(14) but the
entity identified by Department(14) has already been persisted without
a parent. A parent cannot be established or changed once an object has
been persisted.
While I understand that in order to get Employee and Department into the same entity group (which I would prefer), I have to make one of them the parent of the other, their relationship isn't really one that fits into the parent-child paradigm in my mind.
I have tried wrapping various parts between entityManager.getTransaction().begin() and entityManager.getTransaction().end(), but to no avail.
I can get around this by including Department's key as part of Employee's key (thus making Department the parent of Employee), but then I have no idea how to look up an Employee based on their email and figure out what department they're in, or, conversely, how to look up all the employees in a given department.
Does this make sense? How should I structure this relationship in GAE? Surely this is a very common pattern that has a simple solution that is just eluding me.
I'm convinced that there's some fundamental piece of this puzzle that I'm missing, because it seems rather ridiculous that a simple many-to-one foreign key cannot be easily represented in GAE's ORM.
Cheers!
So if it doesn't fit owned relationships then make it unowned, which is supported in v2.x of the GAE JPA plugin.

Cakephp related tables show id's instead of values

i think i have all 'baked' all my relationships correctly but my 'related' table shows id's instead of values.
my db has 3 tables. candidates, qualificationlookups, qualifications.
qualificationlookups, links candidates to qualifications using the id of the candidate and the id of the qualification.
in my view view, for 'candidates', i have a 'related qualificationlookups' table. (generated by baking a candidate hasmany qualificationlookups and a qualificationlookups belongsto candidate relationship)
in my edit view, for 'qualificationlookups', i can correctly set up the candidates and qualifications fields as dropdowns so i know 'qualificationlookups's relationships are fine.
So how do i ask cakephp to list the name of the qualification (from 'qualifications' table) in the 'related qualificationlookups' table on a candidate's page?
i must be missing something...
could someone please point me in the right direction?
Thanks, Vauneen
Whenever CakePHP automagically fetches lists from your tables, it uses the id key for the value and the $displayField for the text.
If your table has a name or title field, CakePHP automatically displays it as the display field. So, either rename the field that you want as your display field (say, candidate_name to just name) or set the $displayField variable in your model:
class Candidate extends AppModel {
var $displayField = 'candidate_name';
}
HTH.
If there is no other data being stored in the qualificationlookups table, change the relationship to candidates -> HABTM -> qualifications.
To do this, you first need to drop the qualificationlookups table. Create a new table called candidates_qualifications with two indexes, candidate_id and qualification_id.
In your Candidate and Qualification models, define a HABTM Relationship. You do not need to make a new CandidatesQualification Model, cake will do it on the fly.

How can I have associations with objects that have the same key ("Id") using .Net Ria Services?

Say I have two classes and have a requirement that the primary key property must be named "Id" (example: Book and Publisher). The requirement is because I'm working with our companies code generated objects and can't change the way they are generated. These classes have a a foreign key between them: Book to Publisher and is a one to one relationship, where in this case, each Book only has one Publisher.
In order to use Book.Publisher as a property in .Net RIA Services, you need to add the attributes.
For example in the meta data for the Book class:
[Key]
public int Id;
...
[Include]
[Association("Book_Publisher", "Id", "Id", IsForeignKey = true)]
public Publisher Publisher;
In the meta data for the publisher class:
[Key]
public int Id;
...
In the client code I attempt to get the Publisher:
Publisher booksPublisher = Book.Publisher;
But I get the wrong publisher (or a null). After looking at the database, the Publisher id is it looking for is the id of the book, not the publisher.
Can I add an alias in the meta data? Will later versions of RIA Services handle this?
Thank you.
Just a guess...but I think the reason you're having issues is because you're trying to key the Id field from the Book object to the Id field of the Publisher object. I'm guessing that Book.Id uniquely identifies the book, not the publisher.
Does the Book object have a field called publisherId or something similar? If so, you should be keying the Book to Publisher using Book.publisherId = Publisher.Id.

Resources