"Persistence framework" SPRINGMVC+SPRING4+MYBATIS3 integration, development of simple Web project + source download

Source: Internet
Author: User
Tags config xmlns create database mysql database

In the previous blog, we introduced the basic concepts and principles of mybatis, which we developed through spring and MyBatis to develop a simple user-censored Web project.

Basic Preparatory work

1, install JDK1.6 above version, installation and configuration

2. Download mybatis-3.2.0 version: https://repo1.maven.org/maven2/org/mybatis/mybatis/

3. Download mybatis-spring-1.2.1 version: https://repo1.maven.org/maven2/org/mybatis/mybatis-spring/

4, the Spring-4.0.0 version

5, tomacat6.x or above version can be

Of course, these jars are not enough, also need MySQL database and drive, log4j jar and so on. Let's start today's trip:


First step: Create a database table


Under Navicat, execute the following SQL command to create the database MyBatis and table T_user

CREATE DATABASE IF not EXISTS mybatis;
Use MyBatis;
CREATE TABLE T_user
(
    user_id Int (one) not NULL auto_increment,
    user_name varchar () is not NULL,
    user_age varchar () Not NULL,
    PRIMARY KEY (user_id)
) Engine=innodb DEFAULT Charset=utf8;

Let's take a look at the full list of items before proceeding to the following content


Step Two: Add a jar package




For the contents of the following code, we will no longer one by one posted out, just the most important content posted out, we can download the source code.


Step three: Create the model

Create a model package and create a User.java file under it.

Package Com.tgb.model;

/** *
 User
 * @author Liang * * */Public
class User {

	private int id;
	Private String age;
	Private String userName;
	Public User () {
		super ();
	}
	public int getId () {
		return ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String Getage () {
		return age;
	}
	public void Setage (String age) {
		this.age = age;
	}
	Public String GetUserName () {
		return userName;
	}
	public void Setusername (String userName) {
		this.username = userName;
	}
	public User (int ID, string age, String userName) {
		super ();
		This.id = ID;
		This.age = age;
		This.username = UserName;
	}
}

Fourth step: Creating the DAO Interface


Create a package mapper, and under it create a Usermapper.java file as the DAO interface.

Package com.tgb.mapper;

Import java.util.List;

Import Com.tgb.model.User;

Public interface Usermapper {

	void Save (user user);
	Boolean update (user user);
	Boolean delete (int id);
	User FindByID (int id);
	List<user> findAll ();
}

Fifth Step: Implementing the DAO Interface


Create a Usermapper.xml file under the DAO package as an implementation of the DAO interface created in the previous step.

<?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" > <!--N  Amespace: Must match the full class name of the corresponding interface ID: must correspond to a corresponding method name of the corresponding interface--<mapper namespace= "Com.tgb.mapper.UserMapper" > <insert
	
	Id= "Save" parametertype= "User" > INSERT into T_user (user_name,user_age) VALUES (#{username},#{age}) </insert> <update id= "Update" parametertype= "User" > Update t_user set user_name=#{username},user_age=#{age} where user_id =#{id} </update> <delete id= "delete" parametertype= "int" > Delete from T_user where User_id=#{id} </d Elete> <!--the alias class name configured in Mybsits_config, can also be configured directly Resulttype for class road strength--<select id= "FindByID" parametertype= "in T "resulttype=" User "> select user_id id,user_name username,user_age age from T_user where User_id=#{id} </select&
	
	Gt <select id= "FindAll" resulttype= "User" > select user_id id,user_name username,user_aGE age from T_user </select> </mapper> 

Here are some notes on this XML file:
1. Namespace must be consistent with the full class name of the corresponding interface.
2, the ID must match the corresponding interface of a corresponding method name must be the same as the method in the Usermapper.java interface.


Sixth step: Integration of MyBatis and spring


The integration of MyBatis and spring is the focus of this blog post, and the content that needs to be configured is explained in more detail 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:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-4.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.0.xsd "> <!--1. Data Source: Drivermanagerdatasource--<bean id= "DataSource" class= " Org.springframework.jdbc.datasource.DriverManagerDataSource "> <property name=" driverclassname "value=" Com.mysql.jdbc.Driver "/> <property name=" url "value=" Jdbc:mysql://localhost:3306/mybatis "/> <propErty name= "username" value= "root"/> <property name= "password" value= "123456"/> </bean> <!--2. MyBatis's sqlsession factory: Sqlsessionfactorybean dataSource: Reference data source MyBatis define data source, agree to load configuration--<bean id= "sqlsessionfact Ory "class=" Org.mybatis.spring.SqlSessionFactoryBean "> <property name=" dataSource "ref=" DataSource "></ property> <property name= "configlocation" value= "Classpath:config/mybatis-config.xml"/> </bean> < !--3. MyBatis automatic Scan load SQL map File/interface: Mapperscannerconfigurer sqlsessionfactory basepackage: Specify the package that contains the SQL mapping File/interface (auto-scan)--<be An class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "basepackage" value= " Com.tgb.mapper "></property> <property name=" sqlsessionfactory "ref=" Sqlsessionfactory "></ Property> </bean> <!--4. Transaction management: Datasourcetransactionmanager DataSource: Referencing the data source defined above-<bean id= "Txmanager" class= "ORG.SPRINGFRAMEWORK.J Dbc.datasoUrce. Datasourcetransactionmanager "> <property name=" dataSource "ref=" DataSource "></property> </bean > <!--5. Use declarative transaction Transaction-manager: Reference the transaction manager defined above--<tx:annotation-driven transaction-manager= "Txmanager"/> <
 /beans>

Seventh Step: MyBatis's configuration file

<?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>

	<!--entity classes, abbreviated-set aliases--
	<typeAliases>
		<typealias alias= " User "type=" Com.tgb.model.User "/>
	</typeAliases>
	<!--Entity Interface Mapping Resources--
	<!--
		Note: If the Xxmapper.xml configuration file is placed in and Xxmapper.java the Unified directory, Mappers can also be omitted, because Org.mybatis.spring.mapper.MapperFactoryBean default will be to find and Xxmapper.java Same directory and name Xxmapper.xml-
	-
	<mappers>
		<mapper resource= "Com/tgb/mapper/usermapper.xml"/ >
	</mappers>

</configuration>  


Summary


The integration of MyBatis and spring is relatively simple, and I wish you success.


SOURCE Download: Springmvc+spring4+mybatis3


In the next blog post we will make a detailed comparison between Hibernate and MyBatis.


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.