i am new to Spring data jpa and learning how to save data in database . I have this entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
@Entity
@Table(name = "account")
public class Account {
@Id
private int id;
private String password;
}
Service layer
@Service
public class AccountsService {
@Autowired
private AccountDAO accountDAO;
public ResponseEntity<?> addAccount( Account account) {
try {
Account response = accountDAO.save(account);
if (response != null) {
return ResponseEntity.status(HttpStatus.CREATED).body(response);
} else {
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
public ResponseEntity<?> getAllAccounts() {
List<Account> accounts = accountDAO.findAll();
if(accounts!=null && accounts.size()>0) {
return ResponseEntity.status(HttpStatus.OK).body(accounts);
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No Accounts exists");
}
}
}
@RestController
public class AccountController {
@Autowired
private AccountsService accountsService;
@PostMapping("api/v1/addAccount")
private ResponseEntity<?> addAccount(@RequestBody Account account) {
return accountsService.addAccount(account);
}
@GetMapping("/api/v1/getAccounts")
private ResponseEntity<?> getAccounts() {
return accountsService.getAllAccounts();
}
}
Dao
import com.example.examDummy.models.Account;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AccountDAO extends JpaRepository<Account,Integer> {
}
now when i try to add Account with following json
{
"id":1,
"password":"fddfdfd@X123"
}
i am getting response
{
"id": 1,
"password": "fddfdfd@X123"
}
which is expected only but when i try to add one more account with same id and its json is like this
{
"id": 1,
"password": "Amit@123"
}
i am getting this response
{
"id": 1,
"password": "Amit@123"
}
which is not expected since it should be primary constraint violation.Can anyone please help me resolve this issue
this is schema of account table
mysql> describe account ;
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| password | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql>