I have used Spring Data JPA and @Embedabble to create the composite key. And one Base class BaseDate will be extended by all the Entity.
sysCreationDate will be generated during insertion (not null and non-updatable)
save user is working fine for the first time but there are 3 issues here-
- During the second call instead of throwing an exception it is updating the sysUpdateDate and userType
- During the first call sysUpdateDate is not null (@UpdateTimestamp)
- During the second call in response it returns the sysCreationDate as null
Below is the code- Embeddable class
@Embeddable
public class CompKey implements Serializable {
@Column(name ="USER_ID")
private String userId;
@Column(name ="USER_NAME")
private String userName;
public CompKey(String userId, String userName) {
super();
this.userId = userId;
this.userName = userName;
}
public CompKey() {
super();
}
//Getters /Setters /Equual and Hashcode
}
Base Class for Date
@MappedSuperclass
public abstract class BaseDate {
@CreationTimestamp
@Column(name = "SYS_CREATION_DATE", updatable=false, nullable=false)
private Calendar sysCreationDate;
@Column(name = "SYS_UPDATE_DATE")
@UpdateTimestamp
private Calendar sysUpdateDate;
public BaseDate(Calendar sysCreationDate, Calendar sysUpdateDate) {
this.sysCreationDate = sysCreationDate;
this.sysUpdateDate = sysUpdateDate;
}
public BaseDate() {
}
//Getters and Setters
}
Entity Class
@Entity
public class User extends BaseDate{
@Column(name = "USER_TYPE")
private String userType;
@EmbeddedId
private CompKey compkey;
public User() {
super();
}
public User(Calendar sysCreationDate, Calendar sysUpdateDate, String userType, CompKey compkey) {
super(sysCreationDate, sysUpdateDate);
this.userType = userType;
this.compkey = compkey;
}
//Getters and setters
}
Repo -
@Repository
public interface UserRepo extends CrudRepository<User, CompKey> {
}
Service and Controller -
@Service
public class UserService {
@Autowired
UserRepo userRepo;
public User saveUser(User user) {
return userRepo.save(user);
}
public Optional<User> getUser(CompKey key) {
return userRepo.findById(key);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@PostMapping("/save")
public User saveUser(@RequestBody User user) {
return userService.saveUser(user);
}
@GetMapping("/get")
public Optional<User> getUser(@RequestBody CompKey key) {
return userService.getUser(key);
}
Input -
{
"userType": "K",
"compkey": {
"userId": "1002",
"userName": "ASDF"
}
}
Output 1)-
{
"sysCreationDate": "2021-01-08T18:09:28.802+00:00",
"sysUpdateDate": "2021-01-08T18:09:28.802+00:00",
"userType": "K",
"compkey": {
"userId": "1002",
"userName": "ASDF"
}
{
"sysCreationDate": null,
"sysUpdateDate": "2021-01-08T18:10:43.206+00:00",
"userType": "K",
"compkey": {
"userId": "1002",
"userName": "ASDF"
}
}
Thanks in advance