1

Getting data works perfectly, but I can't add and delete data from the table. What can I do ?

TaskDAO class:

public class TaskDAO {
    private Session session;

    public TaskDAO(Session session) {
        this.session = session;
    }

    public TaskDataSet get(long id) throws HibernateException {
        return session.get(TaskDataSet.class, id);
    }

    public List<TaskDataSet> getAll() throws HibernateException {
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<TaskDataSet> cq = builder.createQuery(TaskDataSet.class);
        Root<TaskDataSet> task = cq.from(TaskDataSet.class);
        cq.select(task);
        TypedQuery<TaskDataSet> q = session.createQuery(cq);
        List<TaskDataSet> allTask = q.getResultList();
        return allTask;
    }

    public long insert(String name) {
        return (Long) session.save(new TaskDataSet(name));
    }

    public void delete(long id) throws HibernateException {
        session.delete(get(id));
    }
}

TaskDataSet class:

@Entity
@Table(name="task")
public class TaskDataSet {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "name", unique = true, updatable = false, nullable = false)
    private String name;

    @Column(name = "done")
    private boolean done;

    public TaskDataSet() {}

    public TaskDataSet(String name) {
        this.name = name;
        done = false;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public boolean isDone() {
        return done;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    public void setDone(boolean done) {
        this.done = done;
    }
}

DBService class:

public class DBService {
    private static final String hibernate_show_sql = "true";
    private static final String hibernate_hbm2ddl_auto = "update";

    private SessionFactory sessionFactory;

    public DBService() {
        Configuration configuration = getMySqlConfiguration();
        this.sessionFactory = configuration.configure().buildSessionFactory();
    }

    private Configuration getMySqlConfiguration() {
        Configuration configuration = new Configuration();
        configuration.addAnnotatedClass(TaskDataSet.class);

        configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
        configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/test");
        configuration.setProperty("hibernate.connection.username", "root");
        configuration.setProperty("hibernate.connection.password", "root");
        configuration.setProperty("hibernate.show_sql", hibernate_show_sql);
        configuration.setProperty("hibernate.hbm2ddl.auto", hibernate_hbm2ddl_auto);
        return configuration;
    }


    public TaskDataSet getTask(long id) throws DBException {
        try {
            Session session = sessionFactory.openSession();
            TaskDAO dao = new TaskDAO(session);
            TaskDataSet dataSet = dao.get(id);
            session.close();
            return dataSet;
        } catch (HibernateException e) {
            throw new DBException(e);
        }
    }

    public List<TaskDataSet> getAllTasks() throws DBException {
        try {
            Session session = sessionFactory.openSession();
            TaskDAO dao = new TaskDAO(session);
            List<TaskDataSet> tasks = dao.getAll();
            return tasks;
        } catch (HibernateException e) {
            throw new DBException(e);
        }
    }

    public long addTask(String name) {
        Session session = sessionFactory.openSession();
        TaskDAO dao = new TaskDAO(session);
        return dao.insert(name);
    }

    public void deleteTask(long id) throws DBException {
        try {
            Session session = sessionFactory.openSession();
            TaskDAO dao = new TaskDAO(session);
            dao.delete(id);
        } catch (HibernateException e) {
            throw new DBException(e);
        }
    }

    public static void main(String[] args) throws DBException {
        DBService dbService = new DBService();
        dbService.addTask("Test3");

        for (TaskDataSet task : dbService.getAllTasks()) {
            System.out.println(task.getId());
            System.out.println(task.getName());
            System.out.println(task.isDone());
            System.out.println("---------------------------------");
        }

        dbService.deleteTask(1);

        for (TaskDataSet task : dbService.getAllTasks()) {
            System.out.println(task.getId());
            System.out.println(task.getName());
            System.out.println(task.isDone());
            System.out.println("---------------------------------");
        }
    }
}

Hibernate told me that:

14:20:29.738 [main] DEBUG org.hibernate.stat.internal.StatisticsInitiator - Statistics initialized [enabled=false]
14:20:29.748 [main] DEBUG org.hibernate.SQL - select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
14:20:29.758 [main] DEBUG org.hibernate.SQL - update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
14:20:29.789 [main] DEBUG org.hibernate.event.internal.AbstractSaveEventListener - Generated identifier: 12, using strategy: org.hibernate.id.enhanced.SequenceStyleGenerator

But I can't see any of changes at the database.

The table:

CREATE TABLE IF NOT EXISTS task (
  id SERIAL NOT NULL,
  name VARCHAR(150) NOT NULL,
  done BOOLEAN NOT NULL,
  PRIMARY KEY (id)
);
1
  • How did you set up your transaction management? Commented Jan 22, 2017 at 11:37

1 Answer 1

2

I am almost sure that this problem is due to the fact that you do not manage your transactions is any way. Regarding queries you get the data but for DML operations to be reflected on the database you need a transaction in place:

public long addTask(String name) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        TaskDAO dao = new TaskDAO(session);
        long id = dao.insert(name); 

        tx.commit();
        session.close()

        return id;
}

public void deleteTask(long id) throws DBException {
    try {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();            
        TaskDAO dao = new TaskDAO(session);
            dao.delete(id);
            tx.commit();
            session.close();
        } catch (HibernateException e) {
            throw new DBException(e);
        }
    }

Also do not forget to be always closing your sessions when you manage them manually.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.