0

I am creating a CRUD application using Servlets and Hibernate.

When I try to save a new entity using save(), then Hibernate executes the SQL Update query and not Insert. The entity already contains the generated Id (UUID) and as I understand it, it searches for this entity in the database (h2 in-memory) and does not find it. How to properly save an entity in the database if the id has already been generated.

@Entity
@Table(name = "MATCH")
public class Match implements Serializable {
    @Id
    @Column(name = "MATCH_ID")
    private UUID id;

    @ManyToOne
    private Player playerOne;

    @ManyToOne
    private Player playerTwo;

    @ManyToOne
    private Player winner;


    @Transient
    private int[] score = new int[2];

    public Match() {

    }

        //getters and setters
}




   public void executePost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
        Transaction transaction = null;
        try (Session session = DBHandler.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();

            UUID MatchUuid = UUID.fromString(servletRequest.getParameter("match-uuid"));  
            currentMatchService = CurrentMatchService.getInstance(); //service stores current matches in the app's memory
            currentMatch = currentMatchService.getMatch(MatchUuid);
            currentMatch.setWinner(currentMatch.getPlayerOne()); //player One set like winner just for test
            session.save(currentMatch);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
7
  • Hello, please share the entity as a formatted code snippet. Especially the definition of id field.
    – Mar-Z
    Commented Apr 2, 2023 at 17:30
  • 1
    Can you provide a minimal reproducible example? Commented Apr 2, 2023 at 17:32
  • 1
    Please also share the code part where you actually persist the entity.
    – Mar-Z
    Commented Apr 2, 2023 at 17:40
  • id = UUID.randomUUID(); when I create entity.
    – dKopyshov
    Commented Apr 2, 2023 at 17:58
  • OK. So you have another code in use when you create a new entity, right? And what is actually wrong? Are you getting any SQL errors? Please share it as well.
    – Mar-Z
    Commented Apr 2, 2023 at 18:18

1 Answer 1

0

As I understand the question you want to persist the entity in the database without letting Hibernate generate an identifier for you. To accomplish it you can use following code:

If the entity with the id already exists in the database and should be updated - please use:

session.merge(myEntity); // myEntity contains the id

If it's a new entity and should be inserted - please use:

UUUID id = UUID.randomUUID(); // new id will be generated
myEntity.setId(id);
session.persist(myEntity);
3
  • The entity does not exist in the database yet, but the error is the same. I tried persist(), but the error is the same. And I don't understand what's a problem.
    – dKopyshov
    Commented Apr 2, 2023 at 18:37
  • Why it says that hibernate uses SQL statement with update, not insert?
    – dKopyshov
    Commented Apr 2, 2023 at 18:40
  • You can activate the SQL logs in the system.properties hibernate.show_sql=true to get more information.
    – Mar-Z
    Commented Apr 2, 2023 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.