Quantcast
Channel: Форум программистов и сисадминов Киберфорум
Viewing all articles
Browse latest Browse all 514780

Простое Web приложение с использованием Hibernate + JSF - Java EE (J2EE)

$
0
0
Пытаюсь написать CRUD приложение примерно с таким(для начала) функционалом:
- Две статьи бюджета: Доходы, Расходы;
- Операции над ними: Создать, Найти, Изменить, Удалить, Вывести все.

Мне удалось написать консольное приложение с использованием Hibernate.
Ссылка на гитхаб: https://github.com/kurnakov92/Budget-Hibernate-JSF-

Что мы имеем:

1) Слой DAO:

Интерфейс IncomeDao:
:

package training.budget.dao;

import training.budget.model.Income;

import java.util.List;

public interface IncomeDao {

    public Income addIncome(String name, double amount);

    public void updateIncome(int id, String name, double amount);

    public void removeIncome(int id);

    public Income getIncomeById(int id);

    public List<Income> listIncomes();

}

Реализация интерфейса IncomeDaoImpl:
:

package training.budget.dao;

import org.hibernate.Transaction;
import training.budget.model.Income;

import java.util.List;

import org.hibernate.Session;


public class IncomeDaoImpl implements IncomeDao {

    Session session;

    public IncomeDaoImpl() {
        session = HibernateSessionFactory.getSessionFactory().openSession();
    }

    public Income addIncome(String name, double amount) {

        Transaction transaction = null;

        transaction = session.beginTransaction();
        Income income = new Income(name, amount);

        session.save(income);
        transaction.commit();

        return income;
    }

    public void updateIncome(int incomeId, String incomeName, double incomeAmount) {

        Transaction transaction = null;

        transaction = session.beginTransaction();
        Income income = (Income) session.get(Income.class, incomeId);
        income.setName(incomeName);
        income.setAmount(incomeAmount);
        session.update(income);
        transaction.commit();

    }

    public void removeIncome(int incomeId) {
        Transaction transaction = null;

        transaction = session.beginTransaction();
        Income income = (Income) session.get(Income.class, incomeId);
        session.delete(income);
        transaction.commit();
    }

    public Income getIncomeById(int incomeId) {
        Transaction transaction = null;

        transaction = session.beginTransaction();
        Income income = (Income) session.get(Income.class, incomeId);
        transaction.commit();

        return income;
    }

    public List<Income> listIncomes() {
        Transaction transaction = null;
        transaction = session.beginTransaction();

        List incomes = session.createQuery("FROM Income ").list();

        return incomes;
    }

    public void closeSession() {
        session.close();
    }
}

Класс HibernateSessionFactory (честно скопированный на каком-то ресурсе):
:

package training.budget.dao;



import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateSessionFactory {

    private static SessionFactory sessionFactory = buildSessionFactory();

    protected static SessionFactory buildSessionFactory() {
        // A SessionFactory is set up once for an application!
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
        }
        catch (Exception e) {
            // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
            // so destroy it manually.
            StandardServiceRegistryBuilder.destroy( registry );

            throw new ExceptionInInitializerError("Initial SessionFactory failed" + e);
        }
        return sessionFactory;
    }


    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}

2) Модель:
Класс Income(статья дохода):
:

package training.budget.model;

import javax.persistence.*;
/**
 * Аннотация @Entity используется для того, чтобы сообщить Hibernate, что класс взаимодействует с Hibernate.
 * Аннотация @Table - аннотация, используемая для явного указания названия таблицы.
 */
@Entity
@Table(name = "incomes")
public class Income {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
    @Column(name = "name")
    private String name;
    @Column(name = "amount")
    private double amount;

    /**
    * Construcors
    */
    public Income() {
    }

    public Income(String name, double amount) {
        this.name = name;
        this.amount = amount;
    }

    /**
    * Getters and Setters
    */
    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "Income{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", amount=" + amount +
                '}';
    }
}

3)Консольный Runner для проверки работоспособности приложения:
:

package training.budget.consoleRunners;


import training.budget.dao.IncomeDaoImpl;
import training.budget.model.Income;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

public class IncomeRunner {

    public static void main(String[] args) {
        String userInput = ""; // Line read from standard in
        InputStreamReader converter = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(converter);

        IncomeDaoImpl incomeDaoImpl = new IncomeDaoImpl();

        try {
            while (!"0".equals(userInput)) {
                System.out.println("1. Добавить доход");
                System.out.println("2. Найти доход");
                System.out.println("3. Редактировать доход");
                System.out.println("4. Удалить доход");
                System.out.println("5. Вывести все записи");
                System.out.println("0. Выход");

                userInput = in.readLine();

                if ("1".equals(userInput)) {
                    try {
                        String incomeName = "";
                        double incomeAmount = 0;
                        System.out.print(" Введите название дохода: ");
                        incomeName = in.readLine();
                        System.out.print(" Введите сумму дохода: ");
                        incomeAmount = Double.parseDouble(in.readLine());

                        Income income = incomeDaoImpl.addIncome(incomeName, incomeAmount);
                        System.out.println("Доход создан. Название: "
                                + income.getName() + " сумма: " + income.getAmount());
                    } catch (Exception e) {
                        System.out.println("FAIL");
                    }
                } else if ("2".equals(userInput)) {
                    try {
                        int incomeId = 0;
                        System.out.print(" Введите ID дохода: ");
                        incomeId = Integer.parseInt(in.readLine());
                        Income income = incomeDaoImpl.getIncomeById(incomeId);
                        System.out.println("Статья дохода получена из базы данных. Название: "
                                + income.getName() + " сумма: " + income.getAmount());
                    } catch (Exception e) {
                        System.out.println("FAIL");
                    }
                } else if ("3".equals(userInput)) {
                    try {
                        int incomeId = 0;
                        String incomeName = "";
                        double incomeAmount = 0;
                        System.out.print(" Введите ID дохода: ");
                        incomeId = Integer.parseInt(in.readLine());
                        Income income = incomeDaoImpl.getIncomeById(incomeId);
                        System.out.print(" Введите название дохода: ");
                        incomeName = in.readLine();
                        System.out.print(" Введите сумму дохода: ");
                        incomeAmount = Double.parseDouble(in.readLine());
                        incomeDaoImpl.updateIncome(income.getId(), incomeName, incomeAmount);
                    } catch (Exception e){
                        System.out.println("FAIL");
                    }
                } else if ("4".equals(userInput)) {
                    try {
                        int incomeId = 0;
                        System.out.print(" Введите ID дохода: ");
                        incomeId = Integer.parseInt(in.readLine());
                        incomeDaoImpl.removeIncome(incomeId);
                        System.out.println("Статья дохода с ID =  " + incomeId + " удаленa из базы данных.");
                    } catch (Exception e) {
                        System.out.println("FAIL");
                    }
                } else if ("5".equals(userInput)){
                    try {
                        System.out.println("==========ДОХОДЫ=========");
                        List<Income> incomes = incomeDaoImpl.listIncomes();
                        for (Income income : incomes) {
                            System.out.println(income);
                            System.out.println("\n================\n");
                        }
                    } catch (Exception e){
                        System.out.println("FAIL");
                    }
                }
            }
            incomeDaoImpl.closeSession();
        } catch (Exception ex) {
            System.out.println("FAIL");
        }

    }

}

Теперь нужно сделать слой View. Я хочу сделать это с использованием JSF(насколько я знаю это самая свежая технология на данный момент). Вывести какой-то определенный текст на JSF-страницу мне удавалось, но вопрос в том как сделать так, чтобы на странице был доступ к базе данных? Как я понимаю, нужно написать контроллер, который поможет связать представление со слоем дао. Есть пример (который по сути отражает весь нужный мне функционал) https://www.youtube.com/watch?v=e7swABdqOS4&t=4s, в котором помимо контроллера есть еще слой сервиса(вот здесь мой мозг был взорван), но в нем не объясняется как именно реализуются эти слои, иными словами я не могу понять что там происходит.
Надеюсь на Вашу помощь, ув. форумчане!

Viewing all articles
Browse latest Browse all 514780

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>