java - 为什么hibernate不将更改保存到数据库?

标签 java hibernate h2

这是我的配置文件 hibernate.cfg.xml

  <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.password">1</property>
        <property name="hibernate.connection.url">
            jdbc:h2:mem:test3;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto"> create </property>
        <mapping resource="user.hbm.xml"></mapping>
        <mapping resource="role.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

第一次运行此代码时

session.beginTransaction();

User stock = new User();
        User stock1 = new User();
        Role role = new Role();
        role.setId(54l);
        role.setName("student");
        session.save(role);
        stock.setBirthday(new Date(56 + 65));
        stock.setEmail("emaill");
        stock.setFirstName("dima");
        stock.setPassword("1");
        stock.setRole(role);
        System.out.println(stock.getId());

        stock1.setBirthday(new Date(56 + 65));
        stock1.setEmail("emassill");
        stock1.setFirstName("dima");
        stock1.setPassword("1");
        stock1.setRole(role);
        System.out.println(stock.getId());
        session.save(stock);
        session.save(stock1);
        session.getTransaction().commit();

        JdbcUserDao dao = new JdbcUserDao();
        System.out.println(dao.findByEmail("emassill").getFirstName());
        System.out.println(dao.findAll().get(0).getFirstName());`

输出是:
迪马 迪玛

如果我只保存了一个用户,dao.findAll().size() 给出“1”,长话短说,对数据库的更改不会保存。 这是为什么?

对于 findAll(),我使用 DriverManager.getConnection() 等

@Override
public List<User> findAll() {
    List<User> result = new ArrayList<User>();
    try {
        connection = createConnection();
        connection.setAutoCommit(false);
        statement = connection.createStatement();
        resultSet = statement.executeQuery(FIND_ALL);
        while (resultSet.next()) {
            User temp = new User();
            temp.setId(resultSet.getLong(8));
            temp.setLogin(resultSet.getString(2));
            temp.setPassword(resultSet.getString(3));
            temp.setEmail(resultSet.getString(4));
            temp.setFirstName(resultSet.getString(5));
            temp.setLastName(resultSet.getString(6));
            temp.setBirthday(resultSet.getDate(7));
            Role tempRole = new Role();
            JdbcRoleDao jdbcRoleDao = new JdbcRoleDao();
            tempRole = jdbcRoleDao.findById(resultSet.getLong("id_role"));
            temp.setRole(tempRole);
            result.add(temp);
        }
    } catch (SQLException e) {
        myRollback();
        log.error(e, e);
        throw new RuntimeException(e);
    } finally {
        close();
    }
    return result;
}

public Connection createConnection() throws SQLException {
    url = "jdbc:h2:mem:test3;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false";// "jdbc:h2:./first";
    driver = "org.h2.Driver";
    login = "sa";
    password = "1";
    // init();
    try {

        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        log.error(e, e);
        throw new RuntimeException(e);
    }
    Connection connection = DriverManager.getConnection(url, login,
            password);
    RunScript.execute(url, login, password, SCHEMA,
            Charset.forName("UTF-8"), false);
        return connection;
}

我的项目使用了jdbcUserDao,我尝试使用hibernateUserdao

附注 是的,我的控制台有文本:

Hibernate: alter table USER drop constraint FK_32nqg51ic2mg57ysalv1wnmdc if exists
Hibernate: drop table ROLE if exists
Hibernate: drop table USER if exists
Hibernate: create table ROLE (id bigint generated by default as identity, name varchar(45) not null, primary key (id))
Sep 29, 2014 7:49:19 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table USER drop constraint FK_32nqg51ic2mg57ysalv1wnmdc if exists
Sep 29, 2014 7:49:19 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Table "USER" not found; SQL statement:
alter table USER drop constraint FK_32nqg51ic2mg57ysalv1wnmdc if exists [42102-181]
Hibernate: create table USER (id bigint generated by default as identity, login varchar(45) not null, password varchar(45) not null, email varchar(45) not null, first_name varchar(45) not null, last_name varchar(45) not null, birthday date not null, id_role bigint not null, primary key (id))
Hibernate: alter table ROLE add constraint UK_9glod3qre7ighyp4ci4t6fcoy  unique (name)
Hibernate: alter table USER add constraint UK_slockai06wyhy7i5c8vnd2o31  unique (login)
Hibernate: alter table USER add constraint UK_oso07pudw19e66bs4yp8hwpux  unique (email)
Hibernate: alter table USER add constraint FK_32nqg51ic2mg57ysalv1wnmdc foreign key (id_role) references ROLE
Sep 29, 2014 7:49:19 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into ROLE (id, name) values (null, ?)
546
546
Hibernate: insert into USER (id, login, password, email, first_name, last_name, birthday, id_role) values (null, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into USER (id, login, password, email, first_name, last_name, birthday, id_role) values (null, ?, ?, ?, ?, ?, ?, ?)
dima
dima

公共(public)类用户{ 私有(private)长ID; ... 公共(public)字符串 getFirstName() { 返回名字; }

....

public String getPassword() {
    return password;
}

public void setBirthday(Date arg0) {
    birthday = arg0;
}

public void setFirstName(String arg0) {
    firstName = arg0;
}

... } 角色相似

最佳答案

“hibernate.hbm2ddl.auto”创建时出现问题

每次启动应用程序时都会创建新的数据库。 必须是“更新”而不是“创建”

关于java - 为什么hibernate不将更改保存到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26104797/

相关文章:

java - 在生产环境中加载 index.jsp 时出错,但在开发环境中不会

sql - 如何在H2数据库中插入具有两层深度嵌套的引号的字符串?

java - Q : In the context provided, 形参和对象是否被视为局部变量?

java - Java 中的快速傅里叶变换

mysql - 使用 maria DB、JPA 和 Spring Boot 1.5.4 基于架构的 Multi-Tenancy

java - 非法参数异常 : expecting IdClass mapping

java - Lob 使用 Play Framework 和 Ebean 和 H2 返回 null

java - 不需要的 JDBC 消息会忽略 log4j 配置

java - 无法使用 Joda 时间将 DateTime 转换为 ReadableInstant

java - 如果没有语法文件,我需要做什么才能在 Antlr 中以编程方式实现语法、解析器和词法分析器?