Home > Enterprise >  It is necessary to fill the ObservableList by taking data from the table using hibernate
It is necessary to fill the ObservableList by taking data from the table using hibernate

Time:10-03

It is necessary to fill the ObservableList by taking data from the table using hibernate, it turns out to be empty, the table is working, it turns out to be empty, the table works, session open

class Main

public class Main {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;


public static void main(String[] args) {
    findAll();
}

@SuppressWarnings({"unchecked", "deprecation"})
public static ObservableList<Task> findAll() {
    ObservableList<Task> observableTasks = FXCollections.observableArrayList();

    Session session = getSessionFactory().openSession();

    observableTasks.addAll(session.createCriteria(Task.class).list());
    System.out.println("observableTasks = "   observableTasks.isEmpty()); // true empty
    session.close();
    return observableTasks;
}

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

}

file hibernate.cfg.xml hibernate configuration class

 <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!--    <property name="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db-->
    <property name="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db</property>
    <property name="connection.driver_class">org.sqlite.JDBC</property>
    <property name="hibernate.show_sql">true</property>
    <property name="dialect">org.example.hibernate.dialect.SQLiteDialect</property>
    <property name="hibernate.connection.autocommit">true</property>

    <mapping />
    <mapping resource="TodoTask.hbm.xml"/>
    <!-- <property name="connection.username"/> -->
    <!-- <property name="connection.password"/> -->

    <!-- DB schema will be updated if needed -->
    <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
  </session-factory>
</hibernate-configuration>

file TodoTask.hbm.xml

    <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="org.example.test_hibernate_connect_bd.Task" table="todo" schema="main">
        <id name="id">
            <column name="id" sql-type="integer"/>
        </id>
        <property name="task">
            <column name="task" sql-type="text"/>
        </property>
        <property name="time">
            <column name="task_create_time" sql-type="text"/>
        </property>
        <property name="status">
            <column name="status" sql-type="text" not-null="true"/>
        </property>
    </class>
</hibernate-mapping>

class Task the object itself

enter image description here

logs current launch

    сент. 30, 2022 8:40:14 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
сент. 30, 2022 8:40:15 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db]
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
сент. 30, 2022 8:40:15 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.example.hibernate.dialect.SQLiteDialect
сент. 30, 2022 8:40:16 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
сент. 30, 2022 8:40:16 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
observableTasks = true

project structure

enter image description here

CodePudding user response:

I fill in the list first, because the ObservableList class inherits from extends List , then it gets the same addAll(....) methods. I fill in my ObservableList , list , which I got from the table.

class Main

package org.example;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.example.objects.Task;
import org.example.utils.HibernateSessionFactoryUtil;

import java.util.ArrayList;
import java.util.List;



    public class Main {
        
        public static ObservableList<Task> personList = FXCollections.observableArrayList();
        public static List<Task> ist = new ArrayList<>();
        
        
        public static void main(String[] args) {
            findAll();
        }
        
        @SuppressWarnings({"unchecked", "deprecation"})
        public static ObservableList<Task> findAll() {
               ist =  HibernateSessionFactoryUtil.getSessionFactory().openSession().createQuery("From Task").list();
               personList.addAll(ist);
            System.out.println("personList.isEmpty() = "   personList.isEmpty());
            return personList;
        }
    
    
    }

class HibernateSessionFactoryUtil -> In this class, I create a configuration and add a class to it, with a JPA configuration

 package org.example.utils;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;


public class HibernateSessionFactoryUtil {

    private static SessionFactory sessionFactory;

    private static ServiceRegistry serviceRegistry;

    public HibernateSessionFactoryUtil() {
    }

    public static SessionFactory getSessionFactory(){
        if(sessionFactory == null){
            try{
                Configuration configuration = new Configuration().configure();
                // here necessary class add
                configuration.addAnnotatedClass(org.example.objects.Task.class);
                StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
                sessionFactory = configuration.buildSessionFactory(builder.build());
            } catch (Exception e) {
                System.out.println("Exception !"   e);
            }
        }
        return sessionFactory;
    }


}

class Task In this class I put JPA annotations @Entity, @Id, @Column

    package org.example.objects;

import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;

import javax.persistence.*;


@Entity
@Table(name = "todo", schema = "main", catalog = "")
public class Task {

    private SimpleIntegerProperty id = new SimpleIntegerProperty();
    private SimpleStringProperty task = new SimpleStringProperty("");
    private SimpleStringProperty time = new SimpleStringProperty("");
    private SimpleStringProperty status = new SimpleStringProperty("");

    public Task() {
    }

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    @Column(name = "id", nullable = false)
    public int getId() {
        return id.get();
    }

    public SimpleIntegerProperty idProperty() {
        return id;
    }

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

    @Basic
    @Column(name = "task", nullable = false, length = -1)
    public String getTask() {
        return task.get();
    }

    public SimpleStringProperty taskProperty() {
        return task;
    }

    public void setTask(String task) {
        this.task.set(task);
    }

    @Basic
    @Column(name = "task_create_time", nullable = false, length = -1)
    public String getTime() {
        return time.get();
    }

    public SimpleStringProperty timeProperty() {
        return time;
    }

    public void setTime(String time) {
        this.time.set(time);
    }

    @Basic
    @Column(name = "status", nullable = true, length = -1)
    public String getStatus() {
        return status.get();
    }

    public SimpleStringProperty statusProperty() {
        return status;
    }

    public void setStatus(String status) {
        this.status.set(status);
    }

    @Override
    public String toString() {
        return "Task{"  
                "id="   id  
                ", task="   task  
                ", time="   time  
                ", status="   status  
                '}';
    }

}

the result I wanted to see is that the list is not empty

    окт. 01, 2022 8:33:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
окт. 01, 2022 8:33:54 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TestHibernate/db/todolist.db]
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
окт. 01, 2022 8:33:55 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.example.hibernate.dialect.SQLiteDialect
окт. 01, 2022 8:33:55 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
****Hibernate:
 select task0_.id as id1_0_, task0_.status as status2_0_, task0_.task as task3_0_, task0_.task_create_time as task_cre4_0_ from todo task0_
personList.isEmpty() = false**** <----- here result
  • Related