Start from scratch build Springmvc+mybatis project based on MAVEN (1)

Source: Internet
Author: User
Tags constant

Technology has evolved rapidly, and many of the once dominant pop technologies have been replaced by emerging technologies in just a few years.

In the Java world, framing battles may be more interesting than the changes in language itself. In recent years, SPRINGMVC, with its simplicity and portability, high development efficiency and seamless integration with spring framework, has gradually defeated predecessor Struts/struts2 and become the most common web framework. and MyBatis relative to hibernate, also has the advantage of simple development, high efficiency, and the control of the SQL better, conducive to performance tuning, and gradually accumulated a challenge hibernate strength and popularity.

The current springmvc+mybatis has become one of the most popular framework combinations.

A good framework can help us simplify development, but there is still a lot of time in the work of compiling, testing, packaging, deploying, and so on, even if the IDE becomes more and more powerful, the work still needs to be done step-by-step instead of becoming an automated pipelined operation. It makes no sense to repeat these steps every day, every project, so we need help building tools. There is not much selectivity in building tools, and Maven is now the mainstream choice, which helps developers automate building, standardizing structures, managing dependencies, and so on, greatly improving productivity beyond code.

The combination of Maven, SPRINGMVC, and MyBatis is elegant and powerful, but for beginners it is not easy to integrate the three together. In this paper, the complex process of dismantling, starting from the most basic steps, a step-by-step to build a support to add, delete, change, paging query Web projects.

This article takes eclipse as a development tool and needs to install the MAVEN and MAVEN integration for Eclipse Plug-ins, and the database uses MySQL.

If you have not installed Maven, you can refer to:

http://blog.csdn.net/autfish/article/details/51008788

Here's the official start.

Open Eclipse, click File-> New-> Maven Project


This step does not make any changes directly to the next



The next step is to select archetype. MAVEN advocates conventions over configuration, with established rules for source directory structure, configuration file location, test user directory, and so on. The benefit of following these rules is that different developers build a consistent project structure that reduces the additional familiarity and learning costs of adding new projects.

A variety of archetype built into Maven can help developers quickly sketch out the skeleton of a project for different types of projects, such as Web projects that can choose Maven-archetype-webapp, and automatically build directories including WebApp. Here from the most basic start, choose Maven-archetype-quickstart, other options remain unchanged, click Next.



In this step, complete the basic information for the project. The Group ID and artifact ID are used to mark the coordinates of the project or module, one of the main functions of MAVEN is management dependency (jar package), there are thousands of open source projects in Maven's central warehouse, and the required project files in the warehouse need to assign a unique identity to each project. The Group ID is used to define the current project, each of which may divide multiple modules by function, and the artifact ID defines the specific module. For example, the group ID for the spring project is Org.springframework, which divides the artifact IDs into modules such as Spring-core, Spring-context, Spring-jdbc, and more.

Enter the group ID and artifact ID and click Finish. The project structure that is generated after completion is as follows:


Src/main and src/test Two folders are generated by default, and by convention, main places the source code for the project, and the test directory places the testing cases. The default also generates two demo files (App.java and Apptest.java) that can be deleted directly.

In this example we use MyBatis to manipulate the MySQL database and use spring integration, which requires adding dependencies, the jar package. With MAVEN, developers no longer need to download files to each Web site, but only need to configure Pom.xml. Open Pom.xml, the default code is as follows:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= Xmlschema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/
	Maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>petstore</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar </packaging> <name>petstore</name> <url>http://maven.apache.org</url> < Properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties > <dependencies> <dependency> <groupId>junit</groupId> <artifactid>junit</ar tifactid> <version>3.8.1</version> <scope>test</scope> </dependency> </depend Encies> </project> 
Where the content of the,<dependencies> node is dependent, archetype by default added junit-3.8.1, we need to add spring, MyBatis, MySQL driver, etc., complete the following code

... <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < Springframework.version>4.2.6.release</springframework.version> </properties> <dependencies > <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <ver sion>4.12</version> <scope>test</scope> </dependency> <dependency> <groupid& Gt;org.springframework</groupid> <artifactId>spring-test</artifactId> <version>${
			springframework.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version >${springframework.version}</version> </dependency> <dependency> <groupId> Org.springframework</groupid> &LT;ARTIFACTID&GT;SPRING-CONTEXT&Lt;/artifactid> <version>${springframework.version}</version> </dependency> <dependency > <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <ver sion>${springframework.version}</version> </dependency> <dependency> <groupId> Org.springframework</groupid> <artifactId>spring-jdbc</artifactId> <version>${ springframework.version}</version> </dependency> <dependency> <groupid>c3p0</groupid&
			Gt <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> < dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <versio n>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> ;artifactid>mybatis-spring</artifactid> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <ar
	Tifactid>mysql-connector-java</artifactid> <version>5.1.18</version> </dependency> </dependencies> </project>

Note that there is a trick here where spring has multiple modules and uses the same version number, so a <springframework.version> attribute constant is set, and if you need to modify the version you only need to modify the constant value here.

With the MAVEN configuration complete, the MyBatis section begins below.

The function to implement in this example is very simple, based on the relational database for a product to insert and query management, the product has only the name and price two attributes. First, prepare the database.

Build the Library:

CREATE SCHEMA ' petstore ' DEFAULT CHARACTER SET UTF8 COLLATE utf8_bin;
Build table:

CREATE TABLE ' Petstore '. ' T_product ' (
  ' p_id ' INT not null auto_increment,
  ' p_name ' VARCHAR ' (=) not null,
  ' P_ Price ' FLOAT not NULL,
  PRIMARY KEY (' p_id '))
ENGINE = InnoDB
DEFAULT CHARACTER SET = UTF8;
MyBatis as an ORM framework, where the role is to map the operation of the T_product table to the Java class operation, according to the Convention, we need to encode three files:

Product.java-Mapping entity classes

Productmapper.java-interfaces, defining callable methods

Product.xml-the SQL map file actually executed

The directory structure after adding code files is as follows:


The code for three files is as follows:

Product.java

Package Com.example.petstore.model;

public class Product {

	private int id;
	private String name;
	private float price;

	public int getId () {return
		ID;
	}
	public void setId (int id) {
		this.id = ID;
	}
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	public float GetPrice () {return price
		;
	}
	public void Setprice (float price) {
		This.price = Price;
	}
}
Productmapper.java

Package Com.example.petstore.model;

Public interface Productmapper {

	void addproduct (product product);
	
	Product Selectbyid (int id);
}
Product.xml

<?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.example.petstore.model.ProductMapper" > <resultmap type= " Com.example.petstore.model.Product "id=" Productmap "> <id column=" p_id "property=" IDs "/> <result column=" p _name "property=" name "/> <result column=" P_price "property=" price "/> </resultMap> <insert id=" ad Dproduct "parametertype=" com.example.petstore.model.Product "usegeneratedkeys= true" keyproperty= "id" > Insert Into T_product (P_name,p_price) VALUES (#{name},#{price}) </insert> <select id= Selectbyid "Parametertype=" int "resulttype=" com.example.petstore.model.Product "resultmap=" Productmap "> select * from T_product where p_id=#{ ID} </select> </mapper> 
As you can see, Product.java and Productmapper.java are very common and do not have any content associated with database operations. The key code is in Product.xml, where the ID of the Insert element indicates that its matching method is the Addproduct method in the Productmapper.java, the parameter type is an instance of product, the database self-adding field is used, and the self added value is bound to the id attribute. The select element matches a method where the Selectbyid,resultmap element defines the corresponding relationship between the field and the attributes of the product class.

The Productmapper implementation class is not generated in the code, but the proxy class is dynamically created during runtime to complete the instantiation.

Here the MyBatis code has been developed, but we also want to know if the code works, and you need to write some test cases.

If you are using MyBatis only (instead of spring), add the MyBatis profile settings database connection, and so on, but instead of doing this here, spring takes over, So the next code is the spring core configuration file Applicationcontext.xml. Note that this is used for testing, so the file will be added to the Src/test/java directory.

Applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:jdbc=" Http://www.springframework.org/schema/jdbc "xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema/co ntext http://www.springframework.org/schema/context/spring-context-3.0.xsd Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/ JDBC Http://www.springframework.org/schema/jdbc/spring-jdbc-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.springframework.org/schema/aop/spring-aop-3.0.xsd "&GT <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method= "Close" > <property Name= "Driverclass" value= "Com.mysql.jdbc.Driver"/> <property name= "Jdbcurl" value= "Jdbc:mysql://localhost" : 3306/petstore?useunicode=true&characterencoding=utf8 "/> <property name=" user "value=" root "/> < Property name= "Password" value= "root123456"/> <property name= "minpoolsize" value= "2"/> <property name= "m Axpoolsize "value=" "/> </bean> <bean id=" sqlsessionfactory "class=" Org.mybatis.spring.SqlSessionFactoryBean "> <property name=" dataSource "ref=" DataSource "/> <property Name= "Mapperlocations" value= "Classpath*:com/example/petstore/model/*.xml"/> </bean> <bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "> <property name=" basepackage "value=" Com.example.petstore.model "/> </bean> </beans>

In which, the database connection string and user name, password is my test machine settings, you need to change according to your environment. Then the test case, add the class Com.example.petstore.test.ProductTest.java under Src/test/java

Package com.example.petstore.test;

Import static org.junit.assert.*;
Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.test.context.ContextConfiguration;

Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
Import com.example.petstore.model.Product;

Import Com.example.petstore.model.ProductMapper;
@RunWith (Springjunit4classrunner.class) @ContextConfiguration (locations = "Classpath:applicationContext.xml")
	
	public class Producttest {@Autowired private productmapper productmapper;
		@Test public void Insertandselect () {Product Product1 = new product ();
		Product1.setname ("Tom");
		Product1.setprice (99.9f);
		Productmapper.addproduct (PRODUCT1);
		
		Asserttrue (Product1.getid () > 0);
		Product product2 = Productmapper.selectbyid (Product1.getid ());
		Asserttrue (Product2.getid () = = Product1.getid ());
	Asserttrue (Product2.getname (). Equals (Product1.getname ()));
}} 
Done, all the code in this section is written, and the completed directory structure is as follows:


Run a look at the Producttest.java right click-> Run as-> Junit Test


Test through, and take a look at what's in the database:


Summarize

The example above completes the creation of a simple project through MAVEN, insert and read operations on a database table, although it is not practical, but it is also possible to understand the basic usage of mybatis and how to integrate with spring.

The project is packaged and published as a jar package, which is good for code reuse, but obviously no longer adds content to the Web Part. The traditional approach is to build a new Web project and reference this project, but we will then build an aggregation project that includes a database persistence layer module and an SPRINGMVC Web module, as described in the next section, using Maven's aggregation and inheritance capabilities.


This article source code downloads


Start from scratch build Springmvc+mybatis project based on MAVEN (1)
Start from scratch build Springmvc+mybatis project based on MAVEN (2)
Start from scratch build Springmvc+mybatis project based on MAVEN (3)
Start from scratch build Springmvc+mybatis project based on MAVEN (4)

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.