Mybatis+spring Integration Create Web project

Source: Internet
Author: User

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

This article is to implement a Web project using Mybatis+spring+mysql to achieve the whole goal. Configure the sqlsessionfactory of the data source and MyBatis in spring, and then get the beans in spring in the JSP in the Web. Use this bean to manipulate tables in MySQL. Online read a lot of people have written, but either the figure is not clear, or the code is not finished. This article is a complete tutorial and you can integrate it yourself.

version used: Mybatis-3.2.8

Spring3.2.9

Mysql5.6

development environment: Eclipse Java EE kepler+win7

This article works free download
Create a Web project and import the package

Create a Web project in Eclipse and import the following package:


It is important to note that you cannot mybatis-spring-1.2.2.jar this package, this package is used to contact spring and mybatis.

the entire project directory is as follows:


Second, create the Library table mapping class and configure the MyBatis

1. First create a table in the database T_user

Use test;
DROP TABLE IF EXISTS t_user;
CREATE TABLE T_user
(
 userId  int primary key auto_increment,
 userName VARCHAR () not NULL,
 Userage int NOT null
);
Then insert 4 data:

INSERT into T_user values (1, ' Xiao Wang ', ten);
INSERT into T_user values (2, ' Red ', one-by-one);
INSERT into T_user values (3, ' plainly ', ');
INSERT into T_user values (4, ' daily ', 13);
View the results below:


2, the table created after the creation of its mapping class user, in the package Com.mucfc.model

Package Com.mucfc.model;
/** *
 User mapping class
 * @author linbingwen
 * @time 2015.5.15 * * Public
class User {
	private Integer UserId;
	Private String userName;
	private int userage;
	Public Integer getUserId () {
		return userId;
	}
	public void Setuserid (Integer userId) {
		This.userid = userId;
	}
	Public String GetUserName () {
		return userName;
	}
	public void Setusername (String userName) {
		this.username = userName;
	}
	public int getuserage () {
		return userage;
	}
	public void setuserage (int userage) {
		this.userage = userage;
	}
	@Override public
	String toString () {
		return "User [userid=" + UserId + ", username=" + userName
				+ ", Userag E= "+ Userage +"] ";
	}

}

2. After the mapping class is created, the MyBatis mapping file (i.e. the mapper file) is created and is located in the Mapper package of Conf with SRC peers, with the following file contents:

<?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.mucfc.mapper.UserMapper" >	
	<!--  Query single record  -  
    <select id= "Selectuserbyid" parametertype= "int" resulttype= "User" >  
       select * from t_user where userId = #{userid}  
    </ Select>  
</mapper>
3, create the map Usermapper class as below, in the package Com.mucfc.mapper

Package com.mucfc.mapper;

Import Com.mucfc.model.User;
/**
 * Mapper Map class
 * @author linbingwen
 * @time 2015.5.15 */public
interface Usermapper {
	Public User Selectuserbyid (int userId);

}
4. Creating the DAO layer of operational data

Package Com.mucfc.dao;

Import Com.mucfc.model.User;
/**
 * DAO interface Layer
 * @author Linbingwen
 * @time 2015.5.15 * * Public
interface Userdao {
	/**
	 * Query user information based on user ID
	 * @param ID
	 * @return */public
	user Finduserbyid (int id);
}
Then the corresponding implementation layer

Package Com.mucfc.dao;

Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.stereotype.Component;
Import  com.mucfc.mapper.UserMapper;
Import Com.mucfc.model.User;
/** *
 DAO Implementation Layer
 * @author Linbingwen
 * @time 2015.5.15 */
 @Component public
class Userdaoimpl implements userdao{
    @Autowired
	private usermapper usermapper;
	@Override Public
	user Finduserbyid (int id) {
		user user = Usermapper.selectuserbyid (ID);
		 return user; 
	}
	
}

5. Configure the MyBatis configuration file in conf:

MYBATISCONF.XMLL in conf, note the path .

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "
http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
   <!--configuration mapping class aliases--
 	<typeAliases>
      <typealias alias= "User" Type= "Com.mucfc.model.User"/> 
   </typeAliases>  
   <!--Configuring the path to the mapper file--
   <mappers>
       <mapper resource= "Mapper/usermapper.xml"/>
   </mappers>
</configuration>

If you do not integrate with spring, this configuration file also needs to configure the data source information, after the integration with spring data source is configured in the spring configuration file, only need to configure the path of the mapping file. Third, configure Spring

1. Configure the spring configuration file in Web-inf:

Springconf.xml in Web-inf, note the path.

<?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:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "http://www.springframework.org/sc Hema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springfra MEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd Http://www.spri Ngframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> &lt ;! --Configure Data Source--<bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > &lt ;p roperty name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "jdbc:mysql:// Localhost:3306/test "/> <property name=" uSername "value=" root "/> <property name=" password "value=" christmas258@ "/> </bean> <bean id=" Sqls Essionfactory "class=" Org.mybatis.spring.SqlSessionFactoryBean "> <property name=" dataSource "ref=" DataSource "/> <!--<property name=" mapperlocations "value=" Conf/mapper/usermapper.xml "/>--<property name = "Configlocation" value= "Conf/mybatisconf.xml"/> <!--<property name= "Typealiasespackage" value= " Com.tiantian.ckeditor.model "/>--</bean> <bean id=" Usermapper "class=" Org.mybatis.spring.mapper .   
       Mapperfactorybean "> <property name=" mapperinterface "value=" Com.mucfc.mapper.UserMapper "/> <property name= "Sqlsessionfactory" ref= "Sqlsessionfactory"/> </bean> <!--automatic scanning of annotated beans--
 > <context:component-scan base-package= "Com.mucfc.dao"/> </beans>

2. Start spring in Web. xml

Web. XML put in Web-inf

<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.5" xmlns= "http://java.sun.com/xml/ns/ Java ee "
	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 >
	<!--Configure the initial open page-
	< welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file> index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</ Welcome-file-list>
	
	<!--Spring container load-
	<listener>
		<listener-class> org.springframework.web.context.contextloaderlistener</listener-class>
	</listener>
	< context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/ web-inf/springconf.xml</param-value>
	</context-param>

</web-app>

3, read the bean, to find

Set the following in index.jsp:

Index.jsp placed in WebContent

<%@ page import= "Com.mucfc.dao.UserDao"%> <% @page import= " Org.springframework.web.context.WebApplicationContext "%> <% @page import=" Org.springframework.web.context.support.WebApplicationContextUtils "%> <%@ page language=" java "contenttype=" Text/html "pageencoding=" UTF-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 

Four, the Operation

1. Run on server

2. Browser input: http://localhost:8080/MybatisLearningChapter5/

The results are as follows:




Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

This article works free download

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.