# JSF Postgresql DatabaseConnection



## Husamoli345 (24. Okt 2020)

Hallo zusammen vielleicht können sie mir weiterhelfen ich bin ein wenig am verzweifeln :/

Ich habe eine JSF Anwendung geschrieben die Bücher verwalten soll dies klappt auch ganz gut soweit nun möchte ich die Bücher aber aus einer Datenbank auslesen und Crud Funktionen mit ihnen erledingen.

[CODE lang="java" title="ConnectionBean"]package jsfbeans;

import java.sql.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class ConnectionBean {



        private final String url = "jdbcostgresql://localhost/postgres";
        private final String user ="postgres";
        private final String password ="admin";

        void connect() {
            try(Connection con = DriverManager.getConnection(url, user, password) {
                if(con != null) {
                    System.out.println("Verbunden");
                }else {
                    System.out.println("failed to connect");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        public static void main(String[] args) {
            ConnectionBean sqlConnect = new ConnectionBean();
            sqlConnect.connect();

        }

    }[/CODE]



Das klappt auch ganz gut soweit zumindestens die Console sagt das die Verbindung hergestellt wurde aber wie bekomme ich nun die Daten aus der Datenbank und wieder zurück?


Hier meine weiteren Klassen.

[CODE lang="java" title="Book"]
@ManagedBean
@RequestScoped

public class Book {

    private String author;

    private String name;

    private Date publishDate;

    private Double price;

    private String [] emailadresses;

    private String language = "de";

    private static LinkedHashMap<String, String> languages;

    static {
        languages = new LinkedHashMap<>();
        languages.put("Deutsch", "de");
        languages.put("Englisch", "en");
        languages.put("Italienisch","it");
        languages.put("Koreanisch", "kr");
    }

    private String specialmessage;

    public String getSpecialmessage() {
        return specialmessage;
    }

    public void setSpecialmessage(String specialmessage) {
        this.specialmessage = specialmessage;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public LinkedHashMap<String, String> getLanguages() {
        return languages;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(Date publishDate) {
        this.publishDate = publishDate;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String[] getEmailadresses() {
        return emailadresses;
    }

    public void setEmailadresses(String[] emailadresses) {
        this.emailadresses = emailadresses;
    }

    public String save () {

        return "create";
    }

    public void saveListener (ActionEvent e)
    {
        System.out.println("Abteilungen werden benachrichtigt: "+java.util.Arrays.toString(this.emailadresses));
    }

    public void emailAddressChanged (ValueChangeEvent e) {
        System.out.println("Adressen haben sich geändert "+java.util.Arrays.toString((String []) e.getNewValue()));
    }

    public void emailAddressChangedAjax (AjaxBehaviorEvent e) {

        if (emailadresses.length > 1)
            specialmessage = "Zu viele Abteilungen selektiert. Bitte die Emailflut eingrenzen.";
        else
            specialmessage = "";

    }
}
[/CODE]


[CODE lang="java" title="Bookshelf"]   
@SuppressWarnings("deprecation")
@ManagedBean
@SessionScoped

public class BookShelf implements Serializable{

           private static final long serialVersionUID = 1L;
           private static final ArrayList<Book> books;

           static{
               books = new ArrayList<Book>();
               Book book1 = new Book();
               book1.setAuthor("Johann Wolfgang von Goethe");
               book1.setName("Faust");
               book1.setLanguage("de");
               book1.setPublishDate(new Date(1829-1900,1,19));
               book1.setPrice(5.00);
               books.add(book1);

               Book book2 = new Book();
               book2.setAuthor("William Shakespeare");
               book2.setName("Romeo und Julia");
               book2.setLanguage("en");
               book2.setPublishDate(new Date(1597-1900,1,1));
               book2.setPrice(8.49);
               books.add(book2);

               Book book3 = new Book();
               book3.setAuthor("Stephen King");
               book3.setName("Es - It");
               book3.setLanguage("en");
               book3.setPublishDate(new Date(1986-1900,1,1));
               book3.setPrice(14.99);
               books.add(book3);
           };

           transient
           private DataModel<Book> booksDataModel;

           transient
           private ArrayList<Book> rawBooks;

           public DataModel<Book> getBooks() {
               if (booksDataModel == null) {
                   rawBooks = new ArrayList<Book>();
                   rawBooks.addAll(books);
                   booksDataModel = new ListDataModel<Book>(rawBooks);
               }

               return booksDataModel;
           }   

           private Book inedit;

           public String prepareNewBook() {
               inedit = new Book();
               return "create";
           }

           public String prepareBookEdit(Book book) {
               inedit = book;
               return "update";
           }

        public Book getInedit() {
            return inedit;
        }

        public void setInedit(Book inedit) {
            this.inedit = inedit;
        }

        public String saveBook () {
            if (!rawBooks.contains(inedit)) {
                rawBooks.add(inedit);
                booksDataModel = new ListDataModel<Book>(rawBooks);
            }

            inedit = null;

            return "index";

        }

        public String deleteBook (Book book) {

            rawBooks.remove(book);
            booksDataModel = new ListDataModel<Book>(rawBooks);

            return "delete";
        }


}[/CODE]


und meine xhtml dateien 

```
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:t="http://java.sun.com/jsf/facelets">

<t:composition template="/WEB-INF/templates/standardtemplate.xhtml" >

<t:define name="pagetitle">#{msg['index.title']}</t:define>
<t:define name="content">
<f:view>
<h:dataTable value="#{bookShelf.books}" var="onebook" styleClass="bookTable" headerClass="bookHeader" rowClasses="bookTableOddRow,bookTableEvenRow" >

<h:column>
<f:facet name="header">#{msg['index.no']}</f:facet>
#{bookShelf.books.rowIndex+1}
</h:column>

<h:column>
<f:facet name="header">#{msg['index.author']}</f:facet>
#{onebook.author}
</h:column>

<h:column>
<f:facet name="header">#{msg['index.name']}</f:facet>
#{onebook.name}
</h:column>

<h:column>
<f:facet name="header">#{msg['index.publishDate']}</f:facet>
#{onebook.publishDate}
</h:column>

<h:column>
<f:facet name="header">#{msg['index.language']}</f:facet>
#{onebook.language}
</h:column>

<h:column>
<f:facet name="header">#{msg['index.price']}</f:facet>
#{onebook.price}
</h:column>

<h:column>
<f:facet name="header">#{msg['index.actions']}</f:facet>

<h:form>
<h:commandButton value="Editieren" action="#{bookShelf.prepareBookEdit(onebook)}"/>
</h:form>

<h:form>
<h:commandButton value="Lösche" action="#{bookShelf.deleteBook(onebook)}"/>
</h:form>

</h:column>


</h:dataTable>

<h:form>
<h:commandButton value="Buch erfassen" action="#{bookShelf.prepareNewBook}"/>
</h:form>

</f:view>

</t:define>
</t:composition>

</html>
```


[CODE lang="xml" title="create.xhtml"]<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:t="http://java.sun.com/jsf/facelets">

<t:composition template="/WEB-INF/templates/standardtemplate.xhtml" >

<t:define name="pagetitle">#{msg['create.title']}</t:define>
<t:define name="content">
<f:view>
<h:form>
<hanelGrid columns="3">

<hutputText value="#{msg['create.author']}"/>
<h:inputText id="bookAuthor" value="#{bookShelf.inedit.author}" required="true" requiredMessage="Bitte Autor des Buches angeben!">
<f:validator validatorId="vornameNachnameValidator"/>
</h:inputText>
<h:message for="bookAuthor" styleClass="errorMessage"/>

<hutputText value="#{msg['create.name']}"/>
<h:inputText id="bookTitle" value="#{bookShelf.inedit.name}" validatorMessage="Der Titel des Buches muss mindestens 5 und maximal 50 Zeichen beinhalten.">
<f:validateLength minimum="5" maximum="50"/>

</h:inputText>
<h:message for="bookTitle" styleClass="errorMessage"/>

<hutputText value="#{msg['create.publishDate']}"/>
<h:inputText id="bookpublishDate" value="#{bookShelf.inedit.publishDate}">
<f:convertDateTime pattern="dd-MM-yyyy"/>
</h:inputText>
<h:message for="bookpublishDate" styleClass="errorMessage"/>

<hutputText value="#{msg['create.language']}"/>
<h:selectOneListbox id="bookLanguage" value="#{bookShelf.inedit.language}">
<f:selectItems value="#{book.languages}"></f:selectItems>
<f:valueChangeListener type="jsfbeans.LanguageValueChangeListener"></f:valueChangeListener>
</h:selectOneListbox>
<h:message for="bookLanguage" styleClass="errorMessage"/>

<hutputText value="#{msg['create.price']}"/>
<h:inputText id ="bookPrice" value="#{bookShelf.inedit.price}" converterMessage="Der Preis muss mit EUR 9,99 z.B. angegeben werden.">
<f:convertNumber type="currency" currencyCode="EUR"/>
</h:inputText>
<h:message for="bookPrice" styleClass="errorMessage"/>

<hutputText value="#{msg['create.departments']}"/>
<h:selectManyListbox id="bookEmailaddresses" value="#{bookShelf.inedit.emailadresses}" valueChangeListener="#{bookShelf.inedit.emailAddressChanged}">
  <f:selectItem itemValue="abteilung1@mycompany.de" itemLabel="Abteilung 1"/>
  <f:selectItem itemValue="abteilung2@mycompany.de" itemLabel="Abteilung 2"/>
  <f:ajax event="valueChange" listener="#{bookShelf.inedit.emailAddressChangedAjax}" render="sm"></f:ajax>
</h:selectManyListbox>
<h:message for="bookEmailaddresses" styleClass="errorMessage"/>

</hanelGrid>

<hutputText value="#{bookShelf.inedit.specialmessage}" id="sm"/> <br/>

<h:commandButton value="#{msg['create.save']}" action="#{bookShelf.saveBook}" />

</h:form>
</f:view>

</t:define>
</t:composition>
</html>[/CODE]



Ich hoffe ihr könnt mir weiterhelfen das wäre echt klasse....


----------



## mihe7 (25. Okt 2020)

Wenn Du uns noch die Umgebung mitteilst, in der die Anwendung läuft, wäre es einfacher


----------

