A tutorial on the development environment of Windows Java+mybatis Framework +mysql _java

Source: Internet
Author: User
Tags datetime generator stub

MyBatis is a Java Persistence framework that associates an object with a stored procedure or SQL statement through an XML descriptor or annotation.

MyBatis is free software distributed under Apache License 2.0, and is a branch version of Ibatis 3.0. Its maintenance team also includes Ibatis's start-up members.
Unlike other object-relational mapping frameworks, MyBatis does not associate Java objects with database tables, but instead associates Java methods with SQL statements. MyBatis allows users to take full advantage of the various functions of a database, such as stored procedures, views, complex queries, and proprietary features of a database. MyBatis is a good choice if you want to manipulate legacy databases, irregular databases, or to fully control the execution of SQL.

Compared to JDBC, MyBatis simplifies related code: SQL statements can be executed in one line of code. MyBatis provides a mapping engine that declaratively maps the results of SQL statement execution to the object tree. SQL statements can be generated dynamically by using a built-in class XML expression language, or by using Apache velocity-integrated plug-ins.

MyBatis integrates with the spring framework and Google Guice, which keeps developers from dependency issues.

The MyBatis supports declarative data caching (declarative-caching). When an SQL statement is marked as cacheable, all data obtained from the database when it is first executed is stored in a cache, and subsequent execution of the statement reads the result from the cache instead of hitting the database again. MyBatis provides default Java-HashMap cache implementations and default connectors for connections to Oscache, Ehcache, Hazelcast, and memcached. MyBatis also provides APIs for use by other cache implementations.

Points
This period of time to learn, in fact, the main process for MyBatis can not be the following steps

1. Get the sessionfactory from the XML configuration file and then generate the corresponding session by Sessionfactory.

2. It is to use the session object to complete the corresponding CRUD operation of the business data (increase the check) and the corresponding transaction control.

3. Close the session after use to avoid excessive resource consumption

4. Using the corresponding mapper XML file for the JavaBean of the business entity and the corresponding map operation between the database tables

Pre-war preparation:

1. Development environment Eclipse Java EE ide,jdk 1.6, database MySQL 5.5

2. Download the corresponding jar package for later use

Mybatis-3.2.3.zip unpack and take out mybatis-3.2.3.jar,=> download address: http://code.google.com/p/mybatis/(MyBatis core package)

Mybatis-generator-core-1.3.1.jar => Download Address: Http://code.google.com/p/mybatis/wiki/Generator (MyBatis automatically generate configuration packages)

Mysql-connector-java-5.1.26-bin.jar => Download Address: http://dev.mysql.com/downloads/connector/j/(JDBC driver package for MySQL)

Build steps 

And then you can build a Java project project named Mybatisdemo below, and create a new package structure and folder structure as shown in the following figure, where config and mapper are folders, respectively.

Package David.mybatis.demo and Packet David.mybatis.model under the corresponding demo run program and JavaBean object, Lib folder to store just download the several third-party jar packages.

After building the following directory, we can add the corresponding jar package, as shown below

When finished, execute the following SQL, build the table structure required for demo, there are 3 tables, Visitor (visitor table), Website (website table), Channel (channel table)

/* Creates visitor*/create
TABLE Visitor
(
  Id INT (one) not NULL auto_increment,
  Name VARCHAR (1000) Not null,< C5/>email VARCHAR (1000) not null,
  Status INT not null DEFAULT 1,
  createtime DateTime,
  PRIMARY KEY (Id)
) c10/>/* Create Web Site Table * *
/CREATE TABLE Website
(
  Id INT not NULL PRIMARY KEY auto_increment,
  Name VARCHAR (1000 Not NULL,
  VisitorID int REFERENCES Visitor (Id),
  Status INT not null DEFAULT 1,
  createtime DateTime

* * Create a channel table
/created table Channel
(
  Id INT not NULL PRIMARY KEY auto_increment,
  Name VARCHAR ( 1000) not NULL,
  WebSiteID int REFERENCES Website (Id),
  Status INT not null DEFAULT 1,
  createtime datetime
   )

When all this is done, we're going to start doing it.

As the beginning says, all of MyBatis's configurations are based on an XML configuration file, and we need to create a new configuration file named Mybatis_demo_config.xml under the Config folder, one of the core of what we need to do later.

In the configuration of this file must be noted that the elements in the <configuration> node are hierarchical order requirements, can not change the order at random, otherwise the XML configuration file will be loaded when the exception occurs, resulting in subsequent operations unsuccessful.

The specific node shows that you can view http://mybatis.github.io/mybatis-3/zh/configuration.html#, here only the more commonly used nodes, typealiases,environments, Mappers.

1. typealiases => alias node, you can set this node's properties so that other places in the configuration file that require an entity name can use this alias instead of the fully qualified name

For example <typealias type= "David.mybatis.model.Visitor" alias= "Visitor"/>

2. Environments => Environment node, configure data connection related information

3. Mappers => Configure SQL mapping statements.

The simplest configuration is 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> <typeAliases> <typealias type= "David.mybatis.model.Visitor" alias= "Visitor"/> &L t;/typealiases> <environments default= "Development" > <environment id= "Development" > <transac Tionmanager type= "JDBC" ></transactionManager> <datasource type= "Pooled" > <property name= "D
        River "Value=" Com.mysql.jdbc.Driver/> <!--? Useunicode=true&characterencoding=utf8 to support Chinese insert--> <property name= "url" value= "jdbc:mysql://127.0.0.1:3306/mybatis_db?useunicode=true&characterencoding= UTF8 "/> <property name=" username "value=" root "/> <property name=" password "value=" 123456 "/&
      Gt
</dataSource> </environment> </environments> <mappers>    <mapper resource= "Mapper/visitormapper.xml"/> </mappers> </configuration>

 

Create a new Mybatisutils class under Package David.mybatis.demo, which stores the method of obtaining sqlsession and closing sqlsession, and refines it for multiple reuse.

Package David.mybatis.demo;
Import Java.io.InputStream;
Import org.apache.ibatis.io.Resources;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;

Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;

Import David.mybatis.model.CRUD_Enum;

  public class Mybatisutils {private static final String Config_path = "Config/mybatis_demo_config.xml";
    * * Get the database access link */public static sqlsession getsqlsession () {sqlsession session = NULL;
      try {InputStream stream = Resources.getresourceasstream (Config_path); You can read the corresponding database environment//sqlsessionfactory factory = new Sqlsessionfactorybuilder () based on the configured environment. Build (//Stream, "devel 
      Opment ");
      Sqlsessionfactory factory = new Sqlsessionfactorybuilder (). Build (stream);
    Session = Factory.opensession ();
    catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
  return to session; * * * Get database access link * * public static void CloseSession (Sqlsession session) {session.close (); /* * Return action logging message/public static void Showmessages (crud_enum type, int count) {switch (type) {case Add:System.out.println ("added + Count +") record.
      ");
    Break Case Delete:System.out.println ("the + Count +" record was deleted.)
      ");
    Break Case Update:System.out.println ("updated" + Count +) record.
      ");
    Break Case Query:System.out.println ("matches the + Count +" bar record.)
      ");
    Break Case List:System.out.println ("a total of + count +" records.)
      ");
    Break
    Default:break;

 }
  }
}

Create a new class named visitor under Package David.mybatis.model that is used to make the appropriate or Mapping.

Package David.mybatis.model;
Import Java.text.SimpleDateFormat;

Import Java.util.Date;
  public class Visitor {private int id;
  private String name;
  Private String Email;
  private int status;

  Private Date Createtime;
  Public Visitor () {//TODO auto-generated constructor stub createtime = new Date ();
    Public Visitor (string name, string email) {this.name = name;
    This.email = email;
    This.status = 1;
  This.createtime = new Date ();
  public int getId () {return id;
  public void SetName (String name) {this.name = name;
  Public String GetName () {return name;
  public void Setemail (String email) {this.email = email;
  Public String Getemail () {return email;
  Public Date Getcreatetime () {return createtime; @Override public String toString () {//TODO auto-generated Method stub return String.Format ("{Id:%d, Name :%s, Createtime:%s} ", ID, name, new SimpleDateFormat (" YYyy-mm-dd HH:mm:ss "). Format (createtime));

 }
}

Create a new Visitormapper.xml under package David.mybatis.demo to map the corresponding SQL statement.

Notice here namespace=>david.mybatis.demo.ivisitoroperation must be with the actual filename below the package, ivisitoroperation otherwise the corresponding mapping file cannot be loaded successfully

<mapper namespace= ' david.mybatis.demo.IVisitorOperation ' >
  <select id= ' basicquery ' parametertype= ' int "Resulttype=" Visitor >
    select * from Visitor where id=#{id} and status>0 ORDER by
    ID
  </select>< C5/></mapper>

Next, run the following program

 public static void testbasicquery (int id) {
    sqlsession session = Mybatisutils.getsqlsession ();
    try {
      Visitor Visitor = (Visitor) session.selectone ("David.mybatis.demo.IVisitorOperation.basicQuery", id);
      Mybatisutils.closesession (session);
      System.out.println (visitor);
    } catch (Exception e) {
      //Todo:handle Exception
    }
  }

One of the simplest execution results.

This is the helloword~ of the MyBatis series.

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.