1

I have a scenario where there is a DB column which should be like sequence for each primary key + another column. The column's value should again reset and start from 1 for another.

For example:

col1(PK)------col2(FK)-------my-column

0---------------0-------------------1

1---------------0-------------------2

2---------------0-------------------3

3---------------1-------------------1

4---------------1-------------------2

5---------------1-------------------3

For col1(PK), I can simply annotate with @GeneratedValue(strategy = GenerationType.IDENTITY)

In the same way, I want to generate value for my-column as well.

From the code side, This is what it looks like:

classA{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String col2;
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "classa", orphanRemoval = true)
    private List<ClassB> listB = new ArrayList<>();

    //I want to generate/increment the value of myCol each time based on value of col1 & col2
    @Column(name = "my-col")
    private Integer myCol;
//getter/setters
}

ClassB{
    @Id
    @Column(name = "col1")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer col1;

    @ManyToOne
    @JoinColumn(name = "col2")
    private ClassA classa;

//getter/setter
}
2
  • col1(PK)------col2(FK)-------my-column belong to table ClassA or ClassB? Your table names is bad practices. Commented Feb 6, 2019 at 16:38
  • ClassA. This is not the real time column name. This is just sample which is similar as my real world application. I am not allowed to post real code Commented Feb 6, 2019 at 16:40

1 Answer 1

1

When you add elements in listB of instance of classA, just generate a value for myCol each time and reset:

AtomicInteger value = new AtomicInteger(1);
classa.setListB(classa.getListB.stream.map(b->b.setMyCol(value.getAndIncrement())))
Sign up to request clarification or add additional context in comments.

1 Comment

This will just set 1

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.