1

I have Java EE application with Hibernate mapped classes (I use *.hbm.xml mappings). Now I need to remake mappings with JPA annotations. All is fine but I can't create correct mapping with my Map property.

@Entity
@Table(name = DataBaseConstants.EMPLOYEE_TABLE)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = DataBaseConstants.EMPLOYEE_ID, sequenceName = DataBaseConstants.EMPLOYEE_SEQ)
@GeneratedValue(generator = DataBaseConstants.EMPLOYEE_ID)
@Column(name = DataBaseConstants.EMPLOYEE_ID)
private long id = 0;
@Column(name = DataBaseConstants.EMPLOYEE_NAME)
private String name = null;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = DataBaseConstants.ADDRESS_ID_FK)
private Address address = null; 

private Map<Office, Position> officePositions = null;

Here is part of data model in data base. DB MODEL IMAGE (Sorry I can't post images) Help me please to mapping officeEmployee MAP

In Hibernate i used this way and everything was OK.

<map name="officePositions" table="EMPLOYEE_POSITION_OFFICE" lazy="false"
                fetch="join" batch-size="100">
            <key>
            <column name="EMPLOYEE_ID"></column>
        </key>
        <map-key-many-to-many class="com.example.jpajdbctask.entities.Office">
            <column name="OFFICE_ID">
            </column>
        </map-key-many-to-many>
        <many-to-many column="POSITION_ID"
            class="com.example.jpajdbctask.entities.Position" />
        </map> 

2 Answers 2

1

I never used it myself so i can't help you with the exact implementation, but you need to use the @CollectionOfElements annotation, an example would be:

@CollectionOfElements(fetch=FetchType.EAGER)
@JoinTable(
    name = "MappingTable", 
    joinColumns = @JoinColumn(name = "mapOwner"))
@Column(
   name = "mapValueItem", 
   nullable = false
)  
@org.hibernate.annotations.MapKey(
    columns={
        @Column(
             name="mapKeyItem"
        )
   }
)
protected Map<String, String> getMapping() {
    return mapping_;
}

this forum might be helpful.

Sign up to request clarification or add additional context in comments.

1 Comment

thx, i have tried, but my db model does not suitable for it, Hibernate tries to access "officePositions_ID" column and etc. I add hibernate mapping of this class in persistence.xml
0

For a basic case (where key is some primitive), here's a JavaDoc for MapKey annotation with an example.

It seems that in your case @MapKeyColumn should be used; here's an example very similar to yours.

You'll have to change your Map within Employee class to Map<Office, EmployeePositionOffice>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.