Spring Integration MyBatis (maven+mysql) Text tutorials detailed _java

Source: Internet
Author: User
Tags db2 tomcat apache tomcat log4j

First, use MAVEN to create a Web project

To complete the integration of spring4.x and mybatis3.x, first review the creation of Web projects and the use of mybatis3.x in a MAVEN environment, and the first to 2nd is mostly to review past content.

1.2, click "File"-> "new"-> "other"-> enter "Maven", a new "Maven Project", as shown in the following figure:

1.2. Please tick "Create a simple project" to create an easy item without using a template. You can also use a template, choose WebApp, but this should not be checked. As shown in the following illustration:

1.3, fill in the package name, project name, select package Type: War, as shown in the following figure:

1.4, after the project is created, you may find that there are errors, select the project, right button "Property properties"-> "Level project Facets"-> "Java" modified version number is 1.7, the default is 1.5; Click "OK" to save and then close. As shown in the following illustration:

1.5. Repeat the previous step, reverse the dynamic Web Module, and temporarily turn the project into a non-WEB project. Click "OK" to save and then close.

1.6, repeat the previous step, and then enter the level of properties, check "Dynamic Web Module" Select version 3.0. Click on the hyperlink in the lower left corner "further Configuration available ...".

1.7, check "Generate web.xml deployment Descriptor" Generate Web.xml Deployment profile. Click "OK" to save and then close.

1.8. Copy the two folders "Meta-inf" and "Web-inf" under the generated WebContent directory to the Src/main/webapp directory.

1.9, delete the WebContent directory.

1.10, the deletion will find the project's Pom.xml file error, because the location can not find the specified Web.xml file caused. Then enter the properties of the project, select the "Deployment Assembly" Project deployment item, delete the "Src/test/java", "src/test/resources" and "webcontent" directories, because these three items do not need to be deployed.

1.11. Click "Add" and select "Folder Folders" to specify the Web content root folder for the project's final deployment results.

1.12, select the Src\main\webapp directory as the target directory, click Finish finished to save and close.

1.13, if the project at this time also reported wrong, casually modify the Pom.xml file after saving should be wrong will disappear.

1.14, in the Src\main\webapp directory to create a new index.jsp file, as a test use.

1.15, the new completed after the discovery of errors, because there is no Java EE Server Runtime caused by the right key properties on the project to select the "Java build Path" Item, click "Add Library ..." to add a reference.

1.16, select the Server runtime item, click "Next Next", then select "Apache Tomcat v7.0", here may be based on their own operating environment to choose, if not the server, you should first integrate Tomcat.

1.17, write the test content in the index.jsp file.

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
  pageencoding=" UTF-8 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
 
 

1.18, on the project right click "Run as"-> "Run on Server" Run the project, the results are as follows.

Second, use MyBatis to complete MySQL database access

2.1. Add dependencies

To complete the use of MyBatis access to the MySQL database, you need to add some dependency packs, including MYBATIS3, connection Drive, junit,log4j2, and so on. Can go to the shared repository search, the first site address is: http://mvnrepository.com/, here to search the connection driver as an example, the results of the search after the 5.xx version of many, there are 6.xx version, but do not recommend the use of 6.XX version, because MYBATIS3 does not support.

We chose 5.1.38 in version 5.0 to copy the dependency information of Maven to the Pom.xml dependencies node in the project

Of course also can go to another website: http://search.maven.org/, here take log4j for example search as follows:

Some dependencies can also go directly to the official website to find, such as MYBATIS3:

The Pom.xml documentation for the project 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.zhangguo</groupId> <artifactId> Spring061</artifactid> <version>0.0.1</version> <packaging>war</packaging> < dependencies> <dependency> <groupId>mysql</groupId> <artifactid>mysql-connector
      -java</artifactid> <version>5.1.38</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <ve rsion>2.6.1</version> </dependency> <dependency> <groupid>org.mybatis</groupid > <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </d Ependencies> </project>

Reference Result:

If the network is not stable, the download package is likely to fail, you can try to force the project to be downloaded, you can use the Download tool to copy the jar package download back to the local repository.

2.2. Prepare data

Open the MySQL database and create a table, taking the Booktypes table as an example.

The SQL script is as follows:

/* Navicat MySQL Data Transfer source server:localhost source Server version:50536 Source Host:localhost: 3306 Source database:db2 target server type:mysql target server version:50536 File encoding:65001 Date:

2016-07-04 10:49:56 */SET foreign_key_checks=0; --------------------------------Table structure for ' booktypes '------------------------------DROP Table IF EXISTS ' b
Ooktypes ';  CREATE TABLE ' booktypes ' (' id ' int (one) not NULL auto_increment COMMENT ' type number ', ' typeName ' varchar () NOT NULL COMMENT

' Type name ', PRIMARY KEY (' id ')) engine=innodb auto_increment=94 DEFAULT Charset=utf8; --------------------------------Records of booktypes------------------------------INSERT into ' booktypes ' VALUES (' 1
', ' computer software development ');
INSERT into ' booktypes ' VALUES (' 2 ', ' Computer network Engineering ');
INSERT into ' booktypes ' VALUES (' 3 ', ' mythological novel ');
INSERT into ' booktypes ' VALUES (' 4 ', ' science Fiction ');
INSERT into ' booktypes ' VALUES (' 5 ', ' foreign language '); INSERT into ' booktypes ' VALUES (' 6 ', ' Test type');
INSERT into ' booktypes ' VALUES (' 7 ', ' 91 ');
INSERT into ' booktypes ' VALUES (' 8 ', ' 92 ');
INSERT into ' booktypes ' VALUES (' 9 ', ' 93 ');
INSERT into ' booktypes ' VALUES (' 91 ', ' architectural design ');
INSERT into ' booktypes ' VALUES (' 92 ', ' industrial design '); INSERT into ' booktypes ' VALUES (' 93 ', ' ship made ');

2.3. Create Java Bean

Add the class BookType type under the package com.zhangguo.Spring61.entities.

Package com.zhangguo.Spring61.entities;
/**
 * * *
 /Public
class BookType {
  /**
   * *
  ID/private int IDs;
  /**
   * Type name
   *
  /private String typeName;
  public int getId () {return
    ID;
  }
  public void setId (int id) {
    this.id = ID;
  }
  Public String Gettypename () {return
    typeName;
  }
  public void Settypename (String typeName) {
    this.typename = typeName;
  }

2.4, create the instance and table mapping file

This is done in the form of an interface +xml, and the BookType data access interface is as follows:

Package com.zhangguo.Spring61.mapping;
Import java.util.List;
Import Com.zhangguo.Spring61.entities.BookType;
/**
 * Book type data access interface
 */public
interface Booktypedao {
  *
   * * Access to all book types
  * * Public list<booktype> getallbooktypes ();
}

Booktypemapper.xml files are as follows:

<?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" >
<!--namespace should be the package name of the corresponding interface + class name-->
<mapper namespace= "Com.zhangguo.Spring61.mapping.BookTypeDAO" >
  <!--ID should be a method in the interface, and the result type should use full name-->
  <select id= "getallbooktypes" resulttype= "BookType"
    if no alias is configured Select Id,typename from Booktypes
  </select>
</mapper>

2.5. Create mybatiscfg.xml files

The Mybatiscfg.xml file is used to configure the MyBatis operating environment as follows:

<?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" > & lt;configuration> <!--Specify the location of the database connection information--> <properties resource= "Db.properties" ></properties> < !--type alias, the default is to introduce all classes under Com.zhangguo.Spring61.entities--> <typeAliases> <package name= "com.zhangguo.Spring61 . Entities "/> </typeAliases> <environments default=" Development "> <environment id=" Development "&G
      T <transactionmanager type= "JDBC"/> <datasource type= "Pooled" > <property name= "Driver" ${driver} "/> <property name= url" value= "${url}"/> <property name= "username" value= "${userna" Me} "/> <property name= password" value= "${password}"/> </dataSource> &LT;/ENVIRONMENT&G
  T </environments> <mappers> <!--introducing mapping files--> <mapper ResourCe= "Com/zhangguo/spring61/mapping/booktypemapper.xml"/> </mappers> </configuration> 

Because the configuration relies on the Db.properties file, the file is used to specify the connection information for the database, as follows:

Driver=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/db2
username=root
password=root

2.6. Realize data access function

For more convenient multiplexing MyBatis implementation of data Access does not require frequent creation of sqlsessionfactory and Sqlsession objects, encapsulating a Mybatisutil tool class as follows:

Package Com.zhangguo.Spring61.dao;
Import Java.io.InputStream;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;
Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;
  Public abstract class Mybatisutil {//gc static private static sqlsessionfactory factory=null; public static Sqlsessionfactory Getsqlsessionfactory () {if (factory==null) {//Get environment Profile Stream InputStream config = M
    YBatisUtil.class.getClassLoader (). getResourceAsStream ("Mybatiscfg.xml");
    Create SQL Session Factory factory = new Sqlsessionfactorybuilder (). build (config);
  return factory;
  //Get session public static Sqlsession GetSession () {return getsqlsessionfactory (). Opensession (True);
   /** * Obtains SQL session * @param Isautocommit is automatically submitted, if False requires Sqlsession.commit (); rollback (); * @return SQL Session */public static sqlsession GetSession (Boolean isautocommit) {return getsqlsessionfactory (). Opens
  Ession (Isautocommit); }
}

Create the Class Booktypedaoimpl implementation interface Booktypedao, here to achieve through the MyBatis data access function, the contents are as follows:

Package Com.zhangguo.Spring61.dao;
Import java.util.List;
Import org.apache.ibatis.session.SqlSession;
Import Com.zhangguo.Spring61.entities.BookType;
Import Com.zhangguo.Spring61.mapping.BookTypeDAO;
/**
 * realizes book type data access
 */public
class Booktypedaoimpl implements Booktypedao {
  @Override
  Public list<booktype> getallbooktypes () {
    //Get Session Object
    sqlsession session=mybatisutil.getsession ();
    try {
      ///Booktypedao the interface through MyBatis, and returns the instance
      Booktypedao booktypedao=session.getmapper (booktypedao.class);
      return Booktypedao.getallbooktypes ();
    } finally {
      session.close ();}}}

Third, the use of spring4.x integration mybatis3.x

The above is a small series to introduce the spring integration MyBatis (maven+mysql) graphics and text tutorials, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.