Now in the mainstream project framework, the database persistence layer may not hibernate, but MyBatis or ibatis, in fact, they are all the same, let me set up the environment:
"Import related jar packages" new Web project Engineering Mss,spring+struts2+mybatis Consolidation, in addition to the Spring and struts jar packages (which can be downloaded from my resources), we also need to import several MyBatis jar packages:
Three framework integration after JAR package:
"Configure Web. Xml"
<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <welcome-file-list> <welcome-file>index.jsp</ Welcome-file> </welcome-file-list> <!--struts Start-up configuration-<filter> <filter-name>struts2< ;/filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter< /filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pa Ttern>/*</url-pattern> </filter-mapping> <!--spring start load configuration-<context-param> <para M-name>contextconfiglocation</param-name> <param-value>classpath:springconfig/ Applicationcontext-*.xml</param-value> </context-param> <listener> <listener-class> Org.springframework.web.context.ContextLoaderListener </listener-class> </l Istener> <!--log4j related configurations-<context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> < Context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</ param-value> </context-param> <listener> <listener-class> Org.springframework.web.util.log4jconfiglistener</listener-class> </listener></web-app>
Spring Public configuration applicationcontext-common.xml
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans htt P://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/tx http:/ /www.springframework.org/schema/tx/spring-tx-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP HTTP://WWW.SPR Ingframework.org/schema/aop/spring-aop-3.0.xsd "><aop:aspectj-autoproxy proxy-target-class=" true "/> < !--Read configuration file--><bean id= "Propertyconfigurer" class= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "><property name=" Location "value=" Classpath:jdbc.properties "/></bean><!--database connection pool--><bean id=" DataSource "class=" Org.apache.commons.dbcp.BaSicdatasource "destroy-method=" Close "><property name=" Driverclassname "> <value>${jdbc_driver}</ Value></property><property name= "url" ><value>${jdbc_url}</value></property> <property name= "username" > <value>${jdbc_user}</value></property><property name= " Password "> <value>${jdbc_password}</value></property><property name=" maxActive "value=" "></property><property name=" Maxidle "value=" "></property><property name=" maxWait " Value= "$" ></property><property name= "Defaultautocommit" value= "true" ></property></bean > <!--transaction configuration--><bean id= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "><property name=" datasource "ref=" DataSource "/></bean><!--Entity Mapping class--><bean id=" Sqlsessionfactory "class=" Org.mybatis.spring.SqlSessionFactoryBean "><property name=" DatasoUrce "ref=" DataSource "/><property name=" Typealiasespackage "value=" Com.mss.common.pojo "/></bean> </beans>
Database configuration file Jdbc.properties:
"Struts2 Public Configuration"
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.0//en" "Http://struts.apache.org/dt Ds/struts-2.0.dtd "><struts><!--give struts2 to spring management--><constant name=" Struts.configuration.xml.reload "value=" true "/><constant name=" struts.action.extension "value=" Action,do, WebWork "/><constant name=" Struts.enable.DynamicMethodInvocation "value=" true "/> <constant name=" Struts.devmode "value=" true "/><constant name=" struts.multipart.maxSize "value=" 100971520 "></constant ><constant name= "struts.i18n.encoding" value= "UTF-8" ></constant><constant name= " Struts.objectFactory.spring.autoWire "value=" name "></constant><constant name=" Struts.objectfactory " Value= "Spring" ></constant><constant name= "struts.custom.i18n.resources" value= "Messages" ></ Constant><include file= "Strutsconfig/struts-user.xml" ></include></sTruts>
Create data table structure: In the project we used a MySQL database and created a new user table inside:
"Building The Project structure": Here I used a three-tier architecture: Action-->service-->dao (Entity Class)
To write 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 E Mail;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);/** * List all users * @return */public list<user> queryusers ();/** * Delete users * @pa Ram id */public void Deluser (String id);}
With MyBatis, we have to configure the XML file, map the entity class user to the table user, and map the methods in the Userdao, so that we don't need to write Userdaoimpl, Because the operation of the database is also done in this XML: Userdao.xml, this is important.
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Com.mss.user.dao.UserDao" > <!--User entity class, user table mappings, note that the entity class user and table names should be consistent, and the fields below can be configured-->< Resultmap id= "UserMap" type= "Com.mss.common.pojo.User" ><result property= "id" column= "id"/><result Property= "UserName" column= "UserName"/><result property= "password" column= "Password"/><result property = "Email" column= "Email"/></resultmap> <!--to configure the method in Userdao, id= method name, parametertype= parameter type, Resultmap returned results , when the user uses the method in Userdao, Mybaties himself will find the operation of the database in the corresponding configuration file--><insert id= "AddUser" parametertype= "User" >insert into USER (Id,username,password,email) VALUES (#{id},#{username},#{password},#{email}) </insert><!--return one of the above Resultmap instance, where the resultmap is consistent with the ID in the configuration resultmap above--><select id= "Queryusers" resultmap= "UserMap" >select * From user</select><!--Delete information--> <delete id= "Deluser" parametertype= "string" >delete from USER WHERE id = #{id}</delete></mapper>
Write our service and Serviceimpl classes, operate the DAO Layer: UserService, Userserviceimpl
Public interface UserService {/** * Add user * @param user */public void AddUser (user user);/** * List all users * @return */public L Ist<user> 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) {userdao.adduser (user);} /** * List all users */public list<user> queryusers () {list<user> userlist = Userdao.queryusers (); return userList;} /** * Delete user */public void Deluser (String id) {userdao.deluser (id);}}
Write action, Action service,useraction
/** * User Action Action * @author Dell * */public class Useraction extends Actionsupport {private static final long serialversion UID = 1l;private static Logger Logger = Logger.getlogger (useraction.class);p ublic 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 + ""; 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;} /** * Get all user information from the database * * @return */public String queryusers () {try {list<user> 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 ("Exc Eption 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:
One of the most related to MyBatis is the Userdao.xml file, all of our operations and methods of the database can be in the corresponding configuration and parameter settings, as long as the corresponding name set and match well, MyBatis can automatically call
"Configure our own Spring XML file: Applicationcontext-user.xml", where MyBatis and spring integrated with the following property configuration is important: <bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "></bean>, with corresponding annotations below
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans htt P://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/tx http:/ /www.springframework.org/schema/tx/spring-tx-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP HTTP://WWW.SPR Ingframework.org/schema/aop/spring-aop-3.0.xsd > <!--manipulate the spring profile of the user class--<!--Configure the DAO class in user so that the Mybatie S can configure user to interact with database-<!--can map User.xml file--><bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "><property name=" Basepackage "value=" Com.mss.user.dao "/ ></bean><!--Configuration UserService, note that the Userdao name is the same as the Userdao property name in Userserviceimpl--><bean id= "UserseRvice "class=" Com.mss.user.serviceImpl.UserServiceImpl "><property name=" Userdao "ref=" Userdao "/></ bean><!--Configure the action, note that the UserService name is the same as the UserService property name in Useraction--><bean id= "useraction" class= " Com.mss.user.action.UserAction "><property name=" UserService "ref=" UserService "/></bean></beans >
"Configure your own struts Xml:struts-user.xml"
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public "-//apache software foundation//dtd struts Configuration 2.0//en" "/http Struts.apache.org/dtds/struts-2.0.dtd "><struts><package name=" user "extends=" Struts-default " Namespace= "/" > <action name= "useraction" class= "useraction" > <result name= "Success" > success.jsp</result> <result name= "error" >error.jsp</result> <result name= "list" >UserList.jsp</result> </action></package></struts>
"We used log4j in the project and configured Log4j.properties"
The basic configuration of the project is basically complete, write our view layer, above action we jump to userlist.jsp, write 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 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Well, the basic environment has basically been completed, the project deployed to Tomcat, the start of Tom's cat, if no error, indicating that our project was successfully built, enter the following address: http://localhost:8080/mybatiesss/useraction! Queryusers.do, if there is no data in the database, then add the corresponding data, if the corresponding database records, indicating that our project was built successfully!
Compared to hibernate:
Hibernate: To write an XML file of the entity class and the Entity class Mapping database table, and then manipulate the database using the Hibernate encapsulated Java class interface
MyBatis: Write the entity class, Entity class Mapping database table XML file, the data method operation XML file, its operation on the database is also defined in the XML file, basically using pure SQL statement
MyBatis is semi-automatic, hibernate is fully automatic, that is, MyBatis can configure SQL statements, for SQL tuning is better, hibernate will automatically generate all the SQL statements, tuning inconvenient, Hibernate is more difficult to use than MyBatis. MyBatis's main idea is the SQL Mapping, and hibernate is or Mapping,mybatis applied to the project will be more intuitive, can directly see the SQL, and hibernate is to manipulate the data by manipulating objects, Can be flexibly applied 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
Above is just a rough explanation of mybatis and spring and struts of the project integration, and did not have a very detailed explanation of mybatis, in fact, it is also very easy to learn, I hope you have time to get to know!!
Manual configuration three-frame integration: Spring+struts2+mybatis