Hibernate Annotations Id for table with no primary key - sql

I have a table that has no primary key, and one cannot be created either. I can construct a unique key using three columns of this table. Now hibernate demands an id for every annotated class, how do i satisfy this id with the unique Id I can create.

If it is an entity type then you should use a composite key. This can be done by moving primary key fields to separate class and mapping that in entity class with an #Id annotation.
See Mapping composite primary keys and foreign keys to composite primary keys
If it is not an entity but a value type you should map it accordingly.
See https://stackoverflow.com/a/1696146/324900 and Entity and value types in hibernate

Related

SQLAlchemy: Reflect and Automap Tables with Composite Primary Key

I'm trying to reflect and automap some tables in sqlalchemy that have composite primary keys from an Oracle db. When I run
metadata = MetaData()
metadata.reflect(bind=engine, schema='USER')
Base = automap_base(metadata=metadata)
Base.prepare()
print(list(Base.classes))
I get a list of the tables that have primary keys in the database, and not the ones that don't. I know that you can manually map tables with composite primary keys (http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html), but is there a way to feed the two keys that make up the composite primary key to the reflection for automapping?

Clarification on foreign keys, SQL

If I make it so that one of the attributes in my relation A references a foreign key of another relation B, is the attribute in A required to be the primary key for A (or part of the primary key for A)?
Also, my understanding is that in order to reference an attribute, the referenced attribute must be a key or unique. Am I then right is asserting that we couldn't reference part of a primary key (i.e if the primary key had two attributes we would need to reference both of them or neither, since by itself neither attribute is guaranteed to be unique)?
A foreign key must reference a unique key of some sorts, whether it's a primary key or not. You cannot reference just part of a composite unique key, unless it's a unique key on its own right.
The referencing field(s) can be a unique key (making the relation a 1:0..1 relation, but needn't necessarily be one.
Yes you are right in your understanding. Lets say you were storing information about dogs being washed at a doggy parlor, and you had two tables (tbl_dog, tbl_DogsWashed).
tbl_Dog has the columns (DogId,DogsName,Breed,OwnersIdentityNumber)
tbl_DogsWashed has the columns (DogsWashedId,DogsName)
If you linked the two tables together using the dogs name, you would risk the fact that two different dogs with the same name have had washes.
Rather, tbl_Dog would have the columns (DogsWashedId,DogId) and you would look up the DogId using the DogsName,Breed,OwnersIdentityNumber etc and populate the tbl_DogsWashed table with a primary key from tbl_Dog.

Entity Framework code-first: querying a view with no primary key

Our customer has given the access to views in which there is no primary key is defined. I know Entity Framework needs a primary key for table to identify.
But for views not having primary key is it still possible to query.
I try to find but always Entity Framework gives error saying:
Error: : EntityType 'ViewWeight' has no key defined. Define the key for this EntityType.
I understand key is important for tables, but for views just to read is there any hack or way to read the values without modifying the view itself.
It's not possible in Entity Framework to have Entities without primary key.
Try to get a possible unique key from the views, combining columns, ... to create a unique primary key.
If is not possible there is a workaround, if is only a queryable view, with out need to do other operations with retrieved values such delete or update. Modify the view to add NEWID() , it will generate a unique GUID ID for each row, use this new column as primary key for your entity.
CREATE VIEW FooView AS
SELECT SELECT NEWID() AS ID,
COLUMN_A,
COLUMN_B
.....
The problem is if you repeat the same query every time you will get different ID for the same row.
Updated
If you can't not modify the view you can use Entity with a raw Sql, create the raw sql as
List<MyView> myViewItems = context.MyView.SqlQuery("SELECT NEWID() AS ID, MyView.* FROM MyView").ToList();
In your models add
public Guid ID { get; set; }
And configure the new property as the primary key.
But be careful, because there is not compilation check with this kind of code.
I create the view which includes a primary key. Ensure that all fields in the view are of a specific data type:
Number(9) rather than Number, use CAST to get the type you want
Then add a disabled primary key constraint. It won't do anything except be recognized by entity framework as a key
alter view emp_view add constraint vemp_pk primary key (empno) disable

Can a parent child relationship be modeled in the same table using Foreign Keys?

I am designing a table that currently looks like this:
Container
ContaienrId
ParentContainerId
LotsOfOtherColumns
The idea is that a container can have a parent (which can in turn have a parent...). Also, several containers could have the same parent.
I can just stick the ID in there, but I would like the parent to be accessible via Entity Framework. For that to happen, I need a Foreign Key. (I also want the protection of a FK violation if an invalid number is entered for ParentContainerId.)
But when I try to put the Foreign key on these columns I get this error:
The columns in table 'Container (Container)' do not match an existing primary key or UNIQUE constraint.
I get what it is saying, I cant use ParentContainerId unless I put a UNIQUE constraint on it. But several containers can have the same parent, so that won't work.
Is there a way to use one table and have a Foreign Keyed parent child relationship?
You can do it like this if you want to model a one-to-many relationship:
create table container(
container_id int not null,
parent_container_id int,
more_data varchar,
primary key(container_id),
foreign key (parent_container_id) references container (container_id)
);
If you create an additional
unique(parent_container_id)
constraint, you will allow at most one child container in each parent container.
I just think you have to put a unique constraint on the ContainerId not the parentID

How do I map an optional one-to-one relationship with Fluent NHibernate?

I've got two entities, one called Site and the other called Assignment. A Site may or may not have an associated Assignment. An Assignment is only ever associated with one Site. In terms of C#, Site has a property of type Assignment which could hold a null reference.
I have got two tables by the same names in the database. The Assignment table's PK is also its FK back to the Site table (rather than Site having a nullable FK pointing to Assignment). The SQL (with fields omitted for brevity) is as follows
CREATE TABLE Site(
SiteId INT NOT NULL CONSTRAINT PK_Site PRIMARY KEY)
CREATE TABLE Assignment(
AssignmentId INT NOT NULL CONSTRAINT PK_Assignment PRIMARY KEY,
CONSTRAINT FK_Assignment_Site FOREIGN KEY (AssignmentId) REFERENCES Site (SiteId))
I'm using Fluent NHibernate's auto persistence model, which I think I will have to add an override to in order to get this to work. My question is, how do I map this relationship? Is my schema even correct for this scenario? I can change the schema if needs be.
You need to read these:
http://ayende.com/Blog/archive/2009/04/19/nhibernate-mapping-ltone-to-onegt.aspx
http://gnschenker.blogspot.com/2007/06/one-to-one-mapping-and-lazy-loading.html
https://www.hibernate.org/162.html
it's not possible to have one-to-ones lazy loaded unless they are not-nullable, or you map them as a many-to-one with one item in it