Search Results

Search found 60 results on 3 pages for 'onetoone'.

Page 1/3 | 1 2 3  | Next Page >

  • Django Admin: OneToOne Relation as an Inline?

    - by Jim Robert
    I am putting together the admin for a satchmo application. Satchmo uses OneToOne relations to extend the base Product model, and I'd like to edit it all on one page. It is possible to have a OneToOne relation as an Inline? If not, what is the best way to add a few fields to a given page of my admin that will eventually be saved into the OneToOne relation? for example: class Product(models.Model): name = models.CharField(max_length=100) ... class MyProduct(models.Model): product = models.OneToOne(Product) ... I tried this for my admin but it does not work, and seems to expect a Foreign Key: class ProductInline(admin.StackedInline): model = Product fields = ('name',) class MyProductAdmin(admin.ModelAdmin): inlines = (AlbumProductInline,) admin.site.register(MyProduct, MyProductAdmin) Which throws this error: <class 'satchmo.product.models.Product'> has no ForeignKey to <class 'my_app.models.MyProduct'> Is the only way to do this a Custom Form? edit: Just tried the following code to add the fields directly... also does not work: class AlbumAdmin(admin.ModelAdmin): fields = ('product__name',)

    Read the article

  • Mapping @OneToOne with @Where clause

    - by Gabriel
    I am trying to map an entity as following @OneToOne(mappedBy = "localizedLabel") @JoinColumn(insertable = false, updatable = false) @WhereJoinTable(clause = "locale='en_US'") public Localization getEn_US() { return en_US; } I can assure that the data will return only one or null if the not found, but hibernate seems to ignore my @Where clause: ERROR com.eventtouch.bc.business.core.log.LoggingInterceptor - org.hibernate.HibernateException: More than one row with the given identifier was found: 4211, for class: com.eventtouch.bc.business.domain.LocalizedLabel Any ideas on ho to map a @OneToOne relationship with @Where clause? Thanks

    Read the article

  • [hibernate - jpa] @OneToOne annotoation problem (i think...)

    - by blow
    Hi all, im new in hibernate and JPA and i have some problems with annotations. My target is to create this table in db (PERSON_TABLE with personal-details) ID ADDRESS NAME SURNAME MUNICIPALITY_ID First of all, i have a MUNICIPALITY table in db containing all municipality of my country. I mapped this table in this ENTITY: @Entity public class Municipality implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String country; private String province; private String name; @Column(name="cod_catasto") private String codCatastale; private String cap; public Municipality() { } ... Then i make an EMBEDDABLE class Address containing fields that realize a simple address... @Embeddable public class Address implements Serializable { @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="id_municipality") private Municipality municipality; @Column(length=45) private String address; public Address() { } ... Finally i embedded this class into Person ENTITY @Entity public class Person implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String name; private String surname; @Embedded private Address address; public Person() { } ... All works good when i have to save a new Person record, in fact hibernate creates a PERSON_TABLE as i want, but if i try to retrieve a Person record i have an exception. HQL is simply "from Person" The excpetion is (Entities is the package containing all classes above-mentioned): org.hibernate.AnnotationException: @OneToOne or @ManyToOne on Entities.Person.address.municipality references an unknown entity: Entities.Municipality Is the @OneToOne annotation the problem? Thanks.

    Read the article

  • Hibernate @OneToOne @NotNull

    - by Marty Pitt
    Is it valid to declare @OneToOne and @NotNull on both sides of a relationship, such as: class ChangeEntry { @OneToOne(cascade=CascadeType.ALL) @NotNull ChangeEntryDetails changeEntryDetails; } class ChangeEntryDetails { @OneToOne(cascase=CascadeType.ALL) @NotNull ChangeEntry changeEntry; } I can't find anything that says this is invalid, but it seems that during persistence at least one side of the relationship must be violated. (Eg., if writing changeEntry first, changeEntryDetails will be null temporarily). When trying this, I see an exception thrown not-null property references a null or transient value. I'd like to avoid relaxing the constraint if possible, because both sides must be present.

    Read the article

  • ASP.net MVC - OneToOne relationship with pluralized nomenclature

    - by ludicco
    Hi, I have an OneToOne relationship between my models Account and Company the table names are Accounts and Companies respectively. Here is a brief screenshot of the structure: http://cl.ly/1AEU Everything works well, but mysteriously when I use the OneToOne associations I have accessors like: var db = new DB(); var account = db.Accounts.First(); var company = account.Companies; // note the plural not the singular accessor So, what's happing is that even if using OneToOne association, I still get the plural accessor with "companies" and not "company", if it this is a pure object representation and not an EntitySet generated in case when it s an oneToMany relationship. Is there a way to get this nomenclature to be applied properly? Thanks a lot

    Read the article

  • Hibernate using OneToOne

    - by Soft
    I have two tables tab1 { col1 (PK), col2, col3 } tab2 { col1, col2(PK), col3 } I am using Hibernate annotation for joining using "OneToOne" I have the below Hibernate class for tab1 class tab1 { @OneToOne @JoinColumn(name = "col2", referencedColumnName = "col1") private tab2 t2; } i was expecting to run the below sql select * from tab1 t1, tab2 t2 where t1.col1 = t2.col2 But it is not working as i expected.Please help

    Read the article

  • JPA hibernate OneToOne mapping

    - by Stupidfrog
    enviroment: hibernate 4.1.6.final spring 3.1.2.release spring jpa 1.1.0.release postgresql 9.1-901-1.jdbc4 there is 2 table public A { private Long id; private Long name; } public B { private Long id; private Long table_a_id; } the A.id and B.id is sequential, unique , but no related.(means they are separately id for their own table). how to do mapping? i have tried some method, however the result is not i wanted, because it bind wrong. for example: public A { .... @OneToOne @JoinColumn(name = "id") private B table_b } public B { ... @JsonIgnore @OneToOne(mappedBy = "table_b") private A table_a; } when i query A the result is { "id":5, "table_b":{ "id":5, "table_a_id":4 } } obviously the data join by using their id but not joining using table_a_id. what i expect is { "id":4, "table_b":{ "id":5, "table_a_id":4 } } so can somebody teach me that, how to map this 2 table by using table b table_a_id(foregin key)

    Read the article

  • OneToOne JPA / Hibernate eager loading cause N+1 select

    - by Alexandre Lavoie
    I created a method to have multilingual text on different objects without creating field for each languages or tables for each objects types. Now the only problem I've got is N+1 select queries when doing a simple loading. Tables schema : CREATE TABLE `testentities` ( `keyTestEntity` int(11) NOT NULL, `keyMultilingualText` int(11) NOT NULL, PRIMARY KEY (`keyTestEntity`) ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; CREATE TABLE `common_multilingualtexts` ( `keyMultilingualText` int(11) NOT NULL auto_increment, PRIMARY KEY (`keyMultilingualText`) ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; CREATE TABLE `common_multilingualtexts_values` ( `languageCode` varchar(5) NOT NULL, `keyMultilingualText` int(11) NOT NULL, `value` text, PRIMARY KEY (`languageCode`,`keyMultilingualText`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; MultilingualText.java @Entity @Table(name = "common_multilingualtexts") public class MultilingualText implements Serializable { private Integer m_iKeyMultilingualText; private Map<String, String> m_lValues = new HashMap<String, String>(); public void setKeyMultilingualText(Integer p_iKeyMultilingualText) { m_iKeyMultilingualText = p_iKeyMultilingualText; } @Id @GeneratedValue @Column(name = "keyMultilingualText") public Integer getKeyMultilingualText() { return m_iKeyMultilingualText; } public void setValues(Map<String, String> p_lValues) { m_lValues = p_lValues; } @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "common_multilingualtexts_values", joinColumns = @JoinColumn(name = "keyMultilingualText")) @MapKeyColumn(name = "languageCode") @Column(name = "value") public Map<String, String> getValues() { return m_lValues; } public void put(String p_sLanguageCode, String p_sValue) { m_lValues.put(p_sLanguageCode,p_sValue); } public String get(String p_sLanguageCode) { if(m_lValues.containsKey(p_sLanguageCode)) { return m_lValues.get(p_sLanguageCode); } return null; } } And it is used like this on a object (having a foreign key to the multilingual text) : @Entity @Table(name = "testentities") public class TestEntity implements Serializable { private Integer m_iKeyEntity; private MultilingualText m_oText; public void setKeyEntity(Integer p_iKeyEntity) { m_iKeyEntity = p_iKeyEntity; } @Id @GeneratedValue @Column(name = "keyEntity") public Integer getKeyEntity() { return m_iKeyEntity; } public void setText(MultilingualText p_oText) { m_oText = p_oText; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "keyText") public MultilingualText getText() { return m_oText; } } Now, when doing a simple HQL query : from TestEntity, I get a query selecting TestEntity's and one query for each MultilingualText that need to be loaded on each TestEntity. I've searched a lot and found absolutely no solutions. I have tested : @Fetch(FetchType.JOIN) optional = false @ManyToOne instead of @OneToOne Now I am out of idea!

    Read the article

  • @OneToOne and @JoinColumn, auto delete null entity , doable?

    - by smallufo
    I have two Entities , with the following JPA annotations : @Entity @Table(name = "Owner") public class Owner implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private long id; @OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL) @JoinColumn(name="Data_id") private Data Data; } @Entity @Table(name = "Data") public class Data implements Serializable { @Id private long id; } Owner and Data has one-to-one mapping , the owning side is Owner. The problem occurs when I execute : owner.setData(null) ; ownerDao.update(owner) ; The "Owner" table's Data_id becomes null , that's correct. But the "Data" row is not deleted automatically. I have to write another DataDao , and another service layer to wrap the two actions ( ownerDao.update(owner) ; dataDao.delete(data); ) Is it possible to make a data row automatically deleted when the owning Owner set it to null ?

    Read the article

  • Left Join with a OneToOne field in Django

    - by jamida
    I have 2 tables, simpleDB_all and simpleDB_some. The "all" table has an entry for every item I want, while the "some" table has entries only for some items that need additional information. The Django models for these are: class all(models.Model): name = models.CharField(max_length=40) important_info = models.CharField(max_length=40) class some(models.Model): all_key = models.OneToOneField(all) extra_info = models.CharField(max_length=40) I'd like to create a view that shows every item in "all" with the extra info if it exists in "some". Since I'm using a 1-1 field I can do this with almost complete success: allitems = all.objects.all() for item in allitems: print item.name, item.important_info, item.some.extra_info but when I get to the item that doesn't have a corresponding entry in the "some" table I get a DoesNotExist exception. Ideally I'd be doing this loop inside a template, so it's impossible to wrap it around a "try" clause. Any thoughts? I can get the desired effect directly in SQL using a query like this: SELECT all.name, all.important_info, some.extra_info FROM all LEFT JOIN some ON all.id = some.all_key_id; But I'd rather not use raw SQL.

    Read the article

  • Django Multi-Table Inheritance VS Specifying Explicit OneToOne Relationship in Models

    - by chefsmart
    Hope all this makes sense :) I'll clarify via comments if necessary. Also, I am experimenting using bold text in this question, and will edit it out if I (or you) find it distracting. With that out of the way... Using django.contrib.auth gives us User and Group, among other useful things that I can't do without (like basic messaging). In my app I have several different types of users. A user can be of only one type. That would easily be handled by groups, with a little extra care. However, these different users are related to each other in hierarchies / relationships. Let's take a look at these users: - Principals - "top level" users Administrators - each administrator reports to a Principal Coordinators - each coordinator reports to an Administrator Apart from these there are other user types that are not directly related, but may get related later on. For example, "Company" is another type of user, and can have various "Products", and products may be supervised by a "Coordinator". "Buyer" is another kind of user that may buy products. Now all these users have various other attributes, some of which are common to all types of users and some of which are distinct only to one user type. For example, all types of users have to have an address. On the other hand, only the Principal user belongs to a "BranchOffice". Another point, which was stated above, is that a User can only ever be of one type. The app also needs to keep track of who created and/or modified Principals, Administrators, Coordinators, Companies, Products etc. (So that's two more links to the User model.) In this scenario, is it a good idea to use Django's multi-table inheritance as follows: - from django.contrib.auth.models import User class Principal(User): # # # branchoffice = models.ForeignKey(BranchOffice) landline = models.CharField(blank=True, max_length=20) mobile = models.CharField(blank=True, max_length=20) created_by = models.ForeignKey(User, editable=False, blank=True, related_name="principalcreator") modified_by = models.ForeignKey(User, editable=False, blank=True, related_name="principalmodifier") # # # Or should I go about doing it like this: - class Principal(models.Model): # # # user = models.OneToOneField(User, blank=True) branchoffice = models.ForeignKey(BranchOffice) landline = models.CharField(blank=True, max_length=20) mobile = models.CharField(blank=True, max_length=20) created_by = models.ForeignKey(User, editable=False, blank=True, related_name="principalcreator") modified_by = models.ForeignKey(User, editable=False, blank=True, related_name="principalmodifier") # # # Please keep in mind that there are other user types that are related via foreign keys, for example: - class Administrator(models.Model): # # # principal = models.ForeignKey(Principal, help_text="The supervising principal for this Administrator") user = models.OneToOneField(User, blank=True) province = models.ForeignKey( Province) landline = models.CharField(blank=True, max_length=20) mobile = models.CharField(blank=True, max_length=20) created_by = models.ForeignKey(User, editable=False, blank=True, related_name="administratorcreator") modified_by = models.ForeignKey(User, editable=False, blank=True, related_name="administratormodifier") I am aware that Django does use a one-to-one relationship for multi-table inheritance behind the scenes. I am just not qualified enough to decide which is a more sound approach.

    Read the article

  • bidirectional OneToOne Mapping : From Entity to subclass and from superclass to Entity?

    - by Teocali
    I'm trying to establish a tricky bidirectional OneToOne mapping in hibernate. I got the following classes : @Entity @Inheritance(strategy = InheritanceType.JOINED) public class Parent { @OneToOne private AnotherEntity anotherEntity; } @Entity public class Child1 extends Parent{} @Entity public class Child2 extends Parent{} @Entity public class AnotherEntity { @OneToOne(mappedBy = "anotherEntity") private Child1 child1; @OneToOne(mappedBy = "anotherEntity") private Child1 child2; } The problem here is when I'm launching the application : I got the following message : org.hibernate.MappingException: property [anotherEntity] not found on entity [Child1] at org.hibernate.mapping.PersistentClass.getRecursiveProperty(PersistentClass.java:429) at org.hibernate.mapping.PersistentClass.getReferencedProperty(PersistentClass.java:369) at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1614) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1362) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1727) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1778) at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:189) at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:350) at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:335) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133) at javax.servlet.GenericServlet.init(GenericServlet.java:160) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5015) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5302) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:962) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:536) at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1471) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:836) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:761) at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1436) at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:673) at org.apache.catalina.manager.ManagerServlet.doPut(ManagerServlet.java:431) at javax.servlet.http.HttpServlet.service(HttpServlet.java:644) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) One obvious solution would be to move the anotherEntity field to Child1 and Child2, but it would mean lose the link from Parent to AnotherEntity. Any help welcome.

    Read the article

  • Hibernate + Spring : cascade deletion ignoring non-nullable constraints

    - by E.Benoît
    Hello, I seem to be having one weird problem with some Hibernate data classes. In a very specific case, deleting an object should fail due to existing, non-nullable relations - however it does not. The strangest part is that a few other classes related to the same definition behave appropriately. I'm using HSQLDB 1.8.0.10, Hibernate 3.5.0 (final) and Spring 3.0.2. The Hibernate properties are set so that batch updates are disabled. The class whose instances are being deleted is: @Entity( name = "users.Credentials" ) @Table( name = "credentials" , schema = "users" ) public class Credentials extends ModelBase { private static final long serialVersionUID = 1L; /* Some basic fields here */ /** Administrator credentials, if any */ @OneToOne( mappedBy = "credentials" , fetch = FetchType.LAZY ) public AdminCredentials adminCredentials; /** Active account data */ @OneToOne( mappedBy = "credentials" , fetch = FetchType.LAZY ) public Account activeAccount; /* Some more reverse relations here */ } (ModelBase is a class that simply declares a Long field named "id" as being automatically generated) The Account class, which is one for which constraints work, looks like this: @Entity( name = "users.Account" ) @Table( name = "accounts" , schema = "users" ) public class Account extends ModelBase { private static final long serialVersionUID = 1L; /** Credentials the account is linked to */ @OneToOne( optional = false ) @JoinColumn( name = "credentials_id" , referencedColumnName = "id" , nullable = false , updatable = false ) public Credentials credentials; /* Some more fields here */ } And here is the AdminCredentials class, for which the constraints are ignored. @Entity( name = "admin.Credentials" ) @Table( name = "admin_credentials" , schema = "admin" ) public class AdminCredentials extends ModelBase { private static final long serialVersionUID = 1L; /** Credentials linked with an administrative account */ @OneToOne( optional = false ) @JoinColumn( name = "credentials_id" , referencedColumnName = "id" , nullable = false , updatable = false ) public Credentials credentials; /* Some more fields here */ } The code that attempts to delete the Credentials instances is: try { if ( account.validationKey != null ) { this.hTemplate.delete( account.validationKey ); } this.hTemplate.delete( account.languageSetting ); this.hTemplate.delete( account ); } catch ( DataIntegrityViolationException e ) { return false; } Where hTemplate is a HibernateTemplate instance provided by Spring, its flush mode having been set to EAGER. In the conditions shown above, the deletion will fail if there is an Account instance that refers to the Credentials instance being deleted, which is the expected behaviour. However, an AdminCredentials instance will be ignored, the deletion will succeed, leaving an invalid AdminCredentials instance behind (trying to refresh that instance causes an error because the Credentials instance no longer exists). I have tried moving the AdminCredentials table from the admin DB schema to the users DB schema. Strangely enough, a deletion-related error is then triggered, but not in the deletion code - it is triggered at the next query involving the table, seemingly ignoring the flush mode setting. I've been trying to understand this for hours and I must admit I'm just as clueless now as I was then.

    Read the article

  • Hibernate one to one with multiple columns

    - by Erdem Emekligil
    How can i bind two columns, using @OneToOne annotation? Lets say I've 2 tables A and B. Table A: id1 (primary key) id2 (pk) other columns Table B: id1 (pk) id2 (pk) other columns In class A i want to write something like this: @OneToOne(fetch = FetchType.EAGER, targetEntity = B.class) @JoinColumn(name = "id1 and id2", referencedColumnName = "id1 and id2") private B b; Is it possible to do this using annotations? Thanks.

    Read the article

  • Hibernate noob fetch join problem

    - by Bruce
    Hi all I have two classes, Test2 and Test3. Test2 has an attribute test3 that is an instance of Test3. In other words, I have a unidirectional OneToOne association, with test2 having a reference to test3. When I select Test2 from the db, I can see that a separate select is being made to get the details of the associated test3 class. This is the famous 1+N selects problem. To fix this to use a single select, I am trying to use the fetch=join annotation, which I understand to be @Fetch(FetchMode.JOIN) However, with fetch set to join, I still see separate selects. Here are the relevant portions of my setup.. hibernate.cfg.xml: <property name="max_fetch_depth">2</property> Test2: public class Test2 { @OneToOne (cascade=CascadeType.ALL , fetch=FetchType.EAGER) @JoinColumn (name="test3_id") @Fetch(FetchMode.JOIN) public Test3 getTest3() { return test3; } NB I set the FetchType to EAGER out of desperation, even though it defaults to EAGER anyway for OneToOne mappings, but it made no difference. Thanks for any help! Edit: I've pretty much given up on trying to use FetchMode.JOIN - can anyone confirm that they have got it to work ie produce a left outer join? In the docs I see that "Usually, the mapping document is not used to customize fetching. Instead, we keep the default behavior, and override it for a particular transaction, using left join fetch in HQL" If I do a left join fetch instead: query = session.createQuery("from Test2 t2 left join fetch t2.test3"); then I do indeed get the results I want - ie a left outer join in the query.

    Read the article

  • What is the "owning side" in an ORM mapping?

    - by Yousui
    Hi guys, I'm new to JPA. Now I have a question that what exactly is the owning side mean? I only have a rough idea of it. Can someone give me an explanation with some mapping examples(one to many, one to one, many to one) please? Great thanks. ps, the following text is excerpt from the decription of @OneToOne in java EE 6 documentation. You can see the concept owning side in it. Defines a single-valued association to another entity that has one-to-one multiplicity. It is not normally necessary to specify the associated target entity explicitly since it can usually be inferred from the type of the object being referenced. If the relationship is bidirectional, the non-owning side must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the owning side.

    Read the article

  • How to handle JPA annotations for a pointer to a generic interface

    - by HDave
    I have a generic class that is also a mapped super class that has a private field that holds a pointer to another object of the same type: @MappedSuperclass public abstract class MyClass<T extends MyIfc<T>> implements MyIfc<T> { @OneToOne() @JoinColumn(name = "previous", nullable = true) private T previous; ... } My problem is that Eclipse is showing an error in the file at the OneToOne "Target Entity "T" for previous is not an Entity." All of the implementations of MyIfc are, in fact, Entities. I should also add that each concrete implementation that inherit from MyClass uses a different value for T (because T is itself) so I can't use the "targetEntity" attribute. I guess if there is no answer then I'll have to move this JPA annotation to all the concrete subclasses of MyClass. It just seems like JPA/Hibernate should be smart enough to know it'll all work out at run-time. Makes me wonder if I should just ignore this error somehow.

    Read the article

  • JPA entity design / cannot delete entity

    - by timaschew
    I though its simple what I want, but I cannot find any solution for my problem. I'm using playframework 1.2.3 and it's using Hibernate as JPA. So I think playframework has nothing to do with the problem. I have some classes (I omit the nonrelevant fields) public class User { ... } public class Task { public DataContainer dataContainer; } public class DataContainer { public Session session; public User user; } public class Session { ... } So I have association from Task to DataContainer and from DataContainer to Sesssion and the DataContainer belongs to a User. The DataContainers can have always the same User, but the Session have to be different for each instance. And the DataContainer of a Task have also to be different in each instance. A DataContainer can have a Sesesion or not (it's optinal). I use only unidirectional assoc. It should be sufficient. In other words: Every Task must has one DataContainer. Every DataContainer must has one/the same User and can have one Session. To create a DB schema I use JPA annotations: @Entity public class User extends Model { ... } @Entity public class Task extends Model { @OneToOne(optional = false, cascade = CascadeType.ALL) public DataContainer dataContainer; } @Entity public class DataContainer extends Model { @OneToOne(optional = true, cascade = CascadeType.ALL) public Session session; @ManyToOne(optional = false, cascade = CascadeType.ALL) public User user; } @Entity public class Session extends Model { ... } BTW: Model is a play class and provides the primary id as long type. When I create some for each entity a object and 'connect them', I mean the associations, it works fine. But when I try to delete a Session, I get a constraint violation exception, because a DataContainer still refers to the Session I want to delete. I want that the Session (field) of the DataContainer will be set to null respectively the foreign key (session_id) should be unset in the database. This will be okay, because its optional. I don't know, I think I have multiple problems. Am I using the right annotation @OneToOne ? I found on the internet some additional annotation and attributes: @JoinColumn and a mappedBy attribute for the inverse relationship. But I don't have it, because its not bidirectional. Or is a bidirectional assoc. essentially? Another try was to use @OnDelete(action = OnDeleteAction.CASCADE) the the contraint changed from NO ACTIONs when update or delete to: ADD CONSTRAINT fk4745c17e6a46a56 FOREIGN KEY (session_id) REFERENCES annotation_session (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE; But in this case, when I delete a session, the DataContainer and User is deleted. That's wrong for me. EDIT: I'm using postgresql 9, the jdbc stuff is included in play, my only db config is db=postgres://app:app@localhost:5432/app

    Read the article

  • Hibernate one-to-one mapping

    - by Andrey Yaskulsky
    I have one-to-one hibernate mapping between class Student and class Points: @Entity @Table(name = "Users") public class Student implements IUser { @Id @Column(name = "id") private int id; @Column(name = "name") private String name; @Column(name = "password") private String password; @OneToOne(fetch = FetchType.EAGER, mappedBy = "student") private Points points; @Column(name = "type") private int type = getType(); //gets and sets... @Entity @Table(name = "Points") public class Points { @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "student")) @Id @GeneratedValue(generator = "generator") @Column(name = "id", unique = true, nullable = false) private int Id; @OneToOne @PrimaryKeyJoinColumn private Student student; //gets and sets And then i do: Student student = new Student(); student.setId(1); student.setName("Andrew"); student.setPassword("Password"); Points points = new Points(); points.setPoints(0.99); student.setPoints(points); points.setStudent(student); Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(student); session.getTransaction().commit(); And hibernate saves student in the table but not saves corresponding points. Is it OK? Should i save points separately?

    Read the article

  • How do I create self-relationships in polymorphic inheritance in Elixir and Pylons?

    - by Turukawa
    I am new to programming and am following the example in the Pylons documentation on creating a Wiki. The database I want to link to the wiki was created with Elixir so I rewrote the Wiki database schema and have continued from there. In the wiki there is a requirement for a Navigation table which is inherited by Pages and Sections. A section can have many pages, while a page can only have one section. In addition, each sibling node can be chain-referenced to each other. So: Nav has "section" (OneToMany) and "before" (OneToOne - to reference preceeding node) Page has "section" (ManyToOne - many pages in one section) and inherits "before" Section inherits all from Nav The code I've written looks like this: class Nav(Entity): using_options(inheritance='multi') name = Field(Unicode(30), default=u'Untitled Node') path = Field(Unicode(255), default=u'') section = OneToMany('Page', inverse='section') after = OneToOne('Nav', inverse='before') before = OneToMany('Nav', inverse='after') class Page(Nav): using_options(inheritance='multi') content = Field(UnicodeText, nullable=False) posted = Field(DateTime, default=now()) title = Field(Unicode(255), default=u'Untitled Page') heading = Field(Unicode(255)) tags = ManyToMany('Tag') comments = OneToMany('Comment') section = ManyToOne('Nav', inverse='section') class Section(Nav): using_options(inheritance='multi') Errors received on this: sqlalchemy.exc.OperationalError: (OperationalError) table nav has no column named aftr_id u'INSERT INTO nav (name, path, aftr_id, row_type) VALUES (?, ?, ?, ?)' I've also tried: before = ManyToMany('Nav', inverse='before') on Nav in the hopes this might break the problem, but also not. The original SQLAlchemy code from the tutorial for these declarations is as follows: nav_table = schema.Table('nav', meta.metadata, schema.Column('id', types.Integer(), schema.Sequence('nav_id_seq', optional=True), primary_key=True), schema.Column('name', types.Unicode(255), default=u'Untitled Node'), schema.Column('path', types.Unicode(255), default=u''), schema.Column('section', types.Integer(), schema.ForeignKey('nav.id')), schema.Column('before', types.Integer(), default=None), schema.Column('type', types.String(30), nullable=False) ) page_table = schema.Table('page', meta.metadata, schema.Column('id', types.Integer, schema.ForeignKey('nav.id'), primary_key=True), schema.Column('content', types.Text(), nullable=False), schema.Column('posted', types.DateTime(), default=now), schema.Column('title', types.Unicode(255), default=u'Untitled Page'), schema.Column('heading', types.Unicode(255)), ) section_table = sa.Table('section', meta.metadata, schema.Column('id', types.Integer, schema.ForeignKey('nav.id'), primary_key=True), ) orm.mapper(Nav, nav_table, polymorphic_on=nav_table.c.type, polymorphic_identity='nav') orm.mapper(Section, section_table, inherits=Nav, polymorphic_identity='section') orm.mapper(Page, page_table, inherits=Nav, polymorphic_identity='page', properties={ 'comments':orm.relation(Comment, backref='page', cascade='all'), 'tags':orm.relation(Tag, secondary=pagetag_table) }) Any help is much appreciated.

    Read the article

  • How to make an entity out of a join table without primary key

    - by tputkonen
    I'm trying to generate JPA entities out of an existing database having an "interesting" design. Database has a table called UserSet, which can have links to several other UserSets. There is a one to many relation between UserSets and LinkedUserSets. LinkedUserSets also has one to one relation to UserSets. I tried to generate a JPA Entity out of the database structure using Dali JPA Tools. The resulting entity Linkeduserset misses @Id or @EmbeddedId annotation and thus failes to compile. As the resulting entity contains only two @JoinColumns (which cannot be marked as @Id), I have not so far found a way around this issue. Database structure can not be modified in any way. Is there a way to overcome this somehow? Relevant pars of create table statements: CREATE TABLE `LinkedUserSets` ( `UsrSetID` INT(11) NOT NULL DEFAULT '0' , `ChildID` INT(11) NOT NULL DEFAULT '0' , CONSTRAINT `fk_LinkedUserSets_UserSet1` FOREIGN KEY (`UsrSetID` ) REFERENCES `UserSet` (`UsrSetID` )); CREATE TABLE `UserSet` ( `UsrSetID` INT(11) NOT NULL AUTO_INCREMENT , PRIMARY KEY (`UsrSetID`), CONSTRAINT `fk_UserSet_LinkedUserSets1` FOREIGN KEY (`UsrSetID` ) REFERENCES `LinkedUserSets` (`ChildID` )); Generated entities: @Entity @Table(name="linkedusersets") public class Linkeduserset { //bi-directional many-to-one association to Userset @ManyToOne @JoinColumn(name="UsrSetID") private Userset userset1; //bi-directional one-to-one association to Userset @OneToOne @JoinColumn(name="ChildID") private Userset userset2; } @Entity @Table(name="userset") public class Userset { private static final long serialVersionUID = 1L; @Id @Column(name="UsrSetID") private int jngSetID; //bi-directional many-to-one association to Linkeduserset @OneToMany(mappedBy="userset1") private Set<Linkeduserset> linkedusersets; //bi-directional one-to-one association to Linkeduserset @OneToOne(mappedBy="userset2") private Linkeduserset linkeduserset; } Error message: Entity "Linkeduserset" has no Id or EmbeddedId

    Read the article

  • Does Hibernate support one-to-one associations as pkeys?

    - by Andrzej Doyle
    Hi all, Can anyone tell me whether Hibernate supports associations as the pkey of an entity? I thought that this would be supported but I am having a lot of trouble getting any kind of mapping that represents this to work. In particular, with the straight mapping below: @Entity public class EntityBar { @Id @OneToOne(optional = false, mappedBy = "bar") EntityFoo foo // other stuff } I get an org.hibernate.MappingException: "Could not determine type for: EntityFoo, at table: ENTITY_BAR, for columns: [org.hibernate.mapping.Column(foo)]" Diving into the code it seems the ID is always considered a Value type; i.e. "anything that is persisted by value, instead of by reference. It is essentially a Hibernate Type, together with zero or more columns." I could make my EntityFoo a value type by declaring it serializable, but I wouldn't expect this would lead to the right outcome either. I would have thought that Hibernate would consider the type of the column to be integer (or whatever the actual type of the parent's ID is), just like it would with a normal one-to-one link, but this doesn't appear to kick in when I also declare it an ID. Am I going beyond what is possible by trying to combine @OneToOne with @Id? And if so, how could one model this relationship sensibly?

    Read the article

1 2 3  | Next Page >