Integrate manual configuration of three frameworks: Spring + Struts2 + mybatis

Source: Internet
Author: User

Integrate manual configuration of three frameworks: Spring + Struts2 + mybatis

In the mainstream project framework, the database persistence layer may not be hibernate, but mybatis or ibatis. In fact, they are all the same. Let's build the environment:

[Import jar packages] create a web project mss, Spring + Struts2 + mybatis integration, except for the jar packages of Spring and Struts (which can be downloaded from my resources ), we also need to import several jar packages of mybatis:

Jar packages after the three frameworks are integrated:

[Configure web. xml]

 
   
      
   
    
Index. jsp
     
      
    
      
   
    
Struts2
       
   
    
Org. apache. struts2.dispatcher. ng. filter. StrutsPrepareAndExecuteFilter
     
    
      
   
    
Struts2
       
   
    
/*
     
      
    
      
   
    
ContextConfigLocation
       
   
    
Classpath: springConfig/applicationContext-*. xml
     
    
      
   
    
Org. springframework. web. context. ContextLoaderListener
     
      
    
      
   
    
Log4jConfigLocation
       
   
    
// WEB-INF/classes/log4j. properties
     
    
      
   
    
Log4jRefreshInterval
       
   
    
60000
     
    
      
   
    
Org. springframework. web. util. Log4jConfigListener
     
  
 

[Spring public configuration applicationContext-common.xml]

 
         
  
  
   
  
  
  
      
    
     
$ {Jdbc_driver}
    
   
   
    
     
$ {Jdbc_url}
    
   
       
    
     
$ {Jdbc_user}
    
   
       
    
     
$ {Jdbc_password}
    
   
   
   
   
   
      
  
  
   
  
  
  
   
   
  
 

Database Configuration File jdbc. properties:

[Struts2 public configuration]

 
 
  
  
  
      
  
  
  
  
  
  
  
 

[Create a data table structure]: mysql database is used in the project. A user table is created in the project:

[Build a project structure]: Here I use a three-tier architecture: Action --> Service --> Dao (entity class)

Compile the user entity class:

package com.mss.common.pojo;import java.io.Serializable;public class User implements Serializable {/** *  */private static final long serialVersionUID = 1L;private String id;private String userName;private String password;private String email;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;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}

Write our dao layer UserDao:

Package com. mss. user. dao; import java. util. list; import com. mss. common. pojo. user; public interface UserDao {/*** Add user * @ param User */public void addUser (user User user);/*** List all users * @ return */public List
 
  
QueryUsers ();/*** delete user * @ param id */public void delUser (String id );}
 

When using mybatis, We need to configure the xml file to map the object class User to the table user, and map the methods in UserDao to implement the implementation. In this way, we do not need to write UserDaoImpl, because database operations are also performed in this xml: UserDao. xml, which is very important

   
     
  
  
   
   
   
   
      
  
  
   
Insert into user (ID, USERNAME, PASSWORD, EMAIL) VALUES (# {id}, # {userName}, # {password}, # {email })
  
  
  SELECT * FROM USER
  
  
   
Delete from user where id =#{ id}
  
 

Write our Service and ServiceImpl class, operate Dao layer: UserService, UserServiceImpl

Public interface UserService {/*** Add user * @ param User */public void addUser (user);/*** List all users * @ return */public List
 
  
QueryUsers ();/*** delete user * @ param id */public void delUser (String id );}
 
Package com. mss. user. serviceImpl; import java. util. list; import com. mss. common. pojo. user; import com. mss. user. dao. userDao; import com. mss. user. service. userService; public class UserServiceImpl implements UserService {private UserDao userDao; public UserDao getUserDao () {return userDao;} public void setUserDao (UserDao userDao) {this. userDao = userDao;}/*** Add User */public void addUser (user User user) {userDao. addUser (user);}/*** List all users */public List
 
  
QueryUsers () {List
  
   
UserList = userDao. queryUsers (); return userList;}/*** delete user */public void delUser (String id) {userDao. delUser (id );}}
  
 

Write Action, operate Service, and UserAction

/*** User operation Action * @ author dell **/public class UserAction extends ActionSupport {private static final long serialVersionUID = 1L; private static Logger logger = Logger. getLogger (UserAction. class); public UserService userService; public UserService getUserService () {return userService;} public void setUserService (UserService userService) {this. userService = userService;} private String id; private String userName; private String password; private String email;/*** Add User Information ** @ return */public String addUser () {User user = new User (); try {String iid = new Random (). nextInt (100) + ""; user. setId (iid); user. setUsername (userName); user. setPassword (password); user. setEmail (email); userService. addUser (user);} catch (Exception e) {logger. error ("exception in add user", e); return ERROR;} return SUCCESS ;} /*** obtain all user information from the database ** @ return */public String queryUsers () {try {List
 
  
UserList = userService. queryUsers (); for (int I = 0; I <userList. size (); I ++) {System. out. println (userList. get (I ). getId ();} HttpServletRequest request = ServletActionContext. getRequest (); request. setAttribute ("list", userList); return "list";} catch (Exception e) {logger. error ("Exception in queryUsers", e); return ERROR ;}/ *** delete user information ** @ return */public String delUser () {try {userService. delUser (id);} catch (Exception e) {logger. error ("Exception in delUser", e); return ERROR;} return SUCCESS;} public void setId (String id) {this. id = id;} public void setUserName (String userName) {this. userName = userName;} public void setPassword (String password) {this. password = password;} public void setEmail (String email) {this. email = email ;}}
 

Overall code structure:

Among them, the biggest one related to mybatis is UserDao. xml file. All Database Operations and methods can be configured and set parameters in it. As long as the corresponding names are set and matched, mybatis can be automatically called.
[Configure our own spring xml file: applicationContext-user.xml], in which the following attribute configuration of mybatis and spring integration is very important: , The corresponding annotations are as follows:

 
     
      
      
  
  
   
  
  
  
   
  
  
  
   
  
 

[Configure your Struts xml: struts-user.xml]

 
 
          
   
    success.jsp
         
   
    error.jsp
         
   
    UserList.jsp
     
  
 

[Log4j is used in the project to configure log4j. properties]

The basic configuration of the Project is basically complete. compile our view layer. In the above Action, we jump to UserList. jsp and compile our jsp display page:

<% @ Page language = "java" contentType = "text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%> <% @ taglib uri =" http://java.sun.com/jsp/jstl/core "prefix =" c "%>
 Insert title here
 
Delete record

Now, the basic environment is basically set up. Deploy the project to Tomcat and start Tom's cat. If no error is reported, the project is successfully set up. Enter the following address: http: // localhost: 8080/MybatiesSS/userAction! QueryUsers. do: If there is no data in the database, add the corresponding data. If the corresponding database records are displayed, the project is successfully set up!

Full Project can be downloaded in my Repository: http://download.csdn.net/detail/harderxin/7308169

Compared with hibernate:

Hibernate: You need to write xml files that map object classes and object classes to database tables, and then operate the database using the java class interfaces encapsulated by hibernate.

Mybatis: Compile xml files for ing object classes and object classes to database tables, and operate on data methods in xml files. Its operations on databases are also defined in xml files, basically, pure SQL statements are used.

Mybatis is semi-automated, and hibernate is fully automated. That is to say, mybatis can configure SQL statements. For SQL optimization, it is better. hibernate will automatically generate all SQL statements, which is inconvenient to tune, hibernate is more difficult to use than mybatis. The main idea of mybatis is SQL Mapping, while hibernate is OR Mapping. When mybatis is applied to a project, it is more intuitive to see SQL directly, while hibernate operates data through objects, it can be used flexibly between different databases.

To compare the difference between hibernate and mybatis, you can also refer to the blog: http://blog.csdn.net/firejuly/article/details/8190229

The above is just a rough description of the Integration of mybatis with Spring and struts projects, and does not provide a detailed explanation of mybatis. In fact, it is quite easy to learn, I hope you will have time to learn about it !!

Related Article

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.