0

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>
  • 4
    The `save` method acts as a "save or update". Not sure of what you want to do in this case, but this question is close to yours at least : https://stackoverflow.com/questions/35817584/spring-jpa-repository-prevent-update-on-save – Arnaud Jul 31 '23 at 14:30
  • I simply wan to prevent adding same record into the database by using @Id annotation since it will make it primary key in database ,so adding the same record again should throw error – Amit Bhatiwal Jul 31 '23 at 14:46
  • @Arnaud adding same id record should throw error like ERROR 1062 (23000): Duplicate entry '1' for key 'account.PRIMARY' – Amit Bhatiwal Jul 31 '23 at 14:56
  • 1
    It's doing exactly what you're asking it to. As the first comment states, save does a save or update, so in your case, when you ask it to save the record with ID of 1, it's simply updating the existing record, which is what it's supposed to do. – lane.maxwell Jul 31 '23 at 14:59
  • 1
    Are you sure you want to get the ID value from the outside when creating the object anyway. Instead you should get it from a sequence of the db ? – binboavetonik Jul 31 '23 at 16:04
  • 1
    @binboavetonik i am expecting it to throw error when inserting the same record again in database with save method – Amit Bhatiwal Jul 31 '23 at 17:55
  • See this answer from the linked question, it is easy to implement : https://stackoverflow.com/a/54114617/5612858 – Arnaud Aug 01 '23 at 05:40
  • @Arnaud what is concept of Id annotation which is used to indicate primary key in database , if we have to check programmatically if record need to be checked by userRepository.existsById(username) – Amit Bhatiwal Aug 01 '23 at 05:44
  • Entity class is just a replica of your Table structure, like every good table have a primary key so is the Entity have `@Id`, this Id is used with JPA repository this is how the Spring JPA have been designed. You have to check if the record exists or else its bound to be overwritten, you can also use native query if you want though. – Jay Yadav Aug 02 '23 at 04:50
  • @AmitBhatiwal you can never be sure programatically without a global lock even if you check with existsById. After you read and make sure of no record, before you insert someone else can insert. So if you want an exception with save you have to implement it with a INSERT statement yourself – binboavetonik Aug 02 '23 at 10:12

0 Answers0