简体   繁体   中英

Using primary key serial with Postgresql and Hibernate causes exception when insert a new Object

I'm newbie using Hibernate, I'm trying to save an object to my Postgresql table, but my serial id column causes: org.hibernate.TransientObjectException , my column id declaration is this:

    @Table (schema = "inventarios", name = "inventory")
    @Entity (name = "inventory")
    public class Inventory implements DAO {

        @Id
        @GeneratedValue (strategy = GenerationType.AUTO, generator = "inventarios.inventory_id_seq")
        @SequenceGenerator (name = "inventarios.inventory_pkey", sequenceName = "inventarios.inventory_id_seq", allocationSize = 1)
        @Column (name = "id")
        private Integer id;
....

And my insert method is this:

@Override
    public int insert(Object o) {
        int lastId = 0;
        Transaction transaction = null;
        try (Session session = ConnectionFactory.getSessionFactory().openSession()) {
            if (o instanceof Inventory) {
                transaction = session.beginTransaction();
                ((Inventory) o).setLastUser(Utils.username);
                lastId = (Integer) session.save(o);
                transaction.commit();
            } else {
                Utils.showErrorDialog("No se pudo crear el registro a inventario, " +
                        "no se encontró la información correcta para realizar el registro.");
            }
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
            ErrorLogger.getInstance().log(e, Inventory.class.getName());
        }
        return lastId;
    }

I read that I need to flush the current session to be able perform the insert, but I don't know how to do it.

Previously it had these annotations, and it does the inserts well, but the ids generated them very randomly.

@Id
    @Column (name = "id")
    @GeneratedValue (generator = "native")
    @GenericGenerator (name = "increment", strategy = "increment")
    private Integer id;

My Postgresql version is 9.4 and my hibernate version is 5.4.10, any suggestions please?

It seems that I found a solution:

    @Id
    @GeneratedValue (generator = "inventarios.inventory_id_seq", strategy = GenerationType.AUTO)
    @Column (name = "id")
    private Integer id;

In the generator I put the name of the sequence of my table, and it seems that it works..

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