Basic configuration of MyBatis: entity class, configuration file, mapping file, tool class, Mapper interface

Source: Internet
Author: User

Building projects

One: Lib (Jar package for the framework and database-driven jar package)

1, the first step: first put MyBatis Core class library into Lib

2, Step two: Import a third-party class library (in Lib). The core class library of MyBatis also relies on some third-party class libraries at run time

3, Step three: Import the connection database driver jar Package

Two: Create a mybatis configuration file

1, the first step: to create a physical package, against the table structure to write the entity class . Package is to write Get,set method------Unlike hibernate, you can automatically match the Name field name to the entity class, not your own hand-realistic body class and mapping file

2, the second step: Create an XML file, the file name can be casually written here, refer to Hibernate's canonical wording: Mybatis.cfg.xml

No next is required because MyEclipse does not have a built-in MyBatis document declaration

3, the configuration file consists of four parts:

(1) Configuration log

(2) Configuration type Alias

Alias The classes you use frequently, and use aliases later, to simplify your code---Custom entity class settings aliases

(3) Configuring the database connection and transaction manager

(4) Import the mapping file

The complete configuration file is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration><!--Set Some of the operating parameters of the Mtbatis: log, is directly output to the console or output to the log4j file--><settings><!--name can not be written casually Can only be called this name; value has several options here choose to output--><setting name= "Logimpl" value= "stdout_logging" to the console/></settings><! --Set type alias: If the alias is not set when executing the SQL statement. Each time you specify a package name + class name, a long--><typealiases>< to write!--type is the full entity class name,--><tapealias type= " Cn.bdqn.mybatis.entity.User "alias=" User "/></typealiases><!--the properties of the database connection, different phases of development are connected to different stages of the database development-- Development environment: Connect the Programmer's own database testing phase-test environment: Connect the test database to run on-line-production environment: Connect to the official database you can write multiple environment--><environments default= "Dev" > <!--development environment--><environment id= "Dev" ><!--manage Transactions--><transactionmanager type= "jdbc"/><! through JDBC --Do not use connection pooling--><datasource type= "unpooled" ><property name= "Driver" value= "Com.mysql.jdbc.Driver"/>< Property name= "url" value= "Jdbc:mysql://locAlhost:3306:test "/><property name=" username "value=" Test "/><property name=" password "value=" 123456 "/ ></dataSource></environment></environments><!--path to the SQL mapping file--><mappers><!-- Introduce the SQL file to be loaded--><mapper resource= "Cn/bdqn/mybatis/mapper/user.sql.xml"/></mappers></ Configuration>

                                                   authoring Tool class

Package Cn.bdqn.mybatis.util;import Java.io.ioexception;import Java.io.reader;import Org.apache.ibatis.io.resources;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.ibatis.session.sqlsessionfactorybuilder;public Class Mybatisutil {private static sqlsessionfactory Sessionfactory;static{try {//gets the input stream character stream used to load the configuration file  reader reader= Resources.getresourceasreader ("Mybatis.cfg.xml");//builder, through which Sqlsessionfactorybuilder builder=new Sqlsessionfactorybuilder (); Sessionfactory=builder.build (reader);} catch (Exception e) {e.printstacktrace ();}} public static sqlsession Getsqlsession () {return sessionfactory.opensession (true);}}

Mapping Files

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Cn.bdqn.mybatis.mapper.UserMapper" ><insert id= "adduser  "parametertype=" user " >insert into User (username,password,email) VALUES (#{username},#{password},#{email}) </insert><select id= "GetUser" resulttype= "User" >select ID, Username,password,email from User WHERE id=#{id}</select><select id= "Finduser" resulttype= "User" >SELECT Id,username,password,email from the user ORDER by Id;</select><update id= "UpdateUser" parametertype= "User" > UPDATE User SET Username=#{username},password=#{password},email=#{email} WHERE id=#{id}</update><delete id= "Deluser" >delete from User WHERE id=#{id}</delete></mapper> 

Mapper Interface

Package Cn.bdqn.mybatis.mapper;import Java.util.list;import cn.bdqn.mybatis.entity.user;//invokes the corresponding statement via an abstract method inside the interface interface corresponding to the mapping file----The SQL statement namespace set to the full class name of the interface//equivalent to the original DAO layer, I only need to define the DAO interface, the specific implementation of the class now do not have to write their own, just get Mapper interface class can   addUser (User User);p ublic user getUser (Integer ID);p ublic list<user> finduser ();p ublic int updateUser (user user );p ublic void Deluser (Integer id);}

Test class

The first method of invoking an SQL statement
Save a user
int Rows=session.insert ("User.adduser", user);//Get a user User=session.selectone by ID ("User.getuser", 2);

The second most commonly used method of calling SQL statements is to define a mapper interface    Mapper interface, return value type, parameter, corresponding to; method name consistent with SQL statement ID
Tell the session first, and the following session finds the namespace based on the Mapper class.

Usermapper Mapper=session.getmapper (Usermapper.class);
int Rows=mapper.adduser (user);

Basic configuration of MyBatis: entity class, configuration file, mapping file, tool class, Mapper interface

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.