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

Source: Internet
Author: User

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

In the Java world, the frame of contention may be more interesting than the change in language itself. In recent years, SPRINGMVC, with its simplicity and portability, high development efficiency and seamless integration with the spring framework, has gradually defeated its predecessor, STRUTS/STRUTS2, as the most commonly used web framework. and MyBatis relative to hibernate, also has the advantages of simple development, high efficiency, and the controllability of 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 frame combinations.

A good framework can help us simplify development, but the actual work is still a lot of time spent in the compilation, testing, packaging, deployment and other building work, even if the IDE becomes more and more powerful, but these work still need us to step-by-step operation, and not become automated pipeline operations. Repeating these steps every day and every project is meaningless, so we need to build tools for help. There are not many options for building tools, and Maven is now the mainstream choice to help developers automate builds, standardize structures, manage dependencies, and much more efficiently outside of the code.

The combination of Maven, SPRINGMVC, and MyBatis is elegant and powerful, but for beginners, integrating the three is not a simple matter. In this paper, the complex process is disassembled, starting from the most basic steps, one step at a to support the increase, delete, change, paging Query Web project.

This article takes eclipse as the development tool and needs to install 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

The following officially begins.

Open Eclipse, click File-New, Maven Project


This step does not make any changes, direct next



Next, choose Archetype. MAVEN advocates an agreement over configuration, with established rules for the source code directory structure, configuration file location, test user directory, and so on. The benefit of following these rules is that the project structure created by different developers is consistent, reducing the additional familiarity and learning costs when adding new projects.

MAVEN's many built-in archetype can help developers quickly outline the skeleton of a project for different types of projects, such as a Web project that can choose Maven-archetype-webapp, an automatically created directory that includes WebApp, and more. From the beginning of the most basic, choose Maven-archetype-quickstart, other options remain the same, click Next.



This step fills in the basic information of the project. The Group ID and artifact ID are used to label the coordinates of the project or module, one of MAVEN's major functions is management dependencies (jar packages), there are thousands of open source projects in Maven's central repository, and finding the required project files in the warehouse requires assigning a unique identity to each project. The Group ID is used to define the current project, under which each item can be divided into multiple modules, and the Artifact ID defines the specific module. For example, the group ID of the spring project is Org.springframework, which divides the artifact ID into Spring-core, spring-context, SPRING-JDBC, and so on.

Enter the group ID and artifact ID and click Done. The resulting project structure after completion is as follows:


By default, the Src/main and src/test two folders are generated, according to the Convention, main puts the project source code, and the test directory places the testing case. The default also generates two demo files (App.java and Apptest.java) that can be deleted directly.

In this example we use MyBatis to operate the MySQL database and use spring integration, which requires adding dependencies, the jar package. With MAVEN, developers no longer have to go to individual websites to download files, 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= "Http://www.w3.org/2001/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</artifactId>< version>3.8.1</version><scope>test</scope></dependency></dependencies></ Project> 
Where the content of the,<dependencies> node is dependent, archetype added junit-3.8.1 by default, we need to add spring, Mybatis, MySQL driver, etc., after the completion of the code as follows

...<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>< Version>4.12</version><scope>test</scope></dependency><dependency><groupid >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><artifactid>spring-context</artifactid><version>${ Springframework.version}</version></dependency><dependency><groupid>org.springframework</groupid><artifactid>spring-beans</ Artifactid><version>${springframework.version}</version></dependency><dependency> <groupid>org.springframework</groupid><artifactid>spring-jdbc</artifactid><version >${springframework.version}</version></dependency><dependency><groupid>c3p0</ Groupid><artifactid>c3p0</artifactid><version>0.9.1.2</version></dependency> <dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId>< Version>3.4.1</version></dependency><dependency><groupid>org.mybatis</groupid ><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency> <dependency><groupid>mysql</groupid><artifactid>mysql-connector-java</artifactid ><version>5.1.18&lT;/version></dependency></dependencies></project> 

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

Now that the MAVEN configuration is complete, the MyBatis section begins below.

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

Build 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 is not NULL,  PRIMARY KEY (' p_id ')) ENGINE = innodbdefault CHARACTER SET = UTF8;
MyBatis as an ORM framework, the role here is to map the operation of the T_product table into the operation of the Java class, according to the Convention, we need to encode three files:

Product.java-Mapping entity classes

Productmapper.java-Interface, defining callable methods

Product.xml-Actual execution of the SQL mapping file

The directory structure after adding the code file is as follows:


The code for the 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 in T 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=" id "/><result column=" p _name "property=" name "/><result column=" P_price "property=" Price "/></resultmap><insert id=" Addproduct "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 Productmapper.java, the parameter type is an instance of product, the database self-increment field is used, and the self-increment value is bound to the id attribute. The select element is matched by a SELECTBYID,RESULTMAP element that defines the correspondence between the fields and the properties of the product class.

The code does not generate an implementation class for Productmapper, but instead dynamically creates a proxy class during runtime to complete the instantiation.

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

If you use only MyBatis (instead of spring), add the MyBatis profile to set up the database connection, and so on, but instead of doing this, use spring to take over, So the next code is the spring core configuration file Applicationcontext.xml. Note Here is used for testing, so the file will be added in the Src/test/java directory.

Applicationcontext.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 "xmlns:jdbc=" Http://www.springframework.org/schema/jdbc "xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema/cont Ext 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 "><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= " Maxpoolsize "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>

Where 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 under Src/test/java Com.example.petstore.test.ProductTest.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 {@Autowiredprivate productmapper Productmapper; @Testpublic void Insertandselect () {Product product1 = new Product ();p roduct1.setname ("Tom"); Product1.setprice (99.9f);p roductmapper.addproduct (product1) asserttrue (Product1.getid () > 0); Product product2 = Productmapper.selectbyid (Product1.getid ()); Asserttrue (Product2.getid () = = Product1.getid ()); Asserttrue (Product2.getname (). Equals (Product1.getname ()));}}
Finished, all the code in this section has been written, and the following directory structure is completed:


Run for a look, on the Producttest.java. Right-click Run as, Junit Test


Test through, look at the contents of the database:


Summarize

The example above completes the creation of simple projects through MAVEN, insert and read operations on database tables, although it is not practical, but it also provides insight into the basic usage of mybatis and how it is integrated with spring.

The project is packaged as a jar package for publication, which facilitates code reuse, but obviously no longer increases the content of the Web Part. The traditional approach is to build a different Web project and reference this project, but we will then use Maven's aggregation and inheritance capabilities to build an aggregation project that includes a database persistence layer module and a SPRINGMVC-based Web module, which is described in the next section.


This article source code download

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

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.