I have a API in JavaSpring and i want to know how can i get All "Finances" by user id, relly got stuck on that and i want to send a body to the API that sends a UserId and get all Finance matching the user
@Entity
@Table(name = "finance")
public class Finance {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(nullable = false)
private String title;
private String description;
@Column(nullable = false)
private String date;
@Column(nullable = false)
private Integer value;
My code is like this now and i have no idea what i am doing, i try to create the repository just to find out that i dont know to do that
Service:
public ResponseEntity<Object> GetFinanceByUserId(Integer userId) {
List<Finance> userFinances = financeRepository.findByUserId(userId);
return new ResponseEntity<>(userFinances, HttpStatus.OK);
}
Repository:
public interface FinanceRepository extends JpaRepository<Finance, Integer> {
List<Finance> findByUserId(Integer userId);
}
2
Answers
You can change entity like below
Entity
Repository
You should to prefer what type of relationship do you prefer: table vs entity.
If you choose table relationship your code should be like this.
Entity
Repository method
When you choose entity relationship, your code should be like this
Entity
Repository method
In this case you don’t need to create whole user, you need do define only id field.
You can’t mixing both variants because it may produce error:
"Column 'person_id' is duplicated in mapping for entity $entityName$ (use '@Column(insertable=false, updatable=false)' when mapping multiple properties to the same column"
.Of course you can add these params insertable and updatable. But it produce new error when you tried to manage entity bidirectional way. In this case when you mixing both managing type you have to set user_id field when adding a new finance to User entity.