有必要通过使用Hibernate从表中获取数据来填充ObservableList

xdyibdwo  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(147)

需要使用Hibernate从表中获取数据来填充ObservableList,它原来是空的,表正在工作,它原来是空的,表工作,会话打开
主类

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

}
文件hibernate.cfg.xml Hibernate配置类

<?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 class="org.example.test_hibernate_connect_bd.Task"/>
    <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>

文件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>

类任务对象本身

记录当前启动

сент. 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

项目结构

enyaitl3

enyaitl31#

我首先填充列表,因为ObservableList类继承自扩展列表,然后它获得相同的addAll(...)方法:研究方法。我填写了我从表中得到的ObservableList列表。
主类

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->在这个类中,我创建了一个配置并向其中添加了一个带有JPA配置的类

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

}

类任务在这个类中,我将JPA注解@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 +
                '}';
    }

}

我想看到的结果是列表不是空的

окт. 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

相关问题