无法使用Hibernate从表中添加和删除数据

时间:2017-01-22 11:21:31

标签: java mysql hibernate jpa orm

获取数据非常有效,但我无法在表格中添加和删除数据。我该怎么办?

TaskDAO课程:

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课程:

@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课程:

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告诉我:

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

但我无法在数据库中看到任何变化。

表:

CREATE TABLE IF NOT EXISTS task (
  id SERIAL NOT NULL,
  name VARCHAR(150) NOT NULL,
  done BOOLEAN NOT NULL,
  PRIMARY KEY (id)
);

1 个答案:

答案 0 :(得分:2)

我几乎可以肯定,这个问题是由于您不以任何方式管理您的交易。关于查询,您可以获得数据,但是要在数据库中反映DML操作,您需要进行事务处理:

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);
        }
    }

另外,请不要忘记在手动管理会话时始终关闭会话。