简体   繁体   中英

dynamodb java many to one

i wanted to try out dynamodb

I was able to save a single Object. Now i wanted to try to create a many to one association.

Many Tasks sould be attached to a single User.

@DynamoDBTable(tableName = "User")
public class User {
    private String id;
    List<Task> tasks = new ArrayList<Task>();

    @DynamoDBHashKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    @DynamoDBAttribute
    public List<Task> getTasks() {
        return this.tasks;
    }

    public void setTasks(List<Task> taskMap) {
        this.tasks = taskMap;
    }

    public void addTask(Task task){
        this.tasks.add(task);
    }
}

@DynamoDBTable(tableName = "Task")
public class Task {
    private String id;
    private String name;

    @DynamoDBHashKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    public Task(String name) {
        this.name = name;
    }

    @DynamoDBAttribute
    public String getName(){
        return this.name;
    }

    public void setname(String name){
        this.name = name;
    }
}

and now i am trying to save the user with the coresponding tasks

Task task1 = new Task("test");
Task task2 = new Task("test2");
User user = new User();
user.addTask(task1);
user.addTask(task2);
userRepository.save(user);

I know it doesn't work like this but maybe someone can give me an example on how to do it.

in a relational database world the tables would look something like this

User
id|.....

Task
id|name

User_Tasks
user_id|task_id

But how to do it the right way with dynamodb

THANKS!

I hope you are saving both User and Task in single DynamoDB table (ie User). Please annotate the task class with @DynamoDBDocument rather than @DynamoDBTable.

@DynamoDBDocument
public class Task {

}
  • Add getters/setters accordingly and an empty constructor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM