2014-07-17 101 views
1

我正在開發一個Java桌面應用程序,並對使用JavaFX非常感興趣。我打算使用MVC體系結構,因爲我有一些Java EE和MVC模型的經驗。JavaFX + Hibernate(JPA)持久性+ Derby DB

我想將數據存儲在嵌入式derby數據庫中,並使用Hibernate作爲持久層,但我找不到一篇關於使用hibernate和JavaFX實現MVC的優秀教程。

我已經創建了持久性文件,但我不確定如何使它與JavaFX一起工作。在Java EE中,我注入EJB服務或DAO,但由於我的應用程序沒有連接服務器,我認爲我不能這樣做。

有人可以解釋我如何實現這一目標嗎?可以一起使用它們嗎?

回答

3

在我最近的一個JavaFX項目中,我在服務層下創建了一個DataBroker類,它可以完成數據庫上的所有CRUD操作。

例子:

public class DataBroker { 

    private EntityManager em; 

    public DataBroker() { 
     init(); 
    } 

    private void init() { 
     this.em = Persistence.createEntityManagerFactory("<NAME_OF_YOUR_PU>").createEntityManager(); 
    } 

    public Person saveOrUpdate(Person entity) { 
     em.getTransaction().begin(); 
     T savedEntity = em.merge(entity); 
     em.getTransaction().commit(); 
     return savedEntity; 
    } 

    public List<Person> getAllPersons() { 
     TypedQuery<Person> query = em.createNamedQuery(Person.GET_ALL, Person.class); 
     return query.getResultList(); 
    } 

} 

如果你只需要一個DataBroker例如,你也許可以實現它作爲一個Singleton,如果需要實例池,創建池。這是應用服務器的優點,他爲你做這一切,你只需要註釋你的類或成員。

我希望這會幫助你。

編輯/ UPDATE 下面是2.1的EclipseLink工作的例子,但它僅是持久性提供程序,所以它的工作原理也與Hibernate。

我在上面的例子中創建了一個DataBroker,它實現了我的IDataBroker接口並覆蓋了方法。

IDataBroker

import de.professional_webworkx.crm.domain.Person; 
import java.util.List; 


public interface IDateBroker { 

    public abstract void saveOrUpdate(Person person); 
    public abstract List<Person> getAllPersons(); 
    public abstract Person getPersonById(int id); 
    public abstract Person getPersonByEmail(String email); 
} 

DataBroker - 不是每一個方法的實現......

import de.professional_webworkx.crm.domain.Person; 
import java.util.List; 
import javax.persistence.EntityManager; 
import javax.persistence.Persistence; 

/** 
* 
* @author Patrick Ott <[email protected]> 
* @version 1.0 
*/ 
public class DataBroker implements IDateBroker { 

    private EntityManager em; 

    public DataBroker() { 
     em = Persistence.createEntityManagerFactory("CRMPU").createEntityManager(); 
    } 



    @Override 
    public void saveOrUpdate(Person person) { 
     em.getTransaction().begin(); 
     em.merge(person); 
     em.getTransaction().commit(); 
    } 

    @Override 
    public List<Person> getAllPersons() { 
     throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 
    } 

    @Override 
    public Person getPersonById(int id) { 
     throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 
    } 

    @Override 
    public Person getPersonByEmail(String email) { 
     throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 
    } 


} 

IPersonService接口

import de.professional_webworkx.crm.domain.Person; 
import java.util.List; 


public interface IPersonService { 

    void saveOrUpdate(Person person); 
    List<Person> getAllPersons(); 
    Person getPersonById(int id); 
    Person getPersonByEmail(String email); 
} 

PersonService

import de.professional_webworkx.crm.databroker.DataBroker; 
import de.professional_webworkx.crm.databroker.IDateBroker; 
import de.professional_webworkx.crm.domain.Person; 
import java.util.List; 


public class PersonService implements IPersonService { 

    private IDateBroker broker; 

    public PersonService() { 
     broker = new DataBroker(); 
    } 

    @Override 
    public void saveOrUpdate(Person person) { 
     broker.saveOrUpdate(person); 
    } 

    @Override 
    public List<Person> getAllPersons() { 
     return broker.getAllPersons(); 
    } 

    @Override 
    public Person getPersonById(int id) { 
     return broker.getPersonById(id); 
    } 

    @Override 
    public Person getPersonByEmail(String email) { 
     return broker.getPersonByEmail(email); 
    } 
} 

在域類

import java.io.Serializable; 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.Table; 
import javax.validation.constraints.NotNull; 
import javax.validation.constraints.Size; 


@Entity 
@Table(name = "person") 
public class Person implements Serializable { 

    private long id; 
    private String firstName; 
    private String lastName; 
    private String eMail; 

    public Person() { 
    } 

    public Person(String firstName, String lastName, String eMail) { 
     this.firstName = firstName; 
     this.lastName = lastName; 
     this.eMail = eMail; 
    } 


    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    public long getId() { 
     return id; 
    } 


    public void setId(long id) { 
     this.id = id; 
    } 


    @Size(min = 2, max = 255, message = "Enter between 2 and 255 characters!") 
    @Column(name = "firstname") 
    @NotNull 
    public String getFirstName() { 
     return firstName; 
    } 


    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 


    @Column(name = "lastname") 
    @NotNull 
    public String getLastName() { 
     return lastName; 
    } 


    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 


    @NotNull 
    public String geteMail() { 
     return eMail; 
    } 


    public void seteMail(String eMail) { 
     this.eMail = eMail; 
    } 


} 

FXMLController

import de.professional_webworkx.crm.business.IPersonService; 
import de.professional_webworkx.crm.business.PersonService; 
import de.professional_webworkx.crm.domain.Person; 
import java.net.URL; 
import java.util.ResourceBundle; 
import javafx.event.ActionEvent; 
import javafx.fxml.FXML; 
import javafx.fxml.Initializable; 
import javafx.scene.control.Label; 

public class FXMLController implements Initializable { 

    private IPersonService service; 

    @FXML 
    private Label label; 

    @FXML 
    private void handleButtonAction(ActionEvent event) { 
     Person p = new Person("Demo", "User", "[email protected]"); 
     service.saveOrUpdate(p); 
    } 

    @Override 
    public void initialize(URL url, ResourceBundle rb) { 
     // get an instance of PersonService 
     service = new PersonService(); 

    }  
} 

最後但並非最不重要的MainApp啓動應用程序。

import javafx.application.Application; 
import static javafx.application.Application.launch; 
import javafx.fxml.FXMLLoader; 
import javafx.scene.Parent; 
import javafx.scene.Scene; 
import javafx.stage.Stage; 


public class MainApp extends Application { 

    @Override 
    public void start(Stage stage) throws Exception { 
     Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml")); 

     Scene scene = new Scene(root); 
     scene.getStylesheets().add("/styles/Styles.css"); 

     stage.setTitle("JavaFX and Maven"); 
     stage.setScene(scene); 
     stage.show(); 
    } 


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

} 

這是使用Netbeans 8創建的標準Maven JavaFX項目。如果有必要,我可以上傳源到GitHub或其他東西..

數據庫表將創建與第一次提交,因爲我設置在persistence.xml文件中,該模式生成,你可以從文件

<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> 
    <persistence-unit name="CRMPU" transaction-type="RESOURCE_LOCAL"> 
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> 
    <class>de.professional_webworkx.crm.domain.Person</class> 
    <properties> 
     <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/exampleDb?zeroDateTimeBehavior=convertToNull"/> 
     <property name="javax.persistence.jdbc.user" value="user"/> 
     <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> 
     <property name="javax.persistence.jdbc.password" value="pass"/> 
     <property name="javax.persistence.schema-generation.database.action" value="create"/> 
    </properties> 
    </persistence-unit> 
</persistence> 

所以我希望這會幫助你創建你的項目。

Patrick

+0

謝謝,但我已經有類似的東西。我需要關於如何在JavaFX控制器上使用它的幫助。你有一個示例項目或教程? –

+0

@XavierÑauñay我更新了我的答案,希望它會有所幫助! – Patrick

+1

謝謝你的這段代碼示例,這會幫助我很多。 你已經澄清了你的疑惑,現在是代碼:) –