📜 ⬆️ ⬇️

Web development based on Java EE + JSP + Hibernate + Maven + Spring MVC in NetBeans. Part 1

Introduction


This will be a series of articles that will help beginner Java developers in their difficult path. I will show an example of creating an online store.
The first thing you need is NetBeans 7.3. Download here .
Why precisely he? I think for beginners in EE - this is ideal.

Used technologies:

1) NetBeans 7.3;
2) Maven;
3) Hibernate;
4) Spring MVC;
5) JSP + JSTL;
6) Knowledge about Servlets, Sessions, JavaBean, XML, etc .;
7) HTML + CSS (a bit of beauty according to your taste, but it is better to pay the left people - you and the server side will have enough trouble);
8) Java SE (knowledge of collections, ability to handle exceptions ... In general, the standard set);
9) Knowledge of design patterns (DAO, Factory);
10) JPA;
11) SVN;
12) SQL (for writing scripts that fill our databases).

Let's start with where we store our code and how to share it with friends. I think not all beginners know about repositories, and this part is for them.
')

Svn


There is such a thing as a repository - a remote code storage server.
If you are given a test task, and you send it as an archive, you will probably also be sent. Maybe they will not, but they will definitely be disappointed in you.
There are various CVS, SVN, Git repositories. For starters, I think the best SVN. Well, the main thing for you is not to know what it is, but to be able to apply. As long as this is enough, the rest will come with experience.

So, there is a website www.assembla.com/ - You need to register there. After registration, you need to create an open repository on this site on the start page. After registration will be . Create your own space.

Next is a public project, and the first will be Subversion (SVN). Give it a name and finish the creation. After that, at the top, on the black bar of the site, his name will be displayed, you click on it - and you will be redirected to the page of your space. There will be a tab "Source Code / SVN". In this tab there will be a link to your project. If all else fails, try finding a video on how to do this on www.youtube.com/ .

After all this you will have a link to your space. To understand what it is, you need to take one of your projects (or create some kind of empty project in NetBeans). Click on it with the right button and you will have access to the “Version Management” -> “import into the Subversion repository” menu. After that there will be a dialog box, which will be the path to the repository - this is the link that you received on the site in the “Source Code” tab.

Next, completely delete the project that you commit. Then go to the folder where your projects are stored, and check that everything is really deleted. Then you go back to NetBeans and look for the Group tab in the menu bar (in the panel where File, View, Edit, Transition, Source ...) it has our Subversion. And in the submenu there is “Get”. Further in the dialog boxes you will need to specify a link to the repository (this is the link you received on the site in the Source tab.) And when he offers to download folders, you will need to find your project and select it in the repository tree, and at the end you will Download your project. This is how the code is exchanged.
Your project will be constantly synchronized with the repository and mark files that have been changed, or new ones (something different from the version on the repository). To update, you need to call the context menu, and in the "Version Management" tab there will be a large list of what you can do with the project. “Update” is to update your files; "Fix" - put the code that you wrote or changed in the repository; “Reset” - return to the version on the repository, and “Compare” - display of changes to rows that are different from the deleted ones. This is a command exchange method that is always used and you need to get used to it.

Start


So, if we need to share the code with someone, show it to someone, we are now armed with a pretty tool for that.

You have already downloaded NetBeans, played with SVN - now let's get down to business. Create a project. Click "Create a project", there choose Maven-> Web application. Call it what you want, it's all your imagination. So, we have a web application, the assembly of our project is going to be maven, we have a goal, and now it's time to think about how to implement it. That is, you, as a developer, should think about how your application will look like, which architecture to have, the package tree, and so on. The total number of lines of code here is about 4000 and it is better to take care of the beautiful architecture in advance, otherwise then you just won’t understand where and how it works for you, what a miracle you, for example, display the last purchased thing, what do you think the total amount of purchases. And if you are then asked to finish or add something - you realize that it is easier to write everything from scratch.

And of course we need to estimate our plan of action.

So: Action Plan

1) we describe entity (entities) - entities. This POJO is a class associated with a database using annotation (@Entity) or via XML. We will use JPA, so we need to import javax.persistence. * Why not the Hibernate Persistence API, because if you use it and then we want to change the ORM library, you will have to rewrite our classes, and JPA is the standard from Sun. Regarding what JPA is, well, for you I can say this in my own words: this is a library providing an API for working with * long-living * objects, that is, it allows us to conveniently store our objects in the database. I can give advice: create a separate package for this, name it entity or domain - whatever you like, the main thing is that you understand. In the end, it might look like this: edu.shop.model.domain.Customer.java edu.shop.model.domain.Notebook.java.
I will describe in more detail when considering this item. Now the task is to figure out a plan of action.

2) Create HibernateUtil (in general, the suffix or prefix Util implies that the code in this class is universal and is used by many classes).
So, in HibernateUtil we place SessionFactory. He is heavyweight. This code, in theory, should be independent of the entire application, since it establishes a connection to the database at startup and should give us only Sessions with the database. We also register our entity classes in this class. I will tell you more about this class later. We will also post it in a separate package, for example, edu.shop.model.hbutil.HibernateUtil.java

3) We write DAO.
What to write in it? We write what we want to get from the database, but we do not need to think about how this data came out, the result is important. For example, we define the ProductDAO interface and write methods in it.
List <AnyEntity <>> getAllProducts (); then we write its implementation ProductDAOImpl.

What is the idea? If this application was written by me and you, you would say: “Micha, I need the following data from the database: all the goods that I have in the database”. I answer: "no question." And then the following development: in your code, wherever you need to make requests to the database, write the following%

* here is the call to the method * .getAllProducts (); - and you see that the compiler does not swear, and the implementation of this interface, I could not have time to write. And what is the result? You have compiled everything, but there is not even a working code. Here we will apply Enums and the Factory pattern, and one more thing, but there is a time for everything. It is in the DAO that particular attention should be paid to exception handling, at least to generate pages with errors. So that you quickly find a piece of broken code. Otherwise, you simply torture with debugging.

3) This is where our work with Spring MVC will begin. This is a long story and a separate article will be devoted to this. Immediately I say - this is the most difficult thing in this application. But I will show you a simpler version of how to display everything without worrying about the MVC pattern.
We will affect the use of scripts.

4) Here we will have auxiliary classes that add all sorts of goodies to our project: counting the total amount of purchases; Last purchased item; auxiliary variables that will be useful to us for the work of the method, which, for example, will bring us from the database things no more than 5000 UAH, or not less than 500; output of all Asus brand laptops. This item is closely interrelated with the previous one.

For now let's stop on this. We will deal with the rest a bit later. So, we have a plan, let's proceed to its implementation.

Entity


We created our project and created our package with entities. Let it be edu.shop.entity. There we create such classes:

Note. The basket in which our purchased goods will be stored will be like a table in the database, I did this because I will show some basics of working with the database on it. For a real case, it would be better to use collections for the storage of our goods.

1) Product
2) Notebook
3) Camera
4) Book
5) Cable
6) Customer
7) Cart

Let's talk a little about what is the essence of the class.
Entity (Entity) - POJO class associated with a database using annotation (@Entity) or via XML. This class has the following requirements:

- Must have an empty constructor (public or protected);
- Cannot be nested, interface or enum;
- Cannot be final and cannot contain final-fields / properties;
- Must contain at least one @ Id-field.

In this case, an entity can:

- Contain non-empty constructors;
- Inherit and be inherited;
- Contain other methods and implement interfaces.

Entities can be related to each other: one-to-one, one-to-many, many-to-one, and many-to-many.

We will use annotations. And here at once we have the opportunity to describe in two ways. Either we will write annotations directly above the fields, or above the getters. I will say one thing: write correctly over getters, and you ask the reason in Google. I can not absolutely describe all the topics here.

There is one more thing I want to say. To do this, you have to show 2 examples of the description of the class of the entity So, the first example:
I wrote comments to it in the code itself:

import java.io.Serializable; import javax.persistence.*; import javax.validation.constraints.Size; /** * * @author Mikhail Shumenko */ @Entity //   ,     . @Table(name = "CART")//    ,           CART // ,    ,     ,       //    public class CartEntity implements Serializable { //     .     // Id  @Id //,            Id //     ,        . @Column(name = "ID") //   ))     ?     //@GeneratedValue(strategy=GenerationType. TABLE  AUTO)  //   , Id    1    . //   20   ,    1  20. //   , id       - 345768. //   ,    id          . //  SEQUENCE,      Derby,       . // ,  .      @TableGenerator(name = "cartid", table = "cartpktb", pkColumnName = "idCart", pkColumnValue = "idCartValue",allocationSize = 1) @GeneratedValue (strategy = GenerationType.TABLE, generator = "cartid") private Integer id; //  .    25 . @Size(max = 25) @Column(name = "NAMEITEM") //    String,        VARCHAR(  Derby) // Integer,   ,      Integer //boolean  Derby -     SMALLINT private String nameItem; @Column(name = "PRICE") private Integer price; public CartEntity() { } public CartEntity( String nameItem, int price) { this.nameItem = nameItem; this.price = price; } public CartEntity(Integer id,String nameItem, int price) { this.id=id; this.nameItem = nameItem; this.price = price; } public CartEntity(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNameItem() { return nameItem; } public void setNameItem(String nameItem) { this.nameItem = nameItem; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } } 


The second way: we write over getters. Explanations look in the code.


 import java.io.Serializable; import javax.persistence.*; /** * * @author miha */ @Entity //,     @Table //Hibernate    . public class Product implements Serializable { private Integer id; private String nameProduct; private Integer availableProduct; @Id @GeneratedValue(strategy = GenerationType.AUTO) //  Id  , ,         . public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNameProduct() { return nameProduct; } public void setNameProduct(String nameProduct) { this.nameProduct = nameProduct; } public Integer getAvailableProduct() { return availableProduct; } public void setAvailableProduct(Integer availableProduct) { this.availableProduct = availableProduct; } } 


So, you have two examples of entity classes. Create the rest using these examples. Such fields as: model, year of publication, name, value - all to your imagination. Include required field Available (in the translation availability). It will come in handy later. You can make it boolean and add a column named quantity. All this is useful to us.

Now we give an example of our HibernateUtil


 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.shumenko.hibernate; import edu.shumenko.entity.BookEntity; import edu.shumenko.entity.CableEntity; import edu.shumenko.entity.CameraEntity; import edu.shumenko.entity.CartEntity; import edu.shumenko.entity.CustomerEntity; import edu.shumenko.entity.NotebookEntity; import edu.shumenko.entity.ProductEntity; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.SessionFactory; /** * Hibernate Utility class with a convenient method to get Session Factory * object. * * @author Mikhail Shumenko */ public class HibernateUtil { //  SessionFactory. private static final SessionFactory sessionFactory; static { try { //   AnnotationConfiguration AnnotationConfiguration ac = new AnnotationConfiguration(); //    ,       . //  Entity   ,   -   . ac.addAnnotatedClass(ProductEntity.class).addAnnotatedClass(BookEntity.class).addAnnotatedClass(CableEntity.class) .addAnnotatedClass(CameraEntity.class).addAnnotatedClass(NotebookEntity.class). addAnnotatedClass(CartEntity.class).addAnnotatedClass(CustomerEntity.class); //       . //  .       //   ,  ,        . sessionFactory = ac.configure().buildSessionFactory(); } catch (Throwable ex) { // Log the exception. System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } 


DAO


We proceed to the next part. What is DAO. This is a design pattern.

Its meaning is:
- All access to the database in the system is done through DAO for encapsulation.
- Each DAO instance is responsible for one primary domain object or entity. If a domain object has an independent life cycle, it must have its own DAO.
- DAO is responsible for creating, reading (by primary key), updating and deleting (that is, CRUD (create, read, update, delete)) domain object.
- The DAO may allow queries based on criteria other than the primary key. I refer to such methods as finder or finders. The finder method usually returns a collection of domain objects for which the DAO is responsible.
- DAO does not handle transactions, sessions or connections. This is done outside of DAO for flexibility.
More details always tell Google.

We will write DAO for our products for now.
So, think about what we need. The Product table will have 4 fields Id, nameProduct, available + amount + actionForServlet. We will need it to create categories on our site. Over the last field do not bother. The only thing we need is a list of products.

We write the interface
 public interface ProductDAO { ProductDAO INSTANCE_PRODUCT= new ProductDAOImpl(); List<Product> getProducts(); //       } 


The implementation of our interface. Explanations look in the code
 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.shop.model.dao; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; /** * * @author Mikhail Shumenko */ public class ProductDAOImpl implements ProductDAO { @Override public List<Product> getProducts() { List<Product> result = null; // ,      // ,  -    ,     ,    . Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction().begin(); //Criteria          // , ,    //    -,  .       Cart   //   Cart.class Criteria criteria = session.createCriteria(Product.class); result = (List<Product>) criteria.list(); session.getTransaction().commit } catch (Exception e) { //   .        . e.printStackTrace(); }finally { if (session != null) session.close(); } return result; } } 


So, now we have the opportunity to receive data from the database. You can use scripts to create a simple for-each loop and bring your products to your index.jsp page.

 <table border="2" width="2" cellspacing="2" cellpadding="2"> <thead> <h3></h3> </thead> <tbody> <tr> <th></th> //INSTANCE_PRODUCT    ? // ProductDAO   ,    ProductDAOImpl //     -,     . //ProductDAO INSTANCE_PRODUCT= new ProductDAOImpl(); <% for (Product product :ProductDAO.INSTANCE_PRODUCT.getProducts()) {%> <td><a href="<%=product.getActionForServlet()%>"><%=product.getName()%></a></td> <%}%> </tr> <tr> <th></th> <% for (Product product : ProductDAO.INSTANCE_PRODUCT.getProducts()) {%> <td><%=product.getAvailable()%></td> <%}%> </tr> </tbody> </table> 


But this is for the first time, but in general it is bad to do so. This breaks our MVC pattern. How to do it correctly, I will explain in the next lesson, if they give me an invite. In the second lesson, we will deal with Spring, in the third we will touch the Factory pattern, and dive into the hibernate. For especially impatient, I will show you how to remove from the database, save to the database and delete everything from the database completely. Well, how to make it all interact as a whole with our application and leave a detailed review for later.

Save to DB


 public void addItemToCart(CartEntity cart) { Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction().begin(); session.save(cart); session.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } 


Remove from database by id


 public void deleteItemFromCart(Integer id) { Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction().begin(); CartEntity itemDelete = (CartEntity) session.get(CartEntity.class, id); session.delete(itemDelete); session.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } 


Deleting group id from database.


  public void deleteAllItemToCart(List<Integer> idAllItemsInCart) { Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction().begin(); for(Integer id:idAllItemsInCart){ CartEntity itemDelete = (CartEntity) session.get(CartEntity.class, id); session.delete(itemDelete); } session.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } 


You will also need a Hibernate configuration file. Create in DB Derby shop. The username and password of the root user and pass respectively. If it does not work out - do not be discouraged - I will spend more time on this.

 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property> <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property> <property name="hibernate.connection.url">jdbc:derby://localhost:1527/shop</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">pass</property> <property name="connection.characterEncoding">UTF-8</property> <property name="hibernate.hbm2ddl.auto">update</property> </session-factory> </hibernate-configuration> 


How to fill out our database talk later. You can fill them in manually. Or wait for the next lesson.

Source: https://habr.com/ru/post/178865/


All Articles