solovladys
@solovladys
Люблю программировать

Почему не записываются данные в таблицу средствами Hibernate?

Не могу понять-почему при использовании метода save текущей сессии не записываются данные в бд?
Где я мог ошибиться?

таблица:
5ba38a4ea473b447273950.png

точка старта:

public class ClassForTesting {

    public static void main(String[] args) {
        DepartmentDAO dao = new DepartmentDAO();
        Department department1=new Department("DepartmentName1");
        Department department2=new Department("DepartmentName2");

        dao.persist(department1);
        dao.persist(department2);

        department1.setName("changedDapertmentName1");
        dao.update(department1);


    }
}


дао:

public class DepartmentDAO implements ModelDAO<Department, Integer> {
    private Session currentSession;
    private Transaction currentTransaction;

    public DepartmentDAO() {
    }

    public Session openCurrentSession() {
        currentSession = getSessionFactory().openSession();
        return currentSession;
    }

    public Session openCurrentSessionWithTransaction() {
        currentSession = getSessionFactory().openSession();
        currentTransaction = currentSession.getTransaction();
        return currentSession;
    }

    private static SessionFactory getSessionFactory() {
        Configuration configuration = new Configuration().configure();
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
        return sessionFactory;
    }

    public void closeCurrentSession() {
        currentSession.close();
    }

    public void closeCurrentSessionwithTransaction() {
        currentTransaction.commit();
        currentSession.close();
    }

    public Session getCurrentSession() {
        return currentSession;
    }

    public void setCurrentSession(Session currentSession) {
        this.currentSession = currentSession;
    }

    public Transaction getCurrentTransaction() {
        return currentTransaction;
    }

    public void setCurrentTransaction(Transaction currentTransaction) {
        this.currentTransaction = currentTransaction;
    }

    public void persist(Department entity) {
        openCurrentSession();
        getCurrentSession().save(entity);
        closeCurrentSession();
    }


Сущность:
@Entity
public class Department {
    @Id 
     @GeneratedValue
    private Integer id;
    @Column(name="name")
    private String name;


hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/DepartmentsAndEmployees</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">dbpass12</property>
        <property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
        <!--<property name="hibernate.hbm2ddl.auto">update</property>-->

        <property name="show_sql">true</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="model.Employee"/>
        <mapping class="model.Department"/>
    </session-factory>
</hibernate-configuration>


Мой лог (в нем я не увидел ничего страшного):
[ INFO] Version(): 66 - HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
[ INFO] Version(logVersion): 54 - HHH000412: Hibernate Core {4.3.6.Final}
[ INFO] Environment():239 - HHH000206: hibernate.properties not found
[ INFO] Environment(buildBytecodeProvider):346 - HHH000021: Bytecode provider name : javassist
[ INFO] Configuration(configure):2073 - HHH000043: Configuring from resource: /hibernate.cfg.xml
[ INFO] Configuration(getConfigurationInputStream):2092 - HHH000040: Configuration resource: /hibernate.cfg.xml
[ INFO] Configuration(doConfigure):2214 - HHH000041: Configured SessionFactory: null
[ WARN] DriverManagerConnectionProviderImpl(configure): 93 - HHH000402: Using Hibernate built-in connection pool (not for production use!)
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):166 - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/DepartmentsAndEmployees]
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):175 - HHH000046: Connection properties: {user=root, password=****}
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):180 - HHH000006: Autocommit mode: false
[ INFO] DriverManagerConnectionProviderImpl(configure):102 - HHH000115: Hibernate connection pool size: 20 (min=1)
[ INFO] Dialect():145 - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
[ INFO] LobCreatorBuilder(useContextualLobCreation): 88 - HHH000422: Disabling contextual LOB creation as connection was null
[ INFO] TransactionFactoryInitiator(initiateService): 62 - HHH000399: Using default transaction strategy (direct JDBC transactions)
[ INFO] ASTQueryTranslatorFactory(): 47 - HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into Department (name) values (?)
Hibernate: select last_insert_id()
[ INFO] Configuration(configure):2073 - HHH000043: Configuring from resource: /hibernate.cfg.xml
[ INFO] Configuration(getConfigurationInputStream):2092 - HHH000040: Configuration resource: /hibernate.cfg.xml
[ INFO] Configuration(doConfigure):2214 - HHH000041: Configured SessionFactory: null
[ WARN] DriverManagerConnectionProviderImpl(configure): 93 - HHH000402: Using Hibernate built-in connection pool (not for production use!)
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):166 - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/DepartmentsAndEmployees]
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):175 - HHH000046: Connection properties: {user=root, password=****}
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):180 - HHH000006: Autocommit mode: false
[ INFO] DriverManagerConnectionProviderImpl(configure):102 - HHH000115: Hibernate connection pool size: 20 (min=1)
[ INFO] Dialect():145 - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
[ INFO] LobCreatorBuilder(useContextualLobCreation): 88 - HHH000422: Disabling contextual LOB creation as connection was null
[ INFO] TransactionFactoryInitiator(initiateService): 62 - HHH000399: Using default transaction strategy (direct JDBC transactions)
[ INFO] ASTQueryTranslatorFactory(): 47 - HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into Department (name) values (?)
Hibernate: select last_insert_id()
[ INFO] Configuration(configure):2073 - HHH000043: Configuring from resource: /hibernate.cfg.xml
[ INFO] Configuration(getConfigurationInputStream):2092 - HHH000040: Configuration resource: /hibernate.cfg.xml
[ INFO] Configuration(doConfigure):2214 - HHH000041: Configured SessionFactory: null
[ WARN] DriverManagerConnectionProviderImpl(configure): 93 - HHH000402: Using Hibernate built-in connection pool (not for production use!)
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):166 - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/DepartmentsAndEmployees]
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):175 - HHH000046: Connection properties: {user=root, password=****}
[ INFO] DriverManagerConnectionProviderImpl(buildCreator):180 - HHH000006: Autocommit mode: false
[ INFO] DriverManagerConnectionProviderImpl(configure):102 - HHH000115: Hibernate connection pool size: 20 (min=1)
[ INFO] Dialect():145 - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
[ INFO] LobCreatorBuilder(useContextualLobCreation): 88 - HHH000422: Disabling contextual LOB creation as connection was null
[ INFO] TransactionFactoryInitiator(initiateService): 62 - HHH000399: Using default transaction strategy (direct JDBC transactions)
[ INFO] ASTQueryTranslatorFactory(): 47 - HHH000397: Using ASTQueryTranslatorFactory
  • Вопрос задан
  • 325 просмотров
Решения вопроса 1
solovladys
@solovladys Автор вопроса
Люблю программировать
всё решилось тем, что добавил сессию и транзацию до и после начала крад-метода
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы