NHibernate:基于非主键的many-to-one关联映射咨询
Absolutely you can make this work! Hibernate’s many-to-one mapping totally supports associating entities via non-primary key fields—you just need to use the property-ref attribute to specify which non-key field to use for the join. Let me break down the exact configuration for you.
Step 1: Configure the many-to-one in A.hbm.xml
In your A.hbm.xml file, add the many-to-one element pointing to the B entity. The key here is using property-ref to tell Hibernate to use the Name field (instead of B's primary key) for the association:
<class name="com.yourpackage.A" table="A"> <!-- Primary key mapping for A --> <id name="id" column="Id" type="java.lang.Long"> <generator class="native"/> </id> <!-- A's own Name field --> <property name="name" column="Name" type="java.lang.String"/> <!-- Many-to-one association to B, using Name fields for matching --> <many-to-one name="b" class="com.yourpackage.B" column="Name" property-ref="name"/> </class>
Step 2: Ensure B's mapping is set up correctly
In B.hbm.xml, make sure the Name field is mapped, and it’s strongly recommended to add a unique constraint (since a many-to-one expects a single matching B instance; duplicate Names in B would cause unexpected behavior or errors):
<class name="com.yourpackage.B" table="B"> <!-- Primary key mapping for B --> <id name="id" column="Id" type="java.lang.Long"> <generator class="native"/> </id> <!-- B's Name field, marked as unique --> <property name="name" column="Name" type="java.lang.String" unique="true"/> </class>
Key Details to Note
column="Name"in themany-to-oneelement refers to the column in table A that holds the value to match against table B's Name column.property-ref="name"is the critical part: it tells Hibernate to use thenameproperty of the B entity (and its corresponding database column) instead of B's primary key for the association.- Unique Constraint: Always ensure table B's Name column is unique. If multiple B records have the same Name, Hibernate won't know which one to associate with an A record, leading to exceptions or incorrect results.
内容的提问来源于stack exchange,提问作者Powerslave

