L
L
lookingfor2014-08-14 09:06:29
Java
lookingfor, 2014-08-14 09:06:29

Is it possible to describe a one-to-many relationship with the ability to change a field with a foreign key?

The standard description of a one-to-many relationship using jpa looks something like this (for example)

public class User {
        .......
        @ManyToOne
        @JoinColumn(name="group_id")
        Group group;
        .......
    }

public class Group {
        @OneToMany
        Set<User> users;
    }

Accordingly, to add a user to a group, you need to do the following. I need code
user.setGroup( group );
like this
public class User {
        @ManyToOne
        @JoinColumn(name="group_id")
        long groupId;
    }

in code, it will look like this
user.setGroupId( id );
T. You need the ability to directly change the field with a foreign key.
Is it possible to describe such a construction and use it, or such an approach cannot be used?
Addition:
The question considered the possibility of generating a database structure with a hibernate. We came to the conclusion that this would not work. The solution is in the comments.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Smirnov, 2014-08-15
@lookingfor

Even though Hibernate requires a Group object at the object level, it actually only needs the group_id to store it correctly in the database. You can create an empty / fake (not read from the database) Group instance and specify the group_id you need for it. After that, it can be safely passed to user.setGroup(group); If the number of groups in the System is limited and all of them are known in advance (the subtext of the question implies this), then Group instances with a filled ID field can be stored as constants.

D
Dmitry, 2014-08-14
@CTAKAH4uK

Is this option not suitable?
You can try like this:

public class User {
        .......
        @ManyToOne
        @JoinColumn(name="group_id")
        Group group;
        .......
       @Basic
       @Column(name= "group_id")
        long groupId;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question