Configuration instructions for developing web programs using spring and Hibernate and detailed descriptions of simple instances

Source: Internet
Author: User

Configuration instructions for developing web programs using spring and Hibernate and detailed descriptions of simple instances

Author: Yanek
Email: yanek@126.com

I. Goals:

Use spring and Hibernate to add a user. Add User information to the database
Use the hibernate template of spring to implement DaO operations.

Final Result: Enter http: // localhost: 8083/hibernatetestweb/user. Do in the browser to add a record.

Ii. Layered Structure

The system adopts the following layered structure:

1. web layer: the user interface layer is implemented using spring web MVC framework.

2 service layer: the business logic layer consists of business interfaces and implementation classes.

3. Dao layer: the data access layer consists of data access interfaces and implementation classes.

4. Persistence Layer: Use hibernate to implement database access. Implement the DaO interface.

Iii. Database Structure

Database Structure: user_table table

SQL statements for table Creation

Create Table user_table
(
Id varchar2 (255) not null,
Username varchar2 (20 ),
Password varchar2 (20)
)

Assume that the database is Oracle9i.
The username and password are test/1234.

Iv. Related Categories of system design and their hierarchies

1. User. java indicates the value object class of the User entity. It corresponds to the Database User table structure and provides the setter and getter methods as standard javabean.
2. UserDAO. java DAO Interface
3. Implementation class of UserDAOImp. java DAO Interface
4. interfaces at the business logic layer of UserService
5. The implementation class of the interface at the business logic layer of UserServiceImp, And the DAo interface is called to implement the business logic.
6. The customer call layer of UserController web layer calls the business logic layer to process the business logic. (Front-end)

V. Related configuration files: (key points: Error points)

Including Spring configuration files, hibernate configuration files, and web. xml files

Note:

Web. xml, applicationContext. xml, the SpringhibernateStudy-servlet.xml is all under the WEB-INF root directory, the ing file is under the same directory as the entity class

 

1. Spring configuration file:

The configuration file here includes two:

1. applicationContext. xml defines and configures the data source, transaction, transaction proxy, DAO, and Service layer classes.

The content is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE beans PUBLIC "-// SPRING // dtd bean // EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<Beans>

<! -- The following defines the connection information of the database. The class is org. apache. commons. dbcp. BasicDataSource -->

<Bean id = "dataSource" class = "org. apache. commons. dbcp. BasicDataSource" destroy-method = "close">
<Property name = "driverClassName">
<Value> oracle. jdbc. driver. OracleDriver </value>
</Property>

<Property name = "url">
<Value> jdbc: oracle: thin: @ 192.168.1.191: 1521: yanek </value>
</Property>
<Property name = "username">
<Value> test </value>
</Property>
<Property name = "password">
<Value> 1234 </value>
</Property>

</Bean>



<! -- The following defines sessionFactory to prepare for session Creation -->

<Bean id = "sessionFactory" class = "org. springframework. orm. hibernate. LocalSessionFactoryBean">
<Property name = "dataSource">
<Ref local = "dataSource"/>
</Property>

<Property name = "mappingResources">
<List>
<Value> apps/hibernatetest/ioc/User. hbm. xml </value>

</List>
</Property>

<Property name = "hibernateProperties">
<Props>
<Prop key = "hibernate. dialect"> net. sf. hibernate. dialect. OracleDialect </prop>
<Prop key = "hibernate. show_ SQL"> true </prop>
<Prop key = "hibernate. cglib. use_reflection_optimizer"> true </prop>
</Props>
</Property>
</Bean>


<! -- The following defines the hibernate template -->
 
<Bean id = "hibernatetemplate" class = "org. springframework. Orm. hibernate. hibernatetemplate">
<Property name = "sessionfactory">
<Ref local = "sessionfactory"/>
</Property>
</Bean>


<! -- The following defines the User-Defined Dao and specifies the DAO implementation class. The DAO implementation references the hibernate template. -->

<Bean id = "userdao" class = "apps. hibernatetest. IOC. userdaoimp">
<Property name = "hibernatetemplate">
<Ref local = "hibernatetemplate"/>
</Property>
</Bean>

<! -- The following defines the Transaction Manager class and references it to sessionFactory -->

<Bean id = "mytransactionManager" class = "org. springframework. orm. hibernate. HibernateTransactionManager">
<Property name = "sessionFactory">
<Ref local = "sessionFactory"/>
</Property>
</Bean>


<! -- The following defines the transaction proxy factory class, references it to the transaction manager, and specifies the matching rules for calling methods to use transaction processing -->

<Bean id = "MyTransactionProxyFactory" abstract = "true" lazy-init = "true" class = "org. springframework. transaction. interceptor. TransactionProxyFactoryBean">
<Property name = "transactionManager">
<Ref local = "mytransactionManager"/>
</Property>
<Property name = "transactionAttributes">
<Props>
<Prop key = "user *"> PROPAGATION_REQUIRED </prop>
<Prop key = "insert *"> PROPAGATION_REQUIRED </prop>
<Prop key = "del *"> PROPAGATION_REQUIRED </prop>
<Prop key = "up *"> PROPAGATION_REQUIRED </prop>
<Prop key = "find *"> PROPAGATION_REQUIRED, readOnly </prop>
<Prop key = "dis *"> PROPAGATION_REQUIRED, readOnly </prop>
</Props>
</Property>
</Bean>


<! -- The following defines the business logic class, references it to the transaction manager, and uses the defined Dao to automatically inject the DAO class referenced by the business logic class -->

 
<Bean id = "userservice" parent = "mytransactionproxyfactory">
<Property name = "target">
<Bean class = "apps. hibernatetest. IOC. userserviceimp">
<Property name = "userdao"> <ref local = "userdao"/> </property>
</Bean>
</Property>
</Bean>

</Beans>

2. SpringhibernateStudy-servlet.xml mainly defines the mvc an of mvc web layer

Note: The name must match the servlet name corresponding to org. springframework. web. servlet. DispatcherServlet in web. xml.

Here the web. xml file is configured with the name SpringhibernateStudy, so the file name must be: SpringhibernateStudy-servlet.xml

Format: servlet name +-servlet. xml

If the configuration name is SpringServlet, the configuration file should be: SpringServlet-servlet.xml

The content is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE beans PUBLIC "-// SPRING/dtd bean/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<! ---Application context definition for "springapp" DispatcherServlet. -->
<Beans>

<! -- The following defines the web layer controller class, references it to the business processing class, and automatically injects the service class referenced by the web controller through the defined service class -->


<Bean id = "usercontroller" class = "apps. hibernatetest. IOC. usercontroller">
<Property name = "userservice">
<Ref bean = "userservice"/>
</Property>
</Bean>


<! -- The following defines the ing relationship between the web-layer request access path and the Controller class, and the method for configuring the request processing class -->

<Bean id = "userurlmapping" class = "org. springframework. Web. servlet. handler. simpleurlhandlermapping">
<Property name = "mappings">
<Props>
<Prop key = "/user. Do"> usercontroller </prop>

<! -- This indicates that // user. do will be handled by apps. hibernatetest. ioc. UserController by the corresponding controller named UserController. -->
</Props>
</Property>
</Bean>

</Beans>

 

 

2. hibernate configuration file:

The ing file: User. hbm. xml corresponds to USER_TABLE.

Name: User. hbm. xml

The detailed configuration code is as follows:

<? Xml version = "1.0"?>
<! DOCTYPE hibernate-mapping
PUBLIC "-// Hibernate/Hibernate Mapping DTD // EN"
Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd>
<Hibernate-mapping>

<Class name = "apps. hibernatetest. ioc. User" table = "USER_TABLE">
<ID name = "ID" type = "string" unsaved-value = "null">
<Column name = "ID" SQL-type = "varchar2 (255)" not-null = "true"/>
<Generator class = "UUID. Hex"/>
</ID>

<Property name = "username" type = "string">
<Column name = "username" SQL-type = "varchar2 (20)"/>
</Property>

<Property name = "password" type = "string">
<Column name = "password" SQL-type = "varchar2 (20)"/>
</Property>

</Class>

</Hibernate-mapping>

Note:

1. The class name must contain the complete path with the package name.
2. The corresponding database indicates that it must be consistent with the database
For example: <class name = "apps. hibernatetest. IOC. User" table = "user_table">

Name attribute: Object Class Name
The table attribute is the name of the database table.

3. The field information must be consistent with the database table structure.
4. Put the configuration file in the same directory as the object class and give instructions in the spring file.

For example, the full path of user. Java is apps. hibernatetest. IOC. user. The configuration is as follows:

<Property name = "mappingresources">
<List>
<Value> apps/hibernatetest/IOC/user. HBM. xml </value>

</List>
</Property>

 

Net. SF. hibernate. mappingexception: No persister for when you use hibernate to insert data into the database
Based on my error handling experience, there are three solutions to the No persister for error:
1. Check the HBM. xml file.
2. Check the cfg. xml file to see if the HBM. xml file name of the class has been written.
3. The relationship between one-to-Child (parent-to-child) should be
Child. setparent (parent) instead of Child. setparent (parent. ID)


3. Web. xml file:

Configure Servlet and other information here:

<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype web-app public "-// Sun Microsystems, Inc. // DTD web application 2.3 //" http://java.sun.com/dtd/web-app_2_3.dtd ">
<Web-app>

 

<Listener>
<Listener-class> org. springframework. web. context. ContextLoaderListener </listener-class>
</Listener>
<Servlet>

<Servlet-name> ContextLoaderServlet </servlet-name>
<Servlet-class> org. springframework. web. context. ContextLoaderServlet </servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>


<! -- The listener and context-mounted servelet are defined above to load the applicatincontext. xml file -->



<! -- The following defines the request distributor class for Spring configuration -->
<Servlet>
<Servlet-Name> springhibernatestudy </servlet-Name>
<Servlet-class> org. springframework. Web. servlet. dispatcherservlet </servlet-class>
<Load-on-startup> 2 </load-on-startup>
</Servlet>

<Servlet>
<Servlet-Name> debugjsp </servlet-Name>
<Description> added to compile JSPs with debug info </description>
<Servlet-class> org. Apache. Jasper. servlet. jspservlet </servlet-class>
<Init-param>
<Param-Name> classdebuginfo </param-Name>
<Param-value> true </param-value>
</Init-param>
<Load-on-startup> 3 </load-on-startup>
</Servlet>
 

<! -- The following defines that the request distributor configured with Spring will process all *. do requests -->
<Servlet-mapping>
<Servlet-name> SpringhibernateStudy </servlet-name>
<Url-pattern> *. do </url-pattern>
</Servlet-mapping>
 
<Servlet-mapping>
<Servlet-name> debugjsp </servlet-name>
<Url-pattern> *. jsp </url-pattern>
</Servlet-mapping>

</Web-app>

6. Detailed code of various classes

1. User. java indicates the value object class of the User entity. It corresponds to the Database User table structure and provides the setter and getter methods as standard javabean.

Note:

1. the setter and getter methods are provided to comply with the an specifications.
2. Implement the java. io. Serializable interface.
3. One-to-one correspondence with the database table structure

User. java

Package apps. hibernatetest. ioc;

Public class User implements java. io. Serializable
{
Private String id;
Private String username;
Private String password;

Public User (){}

Public String getId ()
{
Return id;
}

Public void setId (String id)
{
This. id = id;
}

Public String getUsername ()
{
Return username;
}

Public void setUsername (String username)
{
This. username = username;
}

Public String getPassword ()
{
Return password;
}

Public void setPassword (String password)
{
This. password = password;
}

}

 

2. UserDAO. java DAO Interface

UserDAO. java

Package apps. hibernatetest. ioc;

Public interface UserDAO
{
Public void userAdd (User user );
}

 

 

3. Implementation class of UserDAOImp. java DAO Interface

Note:

1. inherit from HibernateDaoSupport
2. Implement the dao Interface
3. Use a template to process data

UserDAOImp. java

Package apps. hibernatetest. ioc;
Import net. sf. hibernate. HibernateException;
Import net. sf. hibernate. Query;
Import net. sf. hibernate. Session;

Import org. springframework. orm. hibernate. HibernateCallback;
Import org. springframework. orm. hibernate. support. HibernateDaoSupport;

Public class UserDAOImp extends HibernateDaoSupport implements UserDAO
{
Public void userAdd (User user)
{
// Try
//{
// System. out. println ("save =" + getHibernateTemplate (). save (user ));
System. out. println ("aaa ===>" + user. getUsername ());
System. out. println ("bbb ===>" + user. getPassword ());
GetHibernateTemplate (). save (user );
System. out. println ("bbb ");
/*}
Catch (Exception e)
{
System. out. println ("An error occurred while inserting the user! ");
}*/
}

 

}

 

4. interfaces at the business logic layer of UserService

UserService. java

Package apps. hibernatetest. ioc;

Public interface UserService
{

Public void userAdd (User user );
}

5. The implementation class of the interface at the business logic layer of UserServiceImp, And the DAO interface is called to implement the business logic.

Note:

1. Implement the specified service interface
2. Interface Implementation call DAO Interface
3. The userDAO attribute must be available and the setter method is provided as follows:

Private UserDAO userDAO;
Public UserDAO getUserDAO ()
{
Return userDAO;
}
Public void setuserdao (userdao)
{
This. userdao = userdao;
}

In the configuration file, the DaO attribute is automatically injected by configuration.

This defines the dependency between the service class and Dao.

Userserviceimp. Java

Package apps. hibernatetest. IOC;

Public class userserviceimp implements userservice
{
Private userdao;
Private user = new user ();
Public userdao getuserdao ()
{
Return userdao;
}
Public void setuserdao (userdao)
{
This. userdao = userdao;
}
Public void useradd (User user)
{
Userdao. useradd (User );
}
}

 

6. The customer call layer of usercontroller web layer calls the business logic layer to process the business logic. (Front-end)

Usercontroller. Java

Package apps. hibernatetest. IOC;
Import org. springframework. Web. servlet. MVC. Controller;
Import org. springframework. Web. servlet. modelandview;
Import javax. servlet. servletexception;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import org. springframework. Web. Bind. requestutils;
Import java. io. IOException;
Import java. util. Map;
Import java. util .*;
Import java. util. HashMap;
Import org. apache. commons. beanutils. BeanUtils;

Import org. springframework. context. ApplicationContext;
Import org. springframework. web. context. support. WebApplicationContextUtils;

Public class UserController implements Controller
{
Private UserService userService;
Public void setUserService (UserService userService)
{
This. userService = userService;
}

Public ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String url = "";
Url = "addok. jsp ";

User u = new User ();
U. setUsername ("aaa ");
U. setPassword ("bbbb ");
UserService. userAdd (u );
Return new ModelAndView (url );
}

}

Note:

1. Implement the Controller Interface
2. provides private attributes and setter Methods

The following code

Private UserService userService;
Public void setUserService (UserService userService)
{
This. userService = userService;
}

3. In handleRequest, the Controller calls the property userService to call the business logic.
 
 
User u = new User ();
U. setUsername ("aaa ");
U. setPassword ("bbbb ");
UserService. userAdd (u );

4. Define the url variable and set its value as the parameter of the constructor of the ModelAndView class and as the jump address after the business logic is processed

String url = "";
Url = "addok. jsp ";
Return new ModelAndView (url );


 


VII. Project Description:

Debugging environment: jbulder9.0

Import the following main jar packages:
Spring. jar
Hibernate. java
Dhcp. java
Classes12
And so on.

8. Download Code:

Http://www.e-jrsj.com/hibernatetest.rar

 

9. Code for testing the javabean class method in the configuration file in the main method:

Note: The applicationContext. xml file is stored in the root directory of classes.

Package apps. hibernatetest. ioc;

Import org. springframework. beans. factory. BeanFactory;
Import org. springframework. beans. factory. xml. XmlBeanFactory;
Import org. springframework. core. io. ClassPathResource;
Import org. springframework. core. io. Resource;
Import org. apache. commons. logging. Log;
Import org. apache. commons. logging. LogFactory;

Public class Test
{

Public static void main (String [] args)
{


// Obtain beanFactory (bean Factory) based on the configuration file)

Resource resource = new ClassPathResource ("applicationContext. xml ");
Beanfactory factory = new xmlbeanfactory (Resource );


// Obtain the instantiated bean from the configuration file through the Bean Factory and convert it to the corresponding interface

Userdao Dao = (userdao) Factory. getbean ("userdao ");

/*
<Bean id = "userdao" class = "apps. hibernatetest. IOC. userdaoimp">
<Property name = "hibernatetemplate">
<Ref local = "hibernatetemplate"/>
</Property>
</Bean>
*/

Userservice service = (userservice) Factory. getbean ("userservice ");


/*
Corresponding configuration file
<Bean id = "userservice" parent = "mytransactionproxyfactory">
<Property name = "target">
<Bean class = "apps. hibernatetest. IOC. userserviceimp">
<Property name = "userdao"> <ref local = "userdao"/> </property>
</Bean>
</Property>
</Bean>
*/



System. out. println ("tettet ");
User u = new User ();
U. setUsername ("aaa ");
U. setPassword ("bbbb ");
Dao. userAdd (u );

Service. userAdd (u );

 

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.