Room insert into one-to-many relationship - kotlin

When trying to use intermediary classes to model entity relationships in Room, I have run into an issue. Whilst documentation describes how to get from a one-to-many relationship, it does not describe how to insert.
I'm assuming this cannot be done automatically, therefore we need a query to insert the parent, retrieve the ID for the parent and assign it to the child's foreign key, and then insert the child.
The problem is that I am unsure where to put such a query. If I include it in my DAO, then I will have to include superflous methods for inserting the child. If I include it in my Repository, this makes testing very difficult (if not impossible).
Does anyone know how to resolve this?

I'm assuming this cannot be done automatically, therefore we need a query to insert the parent, retrieve the ID for the parent and assign it to the child's foreign key, and then insert the child.
The first assumption is correct, that is that you have to supply the id of the parent (otherwise how is to know the parent).
However the second assumption that you have to query the parent is not always the case and not so in the scenario you describe. If when inserting a parent then the id is returned if using the convenience #Insert as a Long or an array of Longs (if inserting multiple Parents).
For example, say you have :-
#Entity
data class Parent(
#PrimaryKey
var id: Long? = null,
var other: String
)
and
#Entity
data class Child(
#PrimaryKey
var id: Long? = null,
var parentId: Long,
var otherdata: String
)
and an #Dao annotated class with :-
#Insert
fun insert(parent: Parent): Long
#Insert
fun insert(child: Child): Long
Then you can use the following, without having to query the Parent:-
var lastParent = dao.insert(Parent(other = "Parent1 other data"))
dao.insert(Child(parentId = lastParent, otherdata = "Child1 other data"))
dao.insert(Child(parentId = lastParent, otherdata = "Child2 other data"))
// Insert a Child with it's Parent together
dao.insert(Child(
parentId = dao.insert(Parent(other = "Parent2 other data")),
otherdata = "Child3 other data"
))
note even if you define the id's as Int, a Long is returned when inserting.
It is incorrect to use Int for an id as SQLite stores the id as a 64bit signed integer which is to large for an Int.
However, issues would not occur until the id reached a value that is too large for an Int (32bit signed) i.e. greater than 2,147,483,647.

Related

What should I make the type of a "marital status" field?

I have a field in my table "marital status" , the user has to choose (radiobutton) if he's (married, divorced, single, voeuf)
What should I make the type of this field?
Is there a boolean type?
marital status doesn't sound like a boolean anyway. It sounds like an enumeration. A boolean would be married (Y/N), although I think in this day and age you might want to be able to store multiple kinds of relationships in there, and you specified yourself that you need to store 'devorced' as well, so a boolean is out of the question.
So I'd recommend making a table named MaritalStatus, having an ID and a description. Store the various states in there, and make a foreign key to MaritalStatusID in your table.
Make it an INT field , Create another table in your database something like
CREATE TABLE dbo.MaritalStatus
(
M_ID INT PRIMARY KEY NOT NULL,
M_Status NVARCHAR(20)
)
GO
INSERT INTO dbo.MaritalStatus
VALUES
(1, 'Single'),(2,'Married'),(3,'Divorced'),
(4,'Widowed'),(5,'Other'),(6,'Prefer Not to say').... bla bla
Now in your Table in "Marital Status" field refer to a user Marital Status using INT values from dbo.MaritalStatus table's "M_ID".
Boolean or in SQL bit datatype is best when you have a situation where something can be TRUE or NOT TRUE, for someone's Marital Status there can be more than two possible values therefore you should create a separate table for all the possible Marital Status and use Foreign key constraint.
The boolean equivalent for T-SQL is bit.
Though, it seems like you want more than a yes/no answer. In this case use an int and then convert the int to an enum.
Edit: Dukeling removed the C# tag in an edit, so I am not sure how relevant this part is anymore /Edit
The enum:
enum MaritalStatus
{
Single,
Married,
Divorced,
...
}
The int from DB:
int maritalStatusFromDB = //value from DB
Convert int to enum:
MaritalStatus maritalStatus = (MaritalStatus)maritalStatusFromDB;
Be aware that your database may contain int values that are not defined in your enum, such as 10. You can check whether maritalStatusFromDB is a valid MaritalStatus as follows:
bool isValid = Enum.IsDefined(typeof(MaritalStatus), maritalStatusFromDB);
if( isValid == false )
{
//handle appropriately
}

JPA-how to Add record to master table and child table?

I am having two tables One is a Master table called TRANSACTION and second is record of the transaction this table is called TRANSACTION_RECORD.
TRANSACTION
CREATE TABLE `e3_transaction` (
`transactionid` bigint(20),
`transactiontype` varchar(10),
`transactionstatus` varchar(10),
PRIMARY KEY (`transactionid`)
);
TRANSACTION_RECORD
CREATE TABLE `e3_as2805msg4` (
`transectionid` bigint(20),
`messageType` int(4),
`cardAcceptorName` varchar(40),
`adNational` varchar(1000),
`adPrivate` varchar(1000),
KEY `transectionidFK` (`transectionid`),
CONSTRAINT `transectionidFK` FOREIGN KEY (`transectionid`) REFERENCES `e3_transaction` (`transactionid`)
);
It will have one to one mapping between Transaction and transaction record. It means one transaction can have only one record. I have kept this table separately for some reasons. So my class will look like this:
#Entity
#Table(name = "e3_transaction")
public class Transaction {
#Id
#GeneratedValue(generator = "assigned-by-code")
#GenericGenerator(name = "assigned-by-code", strategy = "assigned")
#Column(name = "transactionid", unique = true, nullable = false)
private Long transactionid;
#Column(name = "transactiontype", nullable = false, length = 10)
private String transactiontype;
#Column(name = "transactionstatus", nullable = false, length = 10)
private String transactionstatus;
#oneToOne
private TransactionRecord record;
}
I want to persist both objects at a same time. when I persist a TRANSACTION, TRANSACTION_RECORD should be persist in it's table. Is there any way to do this ?
You can change the table structure if you want. Only thing i need it TWO tables.
Works with
#OneToOne(cascade=CascadeType.ALL)
#MapsId
private TransactionRecord record;
TransactionRecord must have an #Id of the same type as Transaction with no value generation.
Tried with Hibernate as JPA 2.0-provider.
There are a few options to map this, but it looks like you are handling it with two separate entities. As both entities share the same primary key value, your reference mapping will need to change based on which entity you wish to have controlling the pk value generation - as it stands, the e3_transaction.transactionid field is being set by two separate mappings; the transactionid long and the TransactionRecord record reference.
If you wish to use the #MapsId as is suggested in the other answer, you will need to move your #GeneratedValue code to the TransactionRecord entity, as the JPA provider will use the value in the referenced TransactionRecord to set the transactionid attribute and the database field. This is a simple elegant solution, but you can also remove the Long transactionid attribute from Transaction and just mark the record reference with #Id (instead of #MapsId). The long transactionId value within TransactionRecord would still be used as Transaction's id for EntityManager getReference and find calls.
A different option that allows keeping the #GeneratedValue on the transactionid within Transaction is to define the #JoinColumn annotation on the record reference and specify that the field is insertable=false, updatable=false. You then need to modify the TransactionRecord so that it has a back relationship to the Transaction so that it can pull the transectionid value from the Transaction instance to use as its id. This can be accomplished by simply marking the relationship with #ID though.

Retrieving Database Schema Linq to SQL VB.Net

I want to retrieve each column name and data type then check if the columns is foreign key then query they key table of that relation !!! could be done ?? I googled for 3 days I know that I have to use Mappping model OR Reflection or both ,,,, but i cant do it .
I will simplify what i need assuming :
TABLE1 hase foreign key( COL3) refer to the primary key (COL1) in TABLE0 :
iterate TABLE1 Columns check EACH columns if it is a foreign key ( also get its data type)
Get the relation to determine the associated table(TABLE0)
retrieve the primary key tables (TABLE0)
I got it
I make a function that return the type of each foreign key and the related table class type
Private Function GetForeignKeyTables(ByVal myTableType As Type) As List(Of myForeignKeys)
Dim myDx = New Tester.DataClasses1DataContext
Dim mymodel As New AttributeMappingSource
Dim myAsociations = mymodel.GetModel(GetType(DataClasses1DataContext)).GetTable(myTableType).RowType.Associations
Dim asc = From m In myAsociations Where m.IsForeignKey
Select New myForeignKeys With {.KeyDataType = m.ThisKey.First.DbType, .RelatedTableType = m.OtherType}
Return asc.ToList
End Function
Private Class myForeignKeys
Property KeyDataType As String
Property RelatedTableType As MetaType
End Class
But I still need to retrieve the data from those related table .
I mean how to create an instance of the class from its MetaType variable?

How do you modify existing records using ScalaQuery?

By modify I mean counterparts of SQL UPDATE and DELETE.
In both cases I have an object-record and I would like to delete it in the database. The table has always primary key, and it is set in my object-record.
Please note that I don't have query or other source which "created" that object-record, all I have is it and the table. So in general it looks like this:
fetch the Record from Table
...
// forget how I get the Record
...
Record.person_name = "joe"
? update Record ?
How to do it?
I define records and tables as below:
case class Topic(var id : Long,
var sectionId : Int,
...
object TopicTable extends Table[Topic]("Topic") {
def id = column[Long]("top_Id", O.PrimaryKey)
def sectionId = column[Int]("sect_Id")
...
It seems there are no direct methods, so you have to create explicitly a recordset in order to modify (for comparison -- I know SQ is not ORM -- in EF you fetch records, modify them and at this point your data context "knows" they were modify, so all you have to do is submit changes).
So first you create RS as you like:
val rs = for (rec <- MyTable if rec.id===10) yield rec;
and the delete records:
rs.mutate(rec => rec.delete())
for update:
rs.update(new MyRecord(...))
or (gossip is, it is faster ;-) )
rs.mutate(rec => rec.row = new MyRecord(...))
Please note I am complete newbie with SQ so I might just misinformed you. I works for me though.
Now, the only missing part is adding some nice wrappers, so delete and update could be done directly per record.

Strange relationship mapping question for NHibernate

I have a unique situation working with a legacy application where I have a parent/child relationship that is based on two integer values. Unfortunately, these fields are not id and parentId or something similar. The columns are ItemId and SubItemId. When these two columns equal each other, the item is assumed to be a parent. When they differ, the ItemId references the Items parent and the SubItemId is simply an identifier of which child it is.
Here is an example
ItemId = 1, SubItemId = 1: Parent Item
ItemId = 1, SubItemId = 6: Sub Item, whose parent is the Item where the id fields are (1, 1)
ItemId = 2, SubItemId = 2: Parent Item
ItemId = 2, SubItemId = 9: Sub Item, whose parent is the Item where the id fields are (2, 2)
So with this information, I have a class hierarchy set up like this:
public class Item
public property ItemId as Integer
public property SubItemId as Integer
end class
class ParentItem : Item
end class
class SubItem : Item
public property ParentItem as ParentItem
end class
So I would like to map the ParentItem property of the SubItem class to its corresponding ParentItem using NHibernate and I can't for the life of me figure out how. I was able to get NHibernate to instantiate the correct class based on a formula discriminator, and I was hoping something similar was available for many-to-one relationships.
I'm not able to change the table structure, which certainly limits my options. Also, I'm using FluentNHibernate for my mappings, so feel free to offer suggestions using its syntax.
Thanks!
Update
I created a view that added two new columns that equated to a foreign key pointing to the parent and now I'm getting an NHibernate mapping error:
Foreign key (FK163E572EF90BD69A:ItemsNHibernateView [ParentItemID, ParentrSubitemID])) must have same number of columns as the referenced primary key (ItemsNHibernateView [ItemID, SubitemID])
This is throwing me off because to me, it looks like both keys do have the same number of columns...
Ok, I figured it out based on the comment from Ben Hoffstein. I created the view as I mentioned in the update to my original question. The error was caused by an embarassingly stupid error. When I created the array to list the column names for the foreign key, I put both names in the quotes like this:
new string() {"ParentItemID, ParentSubitemID"}
instead of:
new string() {"ParentItemID", "ParentSubitemID"}
The way that NHibernate was displaying the error threw me off the scent.