Search Results

Search found 1787 results on 72 pages for 'foreign'.

Page 9/72 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Referencing surrogate key

    - by Arman
    I have a table that has an autoincrement surrogate key. I want to use it as a foreign key of my other table. The thing is, I cant figure out how I can reference it to that table, because it is nearly impossible to determine what I have to reference(the actual value of the surrogate key). Please be noted that what I am trying to do is adding a tuple/record through my program(outside the dbms). The process is: Add a new record in Table1 and generate an autoincrement key. Update Add a new record in Table2 and reference its foreign key to the primary key of Table1. Update My question is : HOW do I store the foreign key if I didnt know what is it?

    Read the article

  • Hibernate : Foreign key constraint violation problem

    - by Vinze
    I have a com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException in my code (using Hibernate and Spring) and I can't figure why. My entities are Corpus and Semspace and there's a many-to-one relation from Semspace to Corpus as defined in my hibernate mapping configuration : <class name="xxx.entities.Semspace" table="Semspace" lazy="false" batch-size="30"> <id name="id" column="idSemspace" type="java.lang.Integer" unsaved-value="null"> <generator class="identity"/> </id> <property name="name" column="name" type="java.lang.String" not-null="true" unique="true" /> <many-to-one name="corpus" class="xxx.entities.Corpus" column="idCorpus" insert="false" update="false" /> [...] </class> <class name="xxx.entities.Corpus" table="Corpus" lazy="false" batch-size="30"> <id name="id" column="idCorpus" type="java.lang.Integer" unsaved-value="null"> <generator class="identity"/> </id> <property name="name" column="name" type="java.lang.String" not-null="true" unique="true" /> </class> And the Java code generating the exception is : Corpus corpus = Spring.getCorpusDAO().getCorpusById(corpusId); Semspace semspace = new Semspace(); semspace.setCorpus(corpus); semspace.setName(name); Spring.getSemspaceDAO().save(semspace); I checked and the corpus variable is not null (so it is in database as retrieved with the DAO) The full exception is : com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`xxx/Semspace`, CONSTRAINT `FK4D6019AB6556109` FOREIGN KEY (`idCorpus`) REFERENCES `Corpus` (`idCorpus`)) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715) at com.mysql.jdbc.Connection.execSQL(Connection.java:3249) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1268) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1541) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1455) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1440) at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:102) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:642) at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:373) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:639) at xxx.dao.impl.AbstractDAO.save(AbstractDAO.java:26) at org.apache.jsp.functions.semspaceManagement_jsp._jspService(semspaceManagement_jsp.java:218) [...] The foreign key constraint has been created (and added to database) by hibernate and I don't see where the constraint can be violated. The table are innodb and I tried to drop all tables and recreate it the problem remains... EDIT : Well I think I have a start of answer... I change the log level of hibernate to DEBUG and before it crash I have the following log insert into Semspace (name, [...]) values (?, [...]) So it looks like it does not try to insert the idCorpus and as it is not null it uses the default value "0" which does not refers to an existing entry in Corpus table...

    Read the article

  • Foreign keys and pagination

    - by whitstone86
    This is my pagination script: <?php /*********************************** * PhpMyCoder Paginator * * Created By PhpMyCoder * * 2010 PhpMyCoder * * ------------------------------- * * You may use this code as long * * as this notice stays intact and * * the proper credit is given to * * the author. * ***********************************/ ?> <head> <title> Pagination Test - Created By PhpMyCoder</title> <style type="text/css"> #nav { font: normal 13px/14px Arial, Helvetica, sans-serif; margin: 2px 0; } #nav a { background: #EEE; border: 1px solid #DDD; color: #000080; padding: 1px 7px; text-decoration: none; } #nav strong { background: #000080; border: 1px solid #DDD; color: #FFF; font-weight: normal; padding: 1px 7px; } #nav span { background: #FFF; border: 1px solid #DDD; color: #999; padding: 1px 7px; } </style> </head> <?php //Require the file that contains the required classes include("pmcPagination.php"); //PhpMyCoder Paginator $paginator = new pmcPagination(20, "page"); //Connect to the database mysql_connect("localhost","root","PASSWORD"); //Select DB mysql_select_db("tvguide"); //Select only results for today and future $result = mysql_query("SELECT programme, channel, airdate, expiration, episode, setreminder FROM epdata1 where airdate >= now() order by expiration GROUP BY airdate"); //You can also add reuslts to paginate here mysql_data_seek($queryresult,0) ; while($row = mysql_fetch_array($result)) { $paginator->add(new paginationData($row['programme'], $row['channel'], $row['airdate'], $row['expiration'], $row['episode'], $row['setreminder'])); } ?> <?php //Show the paginated results $paginator->paginate (); ?><? include("pca-footer1.php"); ?> <?php //Show the navigation $paginator->navigation(); ?> However, I have two tables in this, and they are epdata1 (where the airtimes for my show House M.D. are) and housemdep plus the setreminder table. How can I use foreign keys in relation to this? I'm not sure if this will work for my script, but am willing to try. What I would like to do is to select certain episodes from the table housemdep (episodes of the show) and if any are selected it shows them as this: House M.D. showing on Channel 1 June 6th - 8:00pm "Wilson" Set Reminder House M.D. showing on Channel 1 June 7th - 1:30am "Wilson" Set Reminder House M.D. showing on Channel 1 June 7th - 12:55pm "House's Head" Set Reminder or like this, if I have not selected an episode from the row: House M.D. showing on Channel 1 June 7th - 8:00pm "House's Head" Set Reminder House M.D. showing on Channel 1 June 8th - 9:00pm Set Reminder House M.D. showing on Channel 1 June 9th - 2:30pm Set Reminder House M.D. showing on Channel 1 June 7th - 8:00pm "Que Sera Sera" Set Reminder Foreign keys and relationship of interlinked tables are new to me, if anyone could help I'd appreciate this. I've tried some of what Google suggested on foreign keys in another version of this script (this is a clone of the original on my localhost server running Apache and PHP 5.28/MySQL), but am not sure how to implement this. Thanks.

    Read the article

  • Update one-to-many EntityKey using Foreign Key

    - by User.Anonymous
    To use by the easiest way Entity Framework, I use partial class to add Foreign Key on most important Entities Model. For example, I have an Entity "CONTACT" which have "TITLE", "FUNCTION" and others. When I update a CONTACT, with this code, Foreign Key are automatically updated : public int? TitId { get { if (this.TITLE_TIT != null) return TITLE_TIT.TIT_ID; return new Nullable<int>(); } set { this.TITLE_TITReference.EntityKey = new System.Data.EntityKey("Entities.TITLE_TIT", "TIT_ID", value); } } But I have a join with ACTIVITY, that can have many CONTACT, and I don't know how to update EntityKey on setters. public IEnumerable<EntityKeyMember> ActId { get { List<EntityKeyMember> lst = new List<EntityKeyMember>(); if (this.ACT_CON2 != null) { foreach (ACT_CON2 id in this.ACT_CON2.ToList()) { EntityKeyMember key = new EntityKeyMember(id.CON_ID.ToString(),id.ACT_ID); lst.Add(key); } } return lst; } set { this.ACT_CON2.EntityKey = new System.Data.EntityKey("Entities.ACT_CON2", value); } } How set many EntityKey ? Thank you.

    Read the article

  • Importing fixtures with foreign keys and SQLAlchemy?

    - by Chris Reid
    I've been experimenting with using fixture to load test data sets into my Pylons / PostgreSQL app. This works great except that it fails to properly create foreign keys if they reference an auto increment id field. My fixture looks like this: class AuthorsData(DataSet): class frank_herbert: first_name = "Frank" last_name = "Herbert" class BooksData(DataSet): class dune: title = "Dune" author_id = AuthorsData.frank_herbert.ref('id') And the model: t_authors = sa.Table("authors", meta.metadata, sa.Column("id", sa.types.Integer, primary_key=True), sa.Column("first_name", sa.types.String(100)), sa.Column("last_name", sa.types.String(100)), ) t_books = sa.Table("books", meta.metadata, sa.Column("id", sa.types.Integer, primary_key=True), sa.Column("title", sa.types.String(100)), sa.Column("author_id", sa.types.Integer, sa.ForeignKey('authors.id')) ) When running "paster setup-app development.ini", SQLAlchemey reports the FK value as "None" so it's obviously not finding it: 15:59:48,683 INFO [sqlalchemy.engine.base.Engine.0x...9eb0] INSERT INTO books (title, author_id) VALUES (%(title)s, %(author_id)s) RETURNING books.id 15:59:48,683 INFO [sqlalchemy.engine.base.Engine.0x...9eb0] {'author_id': None, 'title': 'Dune'} The fixture docs actually warn that this might be a problem: "However, in some cases you may need to reference an attribute that does not have a value until it is loaded, like a serial ID column. (Note that this is not supported by the SQLAlchemy data layer when using sessions.)" http://farmdev.com/projects/fixture/using-dataset.html#referencing-foreign-dataset-classes Does this mean that this is just not supported with SQLAlchemy? Or is it possible to load the data without using SA "sessions"? How are other people handling this issue?

    Read the article

  • deadlock because of foreign key?

    - by George2
    Hello everyone, I am using SQL Server 2008 Enterprise. I met with deadlock in the following store procedure, but because of my fault, I did not record the deadlock graph. But now I can not reproduce deadlock issue. I want to have a postmortem to find the root cause of deadlock to avoid deadlock in the future. The deadlock happens on delete statement. For the delete statement, Param1 is a column of table FooTable, Param1 is a foreign key of another table (refers to another primary key clustered index column of the other table). There is no index on Param1 itself for table FooTable. FooTable has another column which is used as clustered primary key, but not Param1 column. Here is my guess why there is deadlock, and I want to let people review whether my analysis is correct? Since Param1 column has no index, there will be a table scan, and will acquire table level lock, because of foreign key, the delete operation will also need to check master table (e.g. to acquire lock on master table); Some operation on master table acquires master table lock, but want to acquire lock on FooTable; (1) and (2) cause cycle lock which makes deadlock happen. My analysis correct? Any reproduce scenario? create PROCEDURE [dbo].[FooProc] ( @Param1 int ,@Param2 int ,@Param3 int ) AS DELETE FooTable WHERE Param1 = @Param1 INSERT INTO FooTable ( Param1 ,Param2 ,Param3 ) VALUES ( @Param1 ,@Param2 ,@Param3 ) DECLARE @ID bigint SET @ID = ISNULL(@@Identity,-1) IF @ID > 0 BEGIN SELECT IdentityStr FROM FooTable WHERE ID = @ID END thanks in advance, George

    Read the article

  • "Special case" records for foreign key constraints

    - by keithjgrant
    Let's say I have a mysql table, called foo with a foreign key option_id constrained to the option table. When I create a foo record, the user may or may not have selected an option, and 'no option' is a viable selection. What is the best way to differentiate between 'null' (i.e. the user hasn't made a selection yet) and 'no option' (i.e. the user selected 'no option')? Right now, my plan is to insert a special record into the option table. Let's say that winds up with an id of 227 (this table already has a number of records at this point, so '1' isn't available). I have no need to access this record at a database level, and it would act as nothing more than a placeholder that the foreign key in the foo table can reference. So do I just hard-code '227' in my codebase when I'm creating 'foo' records where the user has selected 'no option'? The hard-coded id seems sloppy, and leaves room for error as the code is maintained down the road, but I'm not really sure of another approach.

    Read the article

  • Going "behind Hibernate's back" to update foreign key values without an associated entity

    - by Alex Cruise
    Updated: I wound up "solving" the problem by doing the opposite! I now have the entity reference field set as read-only (insertable=false updatable=false), and the foreign key field read-write. This means I need to take special care when saving new entities, but on querying, the entity properties get resolved for me. I have a bidirectional one-to-many association in my domain model, where I'm using JPA annotations and Hibernate as the persistence provider. It's pretty much your bog-standard parent/child configuration, with one difference being that I want to expose the parent's foreign key as a separate property of the child alongside the reference to a parent instance, like so: @Entity public class Child { @Id @GeneratedValue Long id; @Column(name="parent_id", insertable=false, updatable=false) private Long parentId; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="parent_id") private Parent parent; private long timestamp; } @Entity public class Parent { @Id @GeneratedValue Long id; @OrderBy("timestamp") @OneToMany(mappedBy="parent", cascade=CascadeType.ALL, fetch=FetchType.LAZY) private List<Child> children; } This works just fine most of the time, but there are many (legacy) cases when I'd like to put an invalid value in the parent_id column without having to create a bogus Parent first. Unfortunately, Hibernate won't save values assigned to the parentId field due to insertable=false, updatable=false, which it requires when the same column is mapped to multiple properties. Is there any nice way to "go behind Hibernate's back" and sneak values into that field without having to drop down to JDBC or implement an interceptor? Thanks!

    Read the article

  • MySQL: optimization of table (indexing, foreign key) with no primary keys

    - by Haradzieniec
    Each member has 0 or more orders. Each order contains at least 1 item. memberid - varchar, not integer - that's OK (please do not mention that's not very good, I can't change it). So, thera 3 tables: members, orders and order_items. Orders and order_items are below: CREATE TABLE `orders` ( `orderid` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `memberid` VARCHAR( 20 ), `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , `info` VARCHAR( 3200 ) NULL , PRIMARY KEY (orderid) , FOREIGN KEY (memberid) REFERENCES members(memberid) ) ENGINE = InnoDB; CREATE TABLE `order_items` ( `orderid` INT(11) UNSIGNED NOT NULL, `item_number_in_cart` tinyint(1) NOT NULL , --- 5 items in cart= 5 rows `price` DECIMAL (6,2) NOT NULL, FOREIGN KEY (orderid) REFERENCES orders(orderid) ) ENGINE = InnoDB; So, order_items table looks like: orderid - item_number_in_cart - price: ... 1000456 - 1 - 24.99 1000456 - 2 - 39.99 1000456 - 3 - 4.99 1000456 - 4 - 17.97 1000457 - 1 - 20.00 1000458 - 1 - 99.99 1000459 - 1 - 2.99 1000459 - 2 - 69.99 1000460 - 1 - 4.99 ... As you see, order_items table has no primary keys (and I think there is no sense to create an auto_increment id for this table, because once we want to extract data, we always extract it as WHERE orderid='1000456' order by item_number_in_card asc - the whole block, id woudn't be helpful in queries). Once data is inserted into order_items, it's not UPDATEd, just SELECTed. The questions are: I think it's a good idea to put index on item_number_in_cart. Could anybody please confirm that? Is there anything else I have to do with order_items to increase the performance, or that looks pretty good? I could miss something because I'm a newbie. Thank you in advance.

    Read the article

  • Foreign website keeps loading in a tab when I start up Firefox

    - by user31788
    Whenever I double-click on the FF icon to open Firefox, a Chinese website loads up in one of the tabs. Checking my settings for startup homepage (Tools Options) it was set to Google. Can anyone please advise how can I remove the uninvited Chinese website from loading every time I open Firefox? I am using Windows 7 64 bit with Firefox as my default web browser.

    Read the article

  • printing foreign text for PHP on UBUNTU and CENTOS

    - by hao
    Hey guys, I am using domdocuments and using things like $div-nodeValue to obtain certain info from a web page. On my ubuntu machine when i do php crawl.php everything is displayed properly in Chinese (the page is in UTF-8). However on my CENTOS machine using the same code I get æ´å¤åå¸ when I print in the terminal. and when I save it to the database, the characters are also messed up. One thing I noticed is that when I do print $content, both systems display them properly.

    Read the article

  • Altering constraint delete action

    - by Hobhouse
    I did this: ALTER TABLE `db`.`my_table` ADD CONSTRAINT FOREIGN KEY (`my_second_table_id`) REFERENCES `my_second_table` (`id`); I should have done this: ALTER TABLE `db`.`my_table` ADD CONSTRAINT FOREIGN KEY (`my_second_table_id`) REFERENCES `my_second_table` (`id`) ON DELETE SET NULL; Is it possible to ALTER this, or do I have to drop the constraint and add again?

    Read the article

  • mysql composite unique on FK's

    - by m2o
    I want to implement the following constraints in mysql: create table TypeMapping( ... constraint unique(server_id,type_id), constraint foreign key(server_id) references Server(id), constraint foreign key(type_id) references Type(id) ); This throws a 'ERROR 1062 (23000): Duplicate entry '3-4' for key 'server_id'' when I issue an insert/update that would break the constraint. Is this type of constraint even possible? If so how? Thank you.

    Read the article

  • Postgresql constraint

    - by Ryan
    I cannot seem to get this right, I am trying to modify a field to be a foreign key, with cascading delete... what am i doing wrong? ALTER TABLE my_table ADD CONSTRAINT $4 FOREIGN KEY my_field REFERENCES my_foreign_table ON DELETE CASCADE;

    Read the article

  • Dynamic Data: how to filter dropdown for foreign key on edit page

    - by Leonv
    I have Organisation with a foreign key to a Manager. Managers can be active, or inactive. On the Dynamic Data edit page for Organisation, I need to filter the dropdown for Manager to only show active records. I started out by making a custom version of DynamicData\FieldTemplates\ForeignKey_Edit.ascx and setting a UIHint to the new field template on Organisation.Manager. But, how to customize the linq or sql query that runs to load the Managers? Using Linq-to-SQL and DynamicDataFutures

    Read the article

  • Multiple foreign keys to same table using Elixir

    - by Suvir
    Hello, I am new to ORMs in general. I have a table (lets call it Entity) with columns -- ID expression type ( can be 'long_word', 'short_word' or 'sentence' ) Often, the first two types occur in a 'sentence', so, I want to maintain another table which maps 'Sentences' to 'long_word' or 'short_word' using the 'ID' field. All i need is another table with 2 'Integer fields' referring to 'ID' as a foreign key. But, how do i do this in Elixir? Thanks a lot...

    Read the article

  • How to Delete all data from a table which contain self referencing foreign key

    - by Shantanu Gupta
    I have a table which has employee relationship defined within itself. i.e. EmpID Name SeniorId ----------------------- 1 A NULL 2 B 1 3 C 1 4 D 3 and so on... Where Senior ID is a foreign key whose primary key table is same with refrence column EmpId I want to clear all rows from this table without removing any constraint. How can i do this? Deletion need to be performed like this 4, 3 , 2 , 1 How can I do this

    Read the article

  • LINQ: Create persistable Associations in Code, Without Foreign Key

    - by Alex
    Hello, I know that I can create LINQ Associations without a Foreign Key. The problem is, I've been doing this by adding the [Association] attribute in the DBML file (same as through the designer), which will get erased again after I refresh my database (and reload the entire table structure). I know that there is the MyData.cs file (as part of the DBML) in which I can place my partial extensions etc. to domain objects (to persist even after I refresh the DBML), but I don't know how to create an association there?

    Read the article

  • Entity Framework foreign relationship issue

    - by Doug Hope
    I've had an entity framework model working for some time. Yesterday, it suddenly started complaining about a foreign key relationship issue during an insert. I've checked the fields and can do a manual insert using the exact field values. But the EF continues to complain. Any ideas what could have happened?

    Read the article

  • Composite keys as Foreign Key?

    - by paulio
    I have the following table... TABLE: Accounts ID (int, PK, Identity) AccountType (int, PK) Username (varchar) Password (varchar) I have created a composite key out of ID and AccountType columns so that people can have the same username/password but different AccountTypes. Does this mean that for each foreign table that I try and link to I'll have to create two columns? I’m using SQL Server 2008

    Read the article

  • Querying with foreign key

    - by theactiveactor
    Say I have 2 tables whose structures are as follows: tableA id | A1 | A2 tableB id | tableA_id (foreign key) | B1 Entries in A have a one-to-many relationship with entries in B. What kind of query operation would I need to achieve "something like this: select all objects from table B where A1="foo""? Basically, apply a query on tableA and from those result, find corresponding dependent objects in tableB

    Read the article

  • Add foreign key constraints to existing tables in Ruby on Rails (MySQL)

    - by randombits
    What's the best way to add foreign keys to my existing tables in Rails with an underlying MySQL database? clearly the solution should be done in a migration, as I want this versioned. Otherwise I'd create the constraints myself. I can't seem to find one, conducive response to they above. Again, the tables have already been created with previous migrations. I'm just going back now and adding referential integrity wherever it's applicable.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >