Search Results

Search found 675 results on 27 pages for 'pk'.

Page 1/27 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Hibernate : Opinions in Composite PK vs Surrogate PK

    - by Albert Kam
    As i understand it, whenever i use @Id and @GeneratedValue on a Long field inside JPA/Hibernate entity, i'm actually using a surrogate key, and i think this is a very nice way to define a primary key considering my not-so-good experiences in using composite primary keys, where : there are more than 1 business-value-columns combination that become a unique PK the composite pk values get duplicated across the table details cannot change the business value inside that composite PK I know hibernate can support both types of PK, but im left wondering by my previous chats with experienced colleagues where they said that composite PK is easier to deal with when doing complex SQL queries and stored procedure processes. They went on saying that when using surrogate keys will complicate things when doing joining and there are several condition when it's impossible to do some stuffs when using surrogate keys. Although im sorry i cant explain the detail here since i was not clear enough when they explain it. Maybe i'll put more details next time. Im currently trying to do a project, and want to try out surrogate keys, since it's not getting duplicated across tables, and we can change the business-column values. And when the need for some business value combination uniqueness, i can use something like : @Table(name="MY_TABLE", uniqueConstraints={ @UniqueConstraint(columnNames={"FIRST_NAME", "LAST_NAME"}) // name + lastName combination must be unique But im still in doubt because of the previous discussion about the composite key. Could you share your experiences in this matter ? Thank you !

    Read the article

  • Moving from a non-clustered PK to a clustered PK in SQL 2005

    - by adaptr
    HI all, I recently asked this question in another thread, and thought I would reproduce it here with my solution: What if I have an auto-increment INT as my non-clustered primary key, and there are about 15 foreign keys defined to it ? (snide comment about original designer being braindead in the original :) ) This is a 15M row table, on a live database, SQL Standard, so dropping indexes is out of the question. Even temporarily dropping the foreign key constraints will be difficult. I'm curious if anybody has a solution that causes minimal downtime. I tested this in our testing environment and finally found that the downtime wasn't as severe as I had originally feared. I ended up writing a script that drops all FK constraints, then drops the non-clustered key, re-creates the PK as a clustered index, and finally re-created all FKs WITH NOCHECK to avoid trawling through all FKs to check constraint compliance. Then I just enable the CHECK constraints to enable constraint checking from that point onwards, and all is dandy :) The most important thing to realize is that during the time the FKs are absent, there MUST NOT be any INSERTs or DELETEs on the parent table, as this may break the constraints and cause issues in the future. The total time taken for clustering a 15M row, 800MB index was ~4 minutes :)

    Read the article

  • Demantra Partitioning and the First PK Column

    - by user702295
      We have found that it is necessary in Demantra to have an index that matches the partition key, although it does not have to be the PK.  It is ok   to create a new index instead of changing the PK.   For example, if my PK on SALES_DATA is (ITEM_ID, LOCATION_ID, SALES_DATE) and I decide partition by SALES_DATE, then I should add an index starting   with the partition key like this: (SALES_DATE, ITEM_ID, LOCATION_ID).   * Note that the first column of the new index matches the partition key.   It might also be helpful to create a 2nd index with the other PK columns reversed (SALES_DATE, LOCATION_ID, ITEM_ID). Again, the first column   matches the partition key.

    Read the article

  • Nhibernate Guid with PK MySQL

    - by Andrew Kalashnikov
    Hello colleagues. I've got a question. I use NHibernate with MySql. At my entities I use Id(PK) for my business-logic usage and Guid(for replication). So my BaseDomain: public class BaseDomain { public virtual int Id { get; set; } public virtual Guid Guid { get; set; } public class Properties { public const string Id = "Id"; public const string Guid = "Guid"; } public BaseDomain() { } } My usage domain: public class ActivityCategory : BaseDomain { public ActivityCategory() { } public virtual string Name { get; set; } public new class Properties { public const string Id = "Id"; public const string Guid = "Guid"; public const string Name = "Name"; private Properties() { } } } Mapping: <class name="ActivityCategory, Clients.Core" table='Activity_category'> <id name="Id" unsaved-value="0" type="int"> <column name="Id" not-null="true"/> <generator class="native"/> </id> <property name="Guid"/> <property name="Name"/> </class> But when I insert my entity: [Test] public void Test() { ActivityCategory ac = new ActivityCategory(); ac.Name = "Test"; using (var repo = new Repository<ActivityCategory>()) repo.Save(ac); } I always get '00000000-0000-0000-0000-000000000000' at my Guid field. What should I do for generate right Guid. May be mapping? Thanks a lot!

    Read the article

  • Looking for a C# implementation of (Pk) Zip32

    - by bukko
    I need to implement Zip32 (PK compatible) in C#. I can't just call a separate dll or exe because (1) I don't want to write the uncompressed file to disk and (2) I want to avoid the possibly that someone could wrap that library - either of these would compromise security. My ideal solution would be to find a C# implementation of the Zip32 algorithm which I could use, and just modify it so I can pass a byte array or something. Does anyone have any suggestions or (I dare but hope) examples of C# PKZip implementations?

    Read the article

  • MERGE Bug with Filtered Indexes

    - by Paul White
    A MERGE statement can fail, and incorrectly report a unique key violation when: The target table uses a unique filtered index; and No key column of the filtered index is updated; and A column from the filtering condition is updated; and Transient key violations are possible Example Tables Say we have two tables, one that is the target of a MERGE statement, and another that contains updates to be applied to the target.  The target table contains three columns, an integer primary key, a single character alternate key, and a status code column.  A filtered unique index exists on the alternate key, but is only enforced where the status code is ‘a’: CREATE TABLE #Target ( pk integer NOT NULL, ak character(1) NOT NULL, status_code character(1) NOT NULL,   PRIMARY KEY (pk) );   CREATE UNIQUE INDEX uq1 ON #Target (ak) INCLUDE (status_code) WHERE status_code = 'a'; The changes table contains just an integer primary key (to identify the target row to change) and the new status code: CREATE TABLE #Changes ( pk integer NOT NULL, status_code character(1) NOT NULL,   PRIMARY KEY (pk) ); Sample Data The sample data for the example is: INSERT #Target (pk, ak, status_code) VALUES (1, 'A', 'a'), (2, 'B', 'a'), (3, 'C', 'a'), (4, 'A', 'd');   INSERT #Changes (pk, status_code) VALUES (1, 'd'), (4, 'a');          Target                     Changes +-----------------------+    +------------------+ ¦ pk ¦ ak ¦ status_code ¦    ¦ pk ¦ status_code ¦ ¦----+----+-------------¦    ¦----+-------------¦ ¦  1 ¦ A  ¦ a           ¦    ¦  1 ¦ d           ¦ ¦  2 ¦ B  ¦ a           ¦    ¦  4 ¦ a           ¦ ¦  3 ¦ C  ¦ a           ¦    +------------------+ ¦  4 ¦ A  ¦ d           ¦ +-----------------------+ The target table’s alternate key (ak) column is unique, for rows where status_code = ‘a’.  Applying the changes to the target will change row 1 from status ‘a’ to status ‘d’, and row 4 from status ‘d’ to status ‘a’.  The result of applying all the changes will still satisfy the filtered unique index, because the ‘A’ in row 1 will be deleted from the index and the ‘A’ in row 4 will be added. Merge Test One Let’s now execute a MERGE statement to apply the changes: MERGE #Target AS t USING #Changes AS c ON c.pk = t.pk WHEN MATCHED AND c.status_code <> t.status_code THEN UPDATE SET status_code = c.status_code; The MERGE changes the two target rows as expected.  The updated target table now contains: +-----------------------+ ¦ pk ¦ ak ¦ status_code ¦ ¦----+----+-------------¦ ¦  1 ¦ A  ¦ d           ¦ <—changed from ‘a’ ¦  2 ¦ B  ¦ a           ¦ ¦  3 ¦ C  ¦ a           ¦ ¦  4 ¦ A  ¦ a           ¦ <—changed from ‘d’ +-----------------------+ Merge Test Two Now let’s repopulate the changes table to reverse the updates we just performed: TRUNCATE TABLE #Changes;   INSERT #Changes (pk, status_code) VALUES (1, 'a'), (4, 'd'); This will change row 1 back to status ‘a’ and row 4 back to status ‘d’.  As a reminder, the current state of the tables is:          Target                        Changes +-----------------------+    +------------------+ ¦ pk ¦ ak ¦ status_code ¦    ¦ pk ¦ status_code ¦ ¦----+----+-------------¦    ¦----+-------------¦ ¦  1 ¦ A  ¦ d           ¦    ¦  1 ¦ a           ¦ ¦  2 ¦ B  ¦ a           ¦    ¦  4 ¦ d           ¦ ¦  3 ¦ C  ¦ a           ¦    +------------------+ ¦  4 ¦ A  ¦ a           ¦ +-----------------------+ We execute the same MERGE statement: MERGE #Target AS t USING #Changes AS c ON c.pk = t.pk WHEN MATCHED AND c.status_code <> t.status_code THEN UPDATE SET status_code = c.status_code; However this time we receive the following message: Msg 2601, Level 14, State 1, Line 1 Cannot insert duplicate key row in object 'dbo.#Target' with unique index 'uq1'. The duplicate key value is (A). The statement has been terminated. Applying the changes using UPDATE Let’s now rewrite the MERGE to use UPDATE instead: UPDATE t SET status_code = c.status_code FROM #Target AS t JOIN #Changes AS c ON t.pk = c.pk WHERE c.status_code <> t.status_code; This query succeeds where the MERGE failed.  The two rows are updated as expected: +-----------------------+ ¦ pk ¦ ak ¦ status_code ¦ ¦----+----+-------------¦ ¦  1 ¦ A  ¦ a           ¦ <—changed back to ‘a’ ¦  2 ¦ B  ¦ a           ¦ ¦  3 ¦ C  ¦ a           ¦ ¦  4 ¦ A  ¦ d           ¦ <—changed back to ‘d’ +-----------------------+ What went wrong with the MERGE? In this test, the MERGE query execution happens to apply the changes in the order of the ‘pk’ column. In test one, this was not a problem: row 1 is removed from the unique filtered index by changing status_code from ‘a’ to ‘d’ before row 4 is added.  At no point does the table contain two rows where ak = ‘A’ and status_code = ‘a’. In test two, however, the first change was to change row 1 from status ‘d’ to status ‘a’.  This change means there would be two rows in the filtered unique index where ak = ‘A’ (both row 1 and row 4 meet the index filtering criteria ‘status_code = a’). The storage engine does not allow the query processor to violate a unique key (unless IGNORE_DUP_KEY is ON, but that is a different story, and doesn’t apply to MERGE in any case).  This strict rule applies regardless of the fact that if all changes were applied, there would be no unique key violation (row 4 would eventually be changed from ‘a’ to ‘d’, removing it from the filtered unique index, and resolving the key violation). Why it went wrong The query optimizer usually detects when this sort of temporary uniqueness violation could occur, and builds a plan that avoids the issue.  I wrote about this a couple of years ago in my post Beware Sneaky Reads with Unique Indexes (you can read more about the details on pages 495-497 of Microsoft SQL Server 2008 Internals or in Craig Freedman’s blog post on maintaining unique indexes).  To summarize though, the optimizer introduces Split, Filter, Sort, and Collapse operators into the query plan to: Split each row update into delete followed by an inserts Filter out rows that would not change the index (due to the filter on the index, or a non-updating update) Sort the resulting stream by index key, with deletes before inserts Collapse delete/insert pairs on the same index key back into an update The effect of all this is that only net changes are applied to an index (as one or more insert, update, and/or delete operations).  In this case, the net effect is a single update of the filtered unique index: changing the row for ak = ‘A’ from pk = 4 to pk = 1.  In case that is less than 100% clear, let’s look at the operation in test two again:          Target                     Changes                   Result +-----------------------+    +------------------+    +-----------------------+ ¦ pk ¦ ak ¦ status_code ¦    ¦ pk ¦ status_code ¦    ¦ pk ¦ ak ¦ status_code ¦ ¦----+----+-------------¦    ¦----+-------------¦    ¦----+----+-------------¦ ¦  1 ¦ A  ¦ d           ¦    ¦  1 ¦ d           ¦    ¦  1 ¦ A  ¦ a           ¦ ¦  2 ¦ B  ¦ a           ¦    ¦  4 ¦ a           ¦    ¦  2 ¦ B  ¦ a           ¦ ¦  3 ¦ C  ¦ a           ¦    +------------------+    ¦  3 ¦ C  ¦ a           ¦ ¦  4 ¦ A  ¦ a           ¦                            ¦  4 ¦ A  ¦ d           ¦ +-----------------------+                            +-----------------------+ From the filtered index’s point of view (filtered for status_code = ‘a’ and shown in nonclustered index key order) the overall effect of the query is:   Before           After +---------+    +---------+ ¦ pk ¦ ak ¦    ¦ pk ¦ ak ¦ ¦----+----¦    ¦----+----¦ ¦  4 ¦ A  ¦    ¦  1 ¦ A  ¦ ¦  2 ¦ B  ¦    ¦  2 ¦ B  ¦ ¦  3 ¦ C  ¦    ¦  3 ¦ C  ¦ +---------+    +---------+ The single net change there is a change of pk from 4 to 1 for the nonclustered index entry ak = ‘A’.  This is the magic performed by the split, sort, and collapse.  Notice in particular how the original changes to the index key (on the ‘ak’ column) have been transformed into an update of a non-key column (pk is included in the nonclustered index).  By not updating any nonclustered index keys, we are guaranteed to avoid transient key violations. The Execution Plans The estimated MERGE execution plan that produces the incorrect key-violation error looks like this (click to enlarge in a new window): The successful UPDATE execution plan is (click to enlarge in a new window): The MERGE execution plan is a narrow (per-row) update.  The single Clustered Index Merge operator maintains both the clustered index and the filtered nonclustered index.  The UPDATE plan is a wide (per-index) update.  The clustered index is maintained first, then the Split, Filter, Sort, Collapse sequence is applied before the nonclustered index is separately maintained. There is always a wide update plan for any query that modifies the database. The narrow form is a performance optimization where the number of rows is expected to be relatively small, and is not available for all operations.  One of the operations that should disallow a narrow plan is maintaining a unique index where intermediate key violations could occur. Workarounds The MERGE can be made to work (producing a wide update plan with split, sort, and collapse) by: Adding all columns referenced in the filtered index’s WHERE clause to the index key (INCLUDE is not sufficient); or Executing the query with trace flag 8790 set e.g. OPTION (QUERYTRACEON 8790). Undocumented trace flag 8790 forces a wide update plan for any data-changing query (remember that a wide update plan is always possible).  Either change will produce a successfully-executing wide update plan for the MERGE that failed previously. Conclusion The optimizer fails to spot the possibility of transient unique key violations with MERGE under the conditions listed at the start of this post.  It incorrectly chooses a narrow plan for the MERGE, which cannot provide the protection of a split/sort/collapse sequence for the nonclustered index maintenance. The MERGE plan may fail at execution time depending on the order in which rows are processed, and the distribution of data in the database.  Worse, a previously solid MERGE query may suddenly start to fail unpredictably if a filtered unique index is added to the merge target table at any point. Connect bug filed here Tests performed on SQL Server 2012 SP1 CUI (build 11.0.3321) x64 Developer Edition © 2012 Paul White – All Rights Reserved Twitter: @SQL_Kiwi Email: [email protected]

    Read the article

  • Int PK inner join Vs Guid PK inner Join on SQL Server. Execution plan.

    - by bigb
    I just did some testing for Int PK join Vs Guid PK. Tables structure and number of records looking like that: Performance of CRUD operations using EF4 are pretty similar in both cases. As we know Int PK has better performance rather than strings. So SQL server execution plan with INNER JOINS are pretty different Here is an execution plan. As i understand according with execution plan from attached image Int join has better performance because it is taking less resources for Clustered index scan and it is go in two ways, am i right? May be some one may explain this execution plan in more details?

    Read the article

  • Problem using Embarcadero ER/Studio with Postgres (With Serial PK)

    - by Paul
    Hello ... I created a table using ER/STudio 8.0.3 ... The table has a serial pk (SERIAL/INTEGER in ER/Studio)... But the ER/Studio Physical Model generated convert the Serial to Integer... And The generated table in database has a integer pk, without auto-increment functionality... Any idea? Table generated : CREATE TABLE test ( id integer NOT NULL ) Should be : CREATE TABLE test ( id serial NOT NULL )

    Read the article

  • Mapping self-table one-to-many using non-PK clolumns

    - by Harel Moshe
    Hey, i have a legacy DB to which a Person object is mapped, having a collection of family-members, like this: class Person { ... string Id; /* 9-digits string */ IList<Person> Family; ... } The PERSON table seems like: Id: CHAR(9), PK FamilyId: INT, NOT NULL and several other non-relevant columns. I'm trying to map the Family collection to the PERSON table using the FamilyId column, which is not the PK as mentioned above. So, i actually have a one-to-many which is self-table-referential. I'm getting an error saying 'Cast is not valid' when my mapping looks like this: ... <set name="Family" table="Person" lazy="false"> <key column="FamilyId" /> <one-to-many class="Person" /> </set> ... because obviously, the join NHibernate is trying to make is between the PK column, Id, and the 'secondary' column, FamilyId, instead of joining the FamilyId column to itself. Any ideas please?

    Read the article

  • Add shortcut SQL management studio 2008 to select top 1000 order by PK desc

    - by JP Hellemons
    Hello, when I right click a table I can select select top 1000 rows and edit top 200 rows I'd like to add an option select bottom 1000 rows I am pretty sure that I've seen it somewhere online how to do this. But I can't remember where... already found this: http://sqlserver-training.com/how-to-change-default-value-of-select-or-edit-top-rows-in-ssms-2008/- but it seems impossible to add a template query...

    Read the article

  • how to retrive pK using spring security

    - by aditya
    i implement this method of the UserDetailService interface, public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException, DataAccessException { final EmailCredential userDetails = persistentEmailCredential .getUniqueEmailCredential(username); if (userDetails == null) { throw new UsernameNotFoundException(username + "is not registered"); } final HashSet<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl("ROLE_USER")); for (UserRole role:userDetails.getAccount().getRoles()) { authorities.add(new GrantedAuthorityImpl(role.getRole())); } return new User(userDetails.getEmailAddress(), userDetails .getPassword(), true, true, true, true, authorities); } in the security context i do some thing like this <!-- Login Info --> <form-login default-target-url='/dashboard.htm' login-page="/login.htm" authentication-failure-url="/login.htm?authfailed=true" always-use-default-target='false' /> <logout logout-success-url="/login.htm" invalidate-session="true" /> <remember-me user-service-ref="emailAccountService" key="fuellingsport" /> <session-management> <concurrency-control max-sessions="1" /> </session-management> </http> now i want to pop out the Pk of the logged in user, how can i show it in my jsp pages, any idea thanks in advance

    Read the article

  • JPA @OneToMany and composite PK

    - by Fleuri F
    Good Morning, I am working on project using JPA. I need to use a @OneToMany mapping on a class that has three primary keys. You can find the errors and the classes after this. If anyone has an idea! Thanks in advance! FF javax.persistence.PersistenceException: No Persistence provider for EntityManager named JTA_pacePersistence: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory: javax.persistence.PersistenceException javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException Exception Description: predeploy for PersistenceUnit [JTA_pacePersistence] failed. Internal Exception: Exception [TOPLINK-7220] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException Exception Description: The @JoinColumns on the annotated element [private java.util.Set isd.pacepersistence.common.Action.permissions] from the entity class [class isd.pacepersistence.common.Action] is incomplete. When the source entity class uses a composite primary key, a @JoinColumn must be specified for each join column using the @JoinColumns. Both the name and the referenceColumnName elements must be specified in each such @JoinColumn. at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:643) at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:196) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) at isd.pacepersistence.common.DataMapper.(Unknown Source) at isd.pacepersistence.server.MainServlet.getDebugCase(Unknown Source) at isd.pacepersistence.server.MainServlet.doGet(Unknown Source) at javax.servlet.http.HttpServlet.service(HttpServlet.java:718) at javax.servlet.http.HttpServlet.service(HttpServlet.java:831) at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:411) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:290) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:271) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:202) There is the source code of my classes : Action : @Entity @Table(name="action") public class Action { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int num; @ManyToOne(cascade= { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) @JoinColumn(name="domain_num") private Domain domain; private String name; private String description; @OneToMany @JoinTable(name="permission", joinColumns= { @JoinColumn(name="action_num", referencedColumnName="action_num", nullable=false, updatable=false) }, inverseJoinColumns= { @JoinColumn(name="num") }) private Set<Permission> permissions; public Action() { } Permission : @SuppressWarnings("serial") @Entity @Table(name="permission") public class Permission implements Serializable { @EmbeddedId private PermissionPK primaryKey; @ManyToOne @JoinColumn(name="action_num", insertable=false, updatable=false) private Action action; @ManyToOne @JoinColumn(name="entity_num", insertable=false, updatable=false) private isd.pacepersistence.common.Entity entity; @ManyToOne @JoinColumn(name="class_num", insertable=false, updatable=false) private Clazz clazz; private String kondition; public Permission() { } PermissionPK : @SuppressWarnings("serial") @Entity @Table(name="permission") public class Permission implements Serializable { @EmbeddedId private PermissionPK primaryKey; @ManyToOne @JoinColumn(name="action_num", insertable=false, updatable=false) private Action action; @ManyToOne @JoinColumn(name="entity_num", insertable=false, updatable=false) private isd.pacepersistence.common.Entity entity; @ManyToOne @JoinColumn(name="class_num", insertable=false, updatable=false) private Clazz clazz; private String kondition; public Permission() { }

    Read the article

  • JPA @ManyToOne and composite PK

    - by Fleuri F
    Good Morning, I am working on project using JPA. I need to use a @ManyToOne mapping on a class that has three primary keys. You can find the errors and the classes after this. If anyone has an idea! Thanks in advance! FF javax.persistence.PersistenceException: No Persistence provider for EntityManager named JTA_pacePersistence: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory: javax.persistence.PersistenceException javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException Exception Description: predeploy for PersistenceUnit [JTA_pacePersistence] failed. Internal Exception: Exception [TOPLINK-7220] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException Exception Description: The @JoinColumns on the annotated element [private java.util.Set isd.pacepersistence.common.Action.permissions] from the entity class [class isd.pacepersistence.common.Action] is incomplete. When the source entity class uses a composite primary key, a @JoinColumn must be specified for each join column using the @JoinColumns. Both the name and the referenceColumnName elements must be specified in each such @JoinColumn. at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:643) at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:196) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) at isd.pacepersistence.common.DataMapper.(Unknown Source) at isd.pacepersistence.server.MainServlet.getDebugCase(Unknown Source) at isd.pacepersistence.server.MainServlet.doGet(Unknown Source) at javax.servlet.http.HttpServlet.service(HttpServlet.java:718) at javax.servlet.http.HttpServlet.service(HttpServlet.java:831) at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:411) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:290) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:271) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:202) There is the source code of my classes : Action : @Entity @Table(name="action") public class Action { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int num; @ManyToOne(cascade= { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH }) @JoinColumn(name="domain_num") private Domain domain; private String name; private String description; @OneToMany @JoinTable(name="permission", joinColumns= { @JoinColumn(name="action_num", referencedColumnName="action_num", nullable=false, updatable=false) }, inverseJoinColumns= { @JoinColumn(name="num") }) private Set<Permission> permissions; public Action() { } Permission : @SuppressWarnings("serial") @Entity @Table(name="permission") public class Permission implements Serializable { @EmbeddedId private PermissionPK primaryKey; @ManyToOne @JoinColumn(name="action_num", insertable=false, updatable=false) private Action action; @ManyToOne @JoinColumn(name="entity_num", insertable=false, updatable=false) private isd.pacepersistence.common.Entity entity; @ManyToOne @JoinColumn(name="class_num", insertable=false, updatable=false) private Clazz clazz; private String kondition; public Permission() { } PermissionPK : @SuppressWarnings("serial") @Entity @Table(name="permission") public class Permission implements Serializable { @EmbeddedId private PermissionPK primaryKey; @ManyToOne @JoinColumn(name="action_num", insertable=false, updatable=false) private Action action; @ManyToOne @JoinColumn(name="entity_num", insertable=false, updatable=false) private isd.pacepersistence.common.Entity entity; @ManyToOne @JoinColumn(name="class_num", insertable=false, updatable=false) private Clazz clazz; private String kondition; public Permission() { }

    Read the article

  • Referencing a Newly inserted Row's seeded PK in C# Linq

    - by Laurence Burke
    I want to use the primary key that was just created on the dc.submitchanges() to create a new EmployeeAddress row that references the employee to the address. protected void btnAdd_Click(object sender, EventArgs e) { if (txtZip.Text != "" && txtAdd1.Text != "" && txtCity.Text != "") { TestDataClassDataContext dc = new TestDataClassDataContext(); Address addr = new Address() { AddressLine1 = txtAdd1.Text, AddressLine2 = txtAdd2.Text, City = txtCity.Text, PostalCode = txtZip.Text, StateProvinceID = Convert.ToInt32(ddlState.SelectedValue) }; dc.Addresses.InsertOnSubmit(addr); lblSuccess.Visible = true; lblErrMsg.Visible = false; dc.SubmitChanges(); // // TODO: insert new row in EmployeeAddress to reference CurEmp to newly created address // SetAddrList(); } else { lblErrMsg.Text = "Invalid Input"; lblErrMsg.Visible = true; } } protected void SetAddrList() { TestDataClassDataContext dc = new TestDataClassDataContext(); dc.ObjectTrackingEnabled = false; var addList = from addr in dc.Addresses from eaddr in dc.EmployeeAddresses where eaddr.EmployeeID == _curEmpID && addr.AddressID == eaddr.AddressID select new { AddValue = addr.AddressID, AddText = addr.AddressID, }; ddlAddList.DataSource = addList; ddlAddList.DataValueField = "AddValue"; ddlAddList.DataTextField = "AddText"; ddlAddList.DataBind(); ddlAddList.Items.Add(new ListItem("<Add Address>", "-1")); }

    Read the article

  • Configuring hibernate.reveng.xml to detect a sequence PK generator with hibernate3-maven-plugin and

    - by mmm
    Hi, is there a way to configure hibernate3-maven-plugin so that a sequence generator is detected for a primary-key? I'm using a bottom-up approach for hibernate configuration (which means letting hibernate-tools generate the hibernate configuration using a jdbc-connection for you via reverse-engineering on an existing database schema). I've read this, but also this already (those two can be unrelated, but can also leave a hint). My hibernate.reveng.xml is the following: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-reverse-engineering SYSTEM "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" > <hibernate-reverse-engineering> <table name="ORDERS"> <primary-key> <!-- setting up a specific id generator for a table --> <generator class="sequence"> <param name="sequence">ORDERS_ORDER_ID_seq</param> </generator> <key-column name="ORDER_ID"/> </primary-key> </table> </hibernate-reverse-engineering> And I'm expecting it to generate an Orders.hbm.xml file like this: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2010-06-06 18:55:42 by Hibernate Tools 3.2.2.GA --> <hibernate-mapping> <class name="some.package.Orders" table="orders" schema="public"> <id name="orderId" type="long"> <column name="order_id" /> <generator class="sequence"> <param name="sequence">ORDERS_ORDER_ID_seq</param> </generator> </id> ... </class> </hibernate-mapping> ...but receiving this instead: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2010-06-06 18:55:42 by Hibernate Tools 3.2.2.GA --> <hibernate-mapping> <class name="some.package.Orders" table="orders" schema="public"> <id name="orderId" type="long"> <column name="order_id" /> <generator class="assigned" /> </id> ... </class> </hibernate-mapping> I know my hibernate.reveng.xml is being read by hibernate3-maven-plugin, as I experience maven errors whenever syntax errors appear in the file, so pom.xml seems to be correct and hibernate.reveng.xml syntactically correct. Any clues?

    Read the article

  • Maintaining content type pk integrity in a Django deployment

    - by hekevintran
    When you run syncdb in Django, the primary keys of the content types will be recomputed. If I create new models, the next time I run syncdb, the primary keys of the content types will be different. If I have an application running in production, how can I update the database with the new models and keep the integrity of content type pks?

    Read the article

  • Trac & Sqlite PK problem

    - by fampinheiro
    I create my trac enviromnets using a sqlite database, it works very well. Now i want to get some information directly from the database and i'm using C# to do it using System.Data.SQLite. The problem i have is an error in the designer cause the tables don't have primary keys. After get this error i went and noticed that all tables that have more than one primary key defined in the schema were not 'converted' to sqlite, that information is lost. I believe the problem is in sqlite_backend.py but python isn't my speciality and i'm in a hurry so if you can guide me to a quick fix. thank you.

    Read the article

  • Change master table PK and update related table FK (changing PK from Autoincrement to UUID on Mysql)

    - by eleonzx
    I have two related tables: Groups and Clients. Clients belongs to Groups so I have a foreign key "group_id" that references the group a client belongs to. I'm changing the Group id from an autoincrement to a UUID. So what I need is to generate a UUID for each Group and update the Clients table at once to reflect the changes and keep the records related. Is there a way to do this with multiple-table update on MySQL? Adding tables definitions for clarification. CREATE TABLE `groups` ( `id` char(36) NOT NULL, `name` varchar(255) DEFAULT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8$$ CREATE TABLE `clients` ( `id` char(36) NOT NULL, `name` varchar(255) NOT NULL, `group_id` char(36) DEFAULT NULL, `active` tinyint(1) DEFAULT '1' PRIMARY KEY (`id`), KEY `fkgp` (`group_id`), CONSTRAINT `fkgp` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

    Read the article

  • django blog - post- reply system display replies

    - by dana
    I have a mini blog app, and a reply system. I want to list all mini blog entries, and their replies, if there are any. i have in views.py def profile_view(request, id): u = UserProfile.objects.get(pk=id) paginator = New.objects.filter(created_by = request.user) replies = Reply.objects.filter(reply_to = paginator) return render_to_response('profile/publicProfile.html', { 'object_list': u, 'list':paginator, 'replies':replies }, context_instance=RequestContext(request)) and in the template: <h3>Recent Entries:</h3> {% for object in list %} <li>{{ object.post }} <br /> {% for object in replies %} {{ object.reply }} <br /> {% endfor %} mention : reply_to is a ForeignKey to New, and New is the name of the 'mini blog' table But it only shows all the replies for each blog entry, not the reply for every entry, if there is one thanks

    Read the article

  • Beware Sneaky Reads with Unique Indexes

    - by Paul White NZ
    A few days ago, Sandra Mueller (twitter | blog) asked a question using twitter’s #sqlhelp hash tag: “Might SQL Server retrieve (out-of-row) LOB data from a table, even if the column isn’t referenced in the query?” Leaving aside trivial cases (like selecting a computed column that does reference the LOB data), one might be tempted to say that no, SQL Server does not read data you haven’t asked for.  In general, that’s quite correct; however there are cases where SQL Server might sneakily retrieve a LOB column… Example Table Here’s a T-SQL script to create that table and populate it with 1,000 rows: CREATE TABLE dbo.LOBtest ( pk INTEGER IDENTITY NOT NULL, some_value INTEGER NULL, lob_data VARCHAR(MAX) NULL, another_column CHAR(5) NULL, CONSTRAINT [PK dbo.LOBtest pk] PRIMARY KEY CLUSTERED (pk ASC) ); GO DECLARE @Data VARCHAR(MAX); SET @Data = REPLICATE(CONVERT(VARCHAR(MAX), 'x'), 65540);   WITH Numbers (n) AS ( SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) FROM master.sys.columns C1, master.sys.columns C2 ) INSERT LOBtest WITH (TABLOCKX) ( some_value, lob_data ) SELECT TOP (1000) N.n, @Data FROM Numbers N WHERE N.n <= 1000; Test 1: A Simple Update Let’s run a query to subtract one from every value in the some_value column: UPDATE dbo.LOBtest WITH (TABLOCKX) SET some_value = some_value - 1; As you might expect, modifying this integer column in 1,000 rows doesn’t take very long, or use many resources.  The STATITICS IO and TIME output shows a total of 9 logical reads, and 25ms elapsed time.  The query plan is also very simple: Looking at the Clustered Index Scan, we can see that SQL Server only retrieves the pk and some_value columns during the scan: The pk column is needed by the Clustered Index Update operator to uniquely identify the row that is being changed.  The some_value column is used by the Compute Scalar to calculate the new value.  (In case you are wondering what the Top operator is for, it is used to enforce SET ROWCOUNT). Test 2: Simple Update with an Index Now let’s create a nonclustered index keyed on the some_value column, with lob_data as an included column: CREATE NONCLUSTERED INDEX [IX dbo.LOBtest some_value (lob_data)] ON dbo.LOBtest (some_value) INCLUDE ( lob_data ) WITH ( FILLFACTOR = 100, MAXDOP = 1, SORT_IN_TEMPDB = ON ); This is not a useful index for our simple update query; imagine that someone else created it for a different purpose.  Let’s run our update query again: UPDATE dbo.LOBtest WITH (TABLOCKX) SET some_value = some_value - 1; We find that it now requires 4,014 logical reads and the elapsed query time has increased to around 100ms.  The extra logical reads (4 per row) are an expected consequence of maintaining the nonclustered index. The query plan is very similar to before (click to enlarge): The Clustered Index Update operator picks up the extra work of maintaining the nonclustered index. The new Compute Scalar operators detect whether the value in the some_value column has actually been changed by the update.  SQL Server may be able to skip maintaining the nonclustered index if the value hasn’t changed (see my previous post on non-updating updates for details).  Our simple query does change the value of some_data in every row, so this optimization doesn’t add any value in this specific case. The output list of columns from the Clustered Index Scan hasn’t changed from the one shown previously: SQL Server still just reads the pk and some_data columns.  Cool. Overall then, adding the nonclustered index hasn’t had any startling effects, and the LOB column data still isn’t being read from the table.  Let’s see what happens if we make the nonclustered index unique. Test 3: Simple Update with a Unique Index Here’s the script to create a new unique index, and drop the old one: CREATE UNIQUE NONCLUSTERED INDEX [UQ dbo.LOBtest some_value (lob_data)] ON dbo.LOBtest (some_value) INCLUDE ( lob_data ) WITH ( FILLFACTOR = 100, MAXDOP = 1, SORT_IN_TEMPDB = ON ); GO DROP INDEX [IX dbo.LOBtest some_value (lob_data)] ON dbo.LOBtest; Remember that SQL Server only enforces uniqueness on index keys (the some_data column).  The lob_data column is simply stored at the leaf-level of the non-clustered index.  With that in mind, we might expect this change to make very little difference.  Let’s see: UPDATE dbo.LOBtest WITH (TABLOCKX) SET some_value = some_value - 1; Whoa!  Now look at the elapsed time and logical reads: Scan count 1, logical reads 2016, physical reads 0, read-ahead reads 0, lob logical reads 36015, lob physical reads 0, lob read-ahead reads 15992.   CPU time = 172 ms, elapsed time = 16172 ms. Even with all the data and index pages in memory, the query took over 16 seconds to update just 1,000 rows, performing over 52,000 LOB logical reads (nearly 16,000 of those using read-ahead). Why on earth is SQL Server reading LOB data in a query that only updates a single integer column? The Query Plan The query plan for test 3 looks a bit more complex than before: In fact, the bottom level is exactly the same as we saw with the non-unique index.  The top level has heaps of new stuff though, which I’ll come to in a moment. You might be expecting to find that the Clustered Index Scan is now reading the lob_data column (for some reason).  After all, we need to explain where all the LOB logical reads are coming from.  Sadly, when we look at the properties of the Clustered Index Scan, we see exactly the same as before: SQL Server is still only reading the pk and some_value columns – so what’s doing the LOB reads? Updates that Sneakily Read Data We have to go as far as the Clustered Index Update operator before we see LOB data in the output list: [Expr1020] is a bit flag added by an earlier Compute Scalar.  It is set true if the some_value column has not been changed (part of the non-updating updates optimization I mentioned earlier). The Clustered Index Update operator adds two new columns: the lob_data column, and some_value_OLD.  The some_value_OLD column, as the name suggests, is the pre-update value of the some_value column.  At this point, the clustered index has already been updated with the new value, but we haven’t touched the nonclustered index yet. An interesting observation here is that the Clustered Index Update operator can read a column into the data flow as part of its update operation.  SQL Server could have read the LOB data as part of the initial Clustered Index Scan, but that would mean carrying the data through all the operations that occur prior to the Clustered Index Update.  The server knows it will have to go back to the clustered index row to update it, so it delays reading the LOB data until then.  Sneaky! Why the LOB Data Is Needed This is all very interesting (I hope), but why is SQL Server reading the LOB data?  For that matter, why does it need to pass the pre-update value of the some_value column out of the Clustered Index Update? The answer relates to the top row of the query plan for test 3.  I’ll reproduce it here for convenience: Notice that this is a wide (per-index) update plan.  SQL Server used a narrow (per-row) update plan in test 2, where the Clustered Index Update took care of maintaining the nonclustered index too.  I’ll talk more about this difference shortly. The Split/Sort/Collapse combination is an optimization, which aims to make per-index update plans more efficient.  It does this by breaking each update into a delete/insert pair, reordering the operations, removing any redundant operations, and finally applying the net effect of all the changes to the nonclustered index. Imagine we had a unique index which currently holds three rows with the values 1, 2, and 3.  If we run a query that adds 1 to each row value, we would end up with values 2, 3, and 4.  The net effect of all the changes is the same as if we simply deleted the value 1, and added a new value 4. By applying net changes, SQL Server can also avoid false unique-key violations.  If we tried to immediately update the value 1 to a 2, it would conflict with the existing value 2 (which would soon be updated to 3 of course) and the query would fail.  You might argue that SQL Server could avoid the uniqueness violation by starting with the highest value (3) and working down.  That’s fine, but it’s not possible to generalize this logic to work with every possible update query. SQL Server has to use a wide update plan if it sees any risk of false uniqueness violations.  It’s worth noting that the logic SQL Server uses to detect whether these violations are possible has definite limits.  As a result, you will often receive a wide update plan, even when you can see that no violations are possible. Another benefit of this optimization is that it includes a sort on the index key as part of its work.  Processing the index changes in index key order promotes sequential I/O against the nonclustered index. A side-effect of all this is that the net changes might include one or more inserts.  In order to insert a new row in the index, SQL Server obviously needs all the columns – the key column and the included LOB column.  This is the reason SQL Server reads the LOB data as part of the Clustered Index Update. In addition, the some_value_OLD column is required by the Split operator (it turns updates into delete/insert pairs).  In order to generate the correct index key delete operation, it needs the old key value. The irony is that in this case the Split/Sort/Collapse optimization is anything but.  Reading all that LOB data is extremely expensive, so it is sad that the current version of SQL Server has no way to avoid it. Finally, for completeness, I should mention that the Filter operator is there to filter out the non-updating updates. Beating the Set-Based Update with a Cursor One situation where SQL Server can see that false unique-key violations aren’t possible is where it can guarantee that only one row is being updated.  Armed with this knowledge, we can write a cursor (or the WHILE-loop equivalent) that updates one row at a time, and so avoids reading the LOB data: SET NOCOUNT ON; SET STATISTICS XML, IO, TIME OFF;   DECLARE @PK INTEGER, @StartTime DATETIME; SET @StartTime = GETUTCDATE();   DECLARE curUpdate CURSOR LOCAL FORWARD_ONLY KEYSET SCROLL_LOCKS FOR SELECT L.pk FROM LOBtest L ORDER BY L.pk ASC;   OPEN curUpdate;   WHILE (1 = 1) BEGIN FETCH NEXT FROM curUpdate INTO @PK;   IF @@FETCH_STATUS = -1 BREAK; IF @@FETCH_STATUS = -2 CONTINUE;   UPDATE dbo.LOBtest SET some_value = some_value - 1 WHERE CURRENT OF curUpdate; END;   CLOSE curUpdate; DEALLOCATE curUpdate;   SELECT DATEDIFF(MILLISECOND, @StartTime, GETUTCDATE()); That completes the update in 1280 milliseconds (remember test 3 took over 16 seconds!) I used the WHERE CURRENT OF syntax there and a KEYSET cursor, just for the fun of it.  One could just as well use a WHERE clause that specified the primary key value instead. Clustered Indexes A clustered index is the ultimate index with included columns: all non-key columns are included columns in a clustered index.  Let’s re-create the test table and data with an updatable primary key, and without any non-clustered indexes: IF OBJECT_ID(N'dbo.LOBtest', N'U') IS NOT NULL DROP TABLE dbo.LOBtest; GO CREATE TABLE dbo.LOBtest ( pk INTEGER NOT NULL, some_value INTEGER NULL, lob_data VARCHAR(MAX) NULL, another_column CHAR(5) NULL, CONSTRAINT [PK dbo.LOBtest pk] PRIMARY KEY CLUSTERED (pk ASC) ); GO DECLARE @Data VARCHAR(MAX); SET @Data = REPLICATE(CONVERT(VARCHAR(MAX), 'x'), 65540);   WITH Numbers (n) AS ( SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) FROM master.sys.columns C1, master.sys.columns C2 ) INSERT LOBtest WITH (TABLOCKX) ( pk, some_value, lob_data ) SELECT TOP (1000) N.n, N.n, @Data FROM Numbers N WHERE N.n <= 1000; Now here’s a query to modify the cluster keys: UPDATE dbo.LOBtest SET pk = pk + 1; The query plan is: As you can see, the Split/Sort/Collapse optimization is present, and we also gain an Eager Table Spool, for Halloween protection.  In addition, SQL Server now has no choice but to read the LOB data in the Clustered Index Scan: The performance is not great, as you might expect (even though there is no non-clustered index to maintain): Table 'LOBtest'. Scan count 1, logical reads 2011, physical reads 0, read-ahead reads 0, lob logical reads 36015, lob physical reads 0, lob read-ahead reads 15992.   Table 'Worktable'. Scan count 1, logical reads 2040, physical reads 0, read-ahead reads 0, lob logical reads 34000, lob physical reads 0, lob read-ahead reads 8000.   SQL Server Execution Times: CPU time = 483 ms, elapsed time = 17884 ms. Notice how the LOB data is read twice: once from the Clustered Index Scan, and again from the work table in tempdb used by the Eager Spool. If you try the same test with a non-unique clustered index (rather than a primary key), you’ll get a much more efficient plan that just passes the cluster key (including uniqueifier) around (no LOB data or other non-key columns): A unique non-clustered index (on a heap) works well too: Both those queries complete in a few tens of milliseconds, with no LOB reads, and just a few thousand logical reads.  (In fact the heap is rather more efficient). There are lots more fun combinations to try that I don’t have space for here. Final Thoughts The behaviour shown in this post is not limited to LOB data by any means.  If the conditions are met, any unique index that has included columns can produce similar behaviour – something to bear in mind when adding large INCLUDE columns to achieve covering queries, perhaps. Paul White Email: [email protected] Twitter: @PaulWhiteNZ

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >