简体   繁体   中英

CreateQuery returning the id of the new record when executing the SQL INSERT command

I am creating a DAO of the User entity. I'm doing the save method, I'd like it to return the created object or the id of the created object. Similar to JPARepository's saveAndFlush. Below is the code for the save method of the UserDAO class:

        public long save(User newUser) {
        String query = "insert into user (email,password,name,tenant) values(?,?,?,?) returning id";
        TypedQuery<Usuario> q = em.createQuery(query, User.class);

        q.setParameter(1, newUser.getCredencials().getEmail())
                .setParameter(2, newUser.getCredenciaals().getPassword()).setParameter(3, newUser.getName())
                .setParameter(4, newUser.getTenant());
        Usuario userSave = q.getSingleResult();
        long id = userSave.getId();
        return userSave;
}

My code is not running. You are experiencing the following errors on the console:

antlr.NoViableAltException: unexpected token: values
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: values near line 1, column 47 [insert into usuario (email,senha,nome,tenant) values(?,?,?,?) returning id]

Please help me to find the code error.

Try this approach:

Query query = em.createNativeQuery(sql);
BigInteger id= (BigInteger) query.getSingleResult();
long id = id.longValue();

The solution I found for my problem was to use createSQLQuery. Here is the code I used:

    EntityManagerFactory emFactory = em.getEntityManagerFactory();
    SessionFactory sessionFactory = emFactory.unwrap(SessionFactory.class);
    Session session = sessionFactory.openSession();
    Transaction txn = session.beginTransaction();

    String query = "insert into user (email,password,name,tenant) values(?,?,?,?)";
    session.createSQLQuery(query).setParameter(0, newUser.getCredenciais().getEmail())
    .setParameter(1, newUser.getCredenciais().getPassword()).setParameter(2, newUser.getName())
    .setParameter(3, newUser.getTenant()).executeUpdate();

    BigInteger result = (BigInteger) session.createSQLQuery("SELECT LAST_INSERT_ID()").uniqueResult();

    txn.commit();
    session.close();

Remembering that I'm using Mysql.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM