How to make several connections between 2 tables?

Hi all!
I have two classes:

public class User{
private int userId;
private List<Message> messages;
private Message lastMessage;
}
public class Message{
private int messageId;
private String msg;
}

As I understand I need two links between tables. And entities have to look like:

public interface UserEntity extends Entity {
   @OneToMany
    MessageEntity[] getMessageEntities();

    @OneToOne
    MessageEntity getMessageEntity();
}
public interface MessageEntity extends Entity {
    String getMessage();
    void setMessage(String message);

   void setUserEntity(UserEntity userEntity);
   UserEntity getUserEntity();
}

But something is wrong. Something is missing. How can such connections be made?

find the way:

public interface UserEntity extends Entity {
   @OneToMany(reverse = "getUserEntity")
    MessageEntity[] getMessageEntities();

    @OneToOne(reverse = "getUEntity")
    MessageEntity getMessageEntity();
}
public interface MessageEntity extends Entity {
    String getMessage();
    void setMessage(String message);

   void setUserEntity(UserEntity userEntity);
   UserEntity getUserEntity();

   void setUEntity(UserEntity userEntity);
   UserEntity getUEntity();
}

I tested a little - it seems to work. Is this approach normal or is it worth looking for another?

I hope I finally found the right path:

public interface UserEntity extends Entity {
   @OneToMany
    MessageEntity[] getMessageEntities();

    @OneToOne
    LastMessageEntity getLastMessageEntity ();
}
public interface MessageEntity extends Entity {
    String getMessage();
    void setMessage(String message);

    void setUserEntity(UserEntity userEntity);
    UserEntity getUserEntity();

    @OneToOne
    LastMessageEntity getLastMessageEntity ();
}
public interface LastMessageEntity extends Entity {
    
   void setUserEntity(UserEntity userEntity);
   UserEntity getUserEntity();

   void setMessageEntity(MessageEntity messageEntity);
   MessageEntity getMessageEntity ();
}
1 Like