Monday, 29.04.2024, 17:37
Welcome Guest | RSS

Tapestry learning

Site menu
Statistics

Connecting DataBase

Connecting Hibernate 
I will not describe here how to install MySQL. I assume that MySQL is already installed, and you can run the utility from the directory mysql bin. 
Start mysql, username and password: mysql-u name-p password 
In my case the username root, password is blank, so I run the program this way: mysql-u root 
Create a new database forum_db. We use a set of UTF-8: create database forum_db character set utf8; 
Do not forget to complete each command with a semicolon. 
Switch to create a database: use forum_db; 
Make sure your database is empty: show tables; 
Query Result: Empty set (0.00 sec) 
Now go to IDE and import the project dependencies, necessary for integration with Hibernate. Double-click the file pom.xml in the Package Explorer and Task to perform list, click Add/Modify/Remove Dependencies. In the Dependencies section, click the New button on the right. The window that appears fill in accordance with the pattern and click OK. Save the file pom.xml, pressing Ctrl + S. This will import the necessary libraries. If some of them are still missing in the local repository, they will be loaded from repository Maven, so that this process may take some time. 
Now, if you look in the node Tapestry Forum -> Java Resources -> Libraries -> Maven Classpath Container in Panel Project Explorer, you will see that there is essentially libraries added. We have a draft of a relationship, and the rest were imported automatically. 
Add another dependency - JDBC-driver for the database MySQL: 
Now, create an entity class (entity class), which will represent our application the user and all related information. We restrict ourselves until the following fields: 
- Nick 
- Login 
- Password. 
Other fields will add as needed. 
Package in which Tapestry will search for the essence of classes for Hibernate, predictably named entities and is located in the root package of the program, ie, in our case the full name of the package will TapestryForum.entities. Create it. To do this, right-click on the folder src / main / java in the Project Explorer, select New ... -> Package. 
In the window, enter the package name TapestryForum.entities: 
In the structure of packages folder src / main / java will be a new empty package. 
Now right-click on the created package and select New ... -> Class. In the resulting window, type the name of the class User. 
Click the Add button in front of the list of Interfaces. Enter the Serializable and select the Matching Items string Serializable - java.io. Click OK and Finish. 
A new empty class. Adding a private-field characterizing the properties of the object, ie user forum. Do not forget about the field-identifier id. 

private Long id; 
private String nickname; 
private String login; 
private String password; 

Eclipse highlight the names of fields wavy yellow lines. Pointing the mouse pointer on it, you can see why - these private-field is not used within a class, therefore, have no meaning. Now we fix it. Move the cursor over the password field and in the tooltip, click «Generate getter and setter for 'password'». In the resulting window you can change nothing and just click OK. For the password field will be generated accessor methods getPassword () and setPassword (). 
But this method is useful if you want to create accessors for a field, and if a lot of them? 
Select the menu item Source Generate getters and setters ... (while the cursor input must be within the class User, otherwise you will get an error message). In the window that appears, select the checkbox of the field id, login and nickName (or click Select All), then click OK.Missing accessors will be generated, and our class User becomes a real bin corresponding to all agreements. 
Now let us make of it entity-class. 
Check the class annotation @ Entity. Press the key combination Ctrl + Shift + O or go to the menu item Source Organize Imports. Most likely, you will be asked to choose one of the two annotations with the same name: 
Both of these annotations have the same function, and classes were marked by them, Hibernate can be recognized as an entity, but javax.persistence.Entity is part of the standard JPA and does not bind us to Hibernate, so that in all such cases it is better to use the annotations from the package javax.persistence. 
Now add to the class annotation @ Table. Import it. After the annotations put parenthesis and press Ctrl + Spacebar. Eclipse will tell you what options are available for annotation. In the drop-down list, select the option name. Enter a name = "forum_user". 
Thus, the User class declaration should look like this: 

@ Entity 
@ Table (name = "forum_user") 
public class User ( 

Table that will store data about users, we call forum_user, because the word user in most databases is a reserved keyword. 
So, we created a class User, and tied him to a table forum_user our future database. Now we associate the fields of class field in the table. 
Locate the code class User method getId (). Add the following annotation: 

@ Id 
@ GeneratedValue (strategy = GenerationType.AUTO) 
@ Column (name = "user_id", nullable = false) 

Abstract @ Id makes the property id identifier objects of class User, in other words, the primary key of the corresponding table. 
Abstract GeneratedValue said Hibernate, that the value of this field when saving a new object in the database should be generated. Option strategy = AUTO leaves the choice of method of generation for Hibernate, with particularly given the SQL dialect for a specific database. 
Abstract @ Column in correspondence with the property class User id field user_id table forum_user. Parameter nullable = false corresponds SQL-attribute NOT NULL, ie allows the insertion of records is permitted only with non-empty value for this field. 
Now, to supply each of the getters getNickName (), getLogin () and getPassword () @ Column annotation to the names of fields, respectively, nick_name, login and password. Make a field mandatory by setting nullable. Add to each of these annotations parameter length = 40, limiting the maximum size of the field. 
The last thing we should do with the class User - add the constructors. First, insert a blank default constructor and provide it with the annotation @ Inject: 

@ Inject 
public User () { 
}

Abstract @ Inject said Tapestry, which is the constructor used in the automatic creation of an object class. 
Now in the menu, select Source Generate Constructor using Fields ..., select all the fields in the list and click OK. 
As a result, the class User should look as follows: 

package TapestryForum.entities; 
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 org.apache.tapestry5.ioc.annotations.Inject; 

@ Entity 
@ Table (name = "forum_user") 
public class User implements Serializable { 

    
@ Inject 
    
public User () { 
    }

     
    
public User (Long id, String nickName, String login, String password) { 
        
super (); 
        
this.id = id; 
        
this.nickName = nickName; 
        
this.login = login; 
        
this.password = password; 
    


    
private Long id; 
    
private String nickName; 
    
private String login; 
    
private String password; 

    
@ Id 
    
@ GeneratedValue (strategy = GenerationType.AUTO) 
    
@ Column (name = "user_id", nullable = false) 
    
public Long getId () { 
        
return id; 
    


    
public void setId (Long id) ( 
        
this.id = id; 
    


    
@ Column (name = "nick_name", nullable = false, length = 40) 
    
public String getNickName () { 
        
return nickName; 
    


    
public void setNickName (String nickName) { 
        
this.nickName = nickName; 
    


    
@ Column (name = "login", nullable = false, length = 40) 
    
public String getLogin () { 
        
return login; 
    


    
public void setLogin (String login) { 
        
this.login = login; 
    


    
@ Column (name = "password", nullable = false, length = 40) 
    
public String getPassword () { 
        
return password; 
    


    
public void setPassword (String password) { 
        
this.password = password; 
    }



Now create a file hibernate.cfg.xml - the main configuration file Hibernate, Tapestry is used to automatically configure Hibernate. 
In Project Explorer, expand TapestryForum/src/main/resources. Right-click on the folder resources and select New -> File. 
In the resulting window, type hibernate.cfg.xml and click Finish. 
Enter into the new file the following lines: 

<! 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.connection.driver_class"> com.mysql.jdbc.Driver </ property> 
        
<property name="hibernate.connection.url"> jdbc: mysql: / / localhost / forum_db </ property> 
        
<property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </ property> 
        
<property name="hibernate.connection.username"> root </ property> 
        
<property name="hibernate.connection.password"> </ property> 
        
<property name="hbm2ddl.auto"> create </ property> 
        
<property name="hibernate.connection.charSet"> UTF-8 </ property> 
    
</ session-factory> 
</ hibernate-configuration> 

This - the main configuration file Hibernate, which is configured factory sessions (session factory). The first five lines of property - a setting used database: JDBC-driver class, URL for the connection, used a dialect of SQL, a user name and password. Perhaps the name and password you have to replace on their own. 
Parameter hbm2ddl.auto = create points Hibernate, that when you start the application must recreate the database schema in accordance with the mapping, in our case will be taken as a basis for entity-classes. After the first run we will change this value to update, otherwise all the tables with all data will be deleted and created again. 
Followed by setting ISP connections C3P0, which I shall not dwell in detail. The last line property specifies the encoding used when connecting to the database. This is the same UTF-8, which we pointed out when creating the database. 
Configuring Hibernate completed. However, Tapestry will not activate Hibernate until until we try to apply to the database. 
For simplicity, we start with the fact that inektiruem Hibernate session directly to the page class. For a real application would cost to introduce an additional level, for example, using a template DAO. Perhaps I will discuss this option later, but so far - this article, and so became rather large, and the results we've seen before. 
Create pages in the package a new class of Register and add a private-box User user, providing him with the annotation @ Property. Intravenous in class Index page and the session Hibernate (class org.hibernate.Session): 

package TapestryForum.pages; 

import TapestryForum.entities.User; 
import org.apache.tapestry5.annotations.InjectPage; 
import org.apache.tapestry5.ioc.annotations.Inject; 
import org.apache.tapestry5.annotations.Property; 
import org.hibernate.Session; 

public class Register { 

    
@ Property 
    
private User user; 
    
@ InjectPage 
    
private Index index; 
    
@ Inject 
    
private Session session; 
     


In the directory src / main / webapp, create a file Register.tml. This is page user's registration.Add the following code: 

<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd"> 
<head> 
<title> Registration </ title> 
</ Head> 
<body> 
        
<h1> New User Registration </ h1> 
        
<t:beaneditform t:id="user" t:submitLabel="Sohranit" exclude="id" /> 
    
</ Body> 
</ Html> 

BeanEditForm - a component for editing the bean, which automatically creates HTML-form with fields bound to the properties of the bean. 
Parameter t: id specifies the name of the bean class Register. In our case, this new object of class User. The same name will have the form, so the event handler will be called submit onSubmitFromUser. 
Parameter t: submitLabel - a label on the button submit the form. t: exclude specifies a list of properties (comma), which do not have to fill. In our case, this property is id, which will be automatically filled in Hibernate when creating a new record in the database. 
Now create a class method Register onSubmitFromUser, providing him with the annotation @ CommitAfter. This abstract interpretation Tapestry, that if successful, this method must produce a confirmation transaction. 

@ CommitAfter 
public Object onSubmitFromUser () { 
    
session.saveOrUpdate (user); 
    
return index; 
}

Method sessions saveOrUpdate stores the new object in the form of records in the database, or update an existing record with the ID equal user.id. Since the field of id of the object user, we did not fill in this case will create a new account. 
Please note that we can not initialize the field user class Register. Component BeanEditForm do everything for us. 
Now modify the code page Index. Add a reference to the registration page and change the mechanism of user authentication. 
Add a file Index.tml after closing form tag </ t: form> the following code: 

[<t:pagelink T:page="register"> Register </ t: pagelink>] 

This component PageLink, which is displayed on the page as a link to another page in Tapestry. Page name specified in the attribute t: page. In our case, the reference [Register] will lead to the newly created registration page. 
Intravenous in class Index Hibernate session and change the method onSubmitFromLoginForm as follows: 

public Object onSubmitFromLoginForm () { 
    
Criteria criteria = session.createCriteria (User.class) 
        
. Add (Restrictions.eq ("login", login)) 
        
. Add (Restrictions.eq ("password", password)); 
    
if (! criteria.list (). isEmpty ()) { 
        
return welcome; 
    }
 
    
return error; 


The method creates a session createCriteria criterion, ie the sample, the class User. Add method adds to it limits, in this case - limited selection of records that have the login and password match the user entered. If the user has passed the registration procedure, then this record should be exactly one, otherwise the list criteria.list () will be empty. 
Start the server and go to http://localhost:8080/TapestryForum. Make sure that under the form to enter your login and password, a link to go to the registration page: 
Click on this link. You will see a form created for us to part BeanEditForm: 
Pay attention to labels to input fields. Their names are derived from the names of the properties of the class User, by bringing them to a readable form. Thus, nickName become a Nick Name, and login - in Login. 
Component BeanEditForm has great potential for customization. You can change his style, you can rearrange the fields in some places or add new ones. Tags default, too, can be replaced by a mechanism of internationalization. Besides, I did not mention validation. But all this - some other time. 
Enter your name, username and password and click "Save". You will return to the login page.Now enter the newly defined login name and password and click "Login". You will be redirected to the page you are already familiar greetings Welcome. Try entering the wrong username and password - you will find yourself on page Error. 
You can go back to the MySQL console and make sure that the database table will appear forum_user, and it adds a string (of course, if you register you entered the Russian letters, you will instead question for). To do this, type the command: 

show tables; 
select * from forum_user; 

If you want to play around with the code and restart the server - do not forget to fix the value hbm2ddl.auto file hibernate.cfg.xml in the update, otherwise the table forum_user be created anew.

Search
Entries archive

Copyright ZmeyStudio © 2024
Hosted by uCoz