The concept for one-to-one mapping. Explain the mapping

前端 未结 2 708
醉酒成梦
醉酒成梦 2020-12-11 13:57

How to define a One-to-One relation between 2 classes ? I think I am going wrong somewhere,conceptually. I don\'t know what ,but it is.

Let us suppose t

2条回答
  •  醉酒成梦
    2020-12-11 14:38

    If part of your question is also "...I think I am going wrong somewhere,conceptually... ", I'd like to provide some explanation.

    First of all, One-to-One means, that the reference is between objects (instances). Other words, there must be reference from one object to other. Not only a common simple type (i.e. String name_pm or String name_c)

    Both objects should reference each other:

    public class PM {
        private Country country;  // reference to an instance of the PM
        ...
    }
    
    public class Country {
        private PM pm; // reference to an instance of the Country
        ...
    }
    

    On a DB level, it is a bit more trickier. Because references are based on ID columns and we do assure us, that these two Country-PM will always belong together, we have to reuse the ID value.

    So, one object will play the role of the Master, e.g. Country and the second will assign its ID based on it. If we won't follow that pattern, we cannot be sure, that there will sooner or later arise some many-to-one or many-to-many relation.

    And that's why the mapping usually looks like this

    
        
            
        
        
        
    
    
    
        
            
            
               country
            
        
        
    
    

    But one-to-one mapping is really very exceptional. I guess that mapping many-to-on on PM side (with country id reference in DB) could be more suitable. It is different approach at all, but...

    Please, try to see this nice article:

    • One-to-One example (XML Mapping)
    • 5.1.13. One-to-one

提交回复
热议问题