P
P
parkito2016-08-21 21:41:45
Java
parkito, 2016-08-21 21:41:45

How to generate primary key in jpa?

Hello. Help, please, to solve a problem. It would be desirable that the value of the primary key, when adding a new object, was generated by itself.
For this I do:

@Entity
public class Tariff {
    @Id
    @Column(name = "id")
    @GeneratedValue
    private int id;
    @Basic
    @Column(name = "title")
    private String title;

    public Tariff() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Tariff(String title) {
//        this.id = id;
        this.title = title;
    }  
}

and correspondingly
public class TariffDAO {
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("operator");
    private EntityManager em = emf.createEntityManager();

    public static void main(String[] args) {
        TariffDAO tariffDAO = new TariffDAO();
        tariffDAO.addTariff("Base");
    }

    public void addTariff(String title) {
        Tariff tariff = new Tariff(title);
        try {
            em.getTransaction().begin();
            em.persist(tariff);
            em.getTransaction().commit();
            System.out.println("Tariff added");
        } catch (PersistenceException e) {
            e.printStackTrace();
            System.out.println("Fail");
        } finally {
            em.close();
            emf.close();
        }
    }

}

However, it pours out a long exception
ERROR: could not read a hi value
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'operator.hibernate_sequence' doesn't exist
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
  at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
  at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
  at com.mysql.jdbc.Util.getInstance(Util.java:387)
  at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:942)
  at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
  at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
  at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
  ...

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2016-08-22
@parkito

@GeneratedValue(strategy = GenerationType.IDENTITY)

or here is 1 or 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question