inotgo.com

Download area
File name File size
lib.rar 1m
mybatis.rar 1m
Use the webmaster secret download tool

Tool version compatibility problem
We usually use JDBC Access the database , In addition to writing it yourself SQL outside , You must also operate Connection, Statement, ResultSet These are actually auxiliary classes of means . More Than This , Access different tables , And write a lot of the same code , It seems cumbersome and boring .

So it's used Mybatis Then , Just provide yourself SQL sentence , Other work , Such as establishing a connection ,Statement, JDBC Relevant exception handling and so on are handed over to Mybatis I did , The repetitive work Mybatis Also done , We only need to focus on the operation level of addition, deletion, modification and query , The technical details are encapsulated in places we can't see .

Must read : Framework based programs run successfully , For JAR Package version , The correctness of the configuration file has strict requirements , Anything goes wrong , Will cause the framework program to fail . If you are learning this framework for the first time , Be sure to follow the instructions of the tutorial strictly , Completely imitate the operation , Until you successfully see the running effect . After the first success , Confidence , Ideas will have a better cushion , Then according to their doubts , stay “ success ” Make the desired changes and adjustments to your code , This can greatly save learning time , increase of efficiency , Don't change it at once , Create obstacles to your learning
Correct

Step 1 : Look at the effect before learning   
Step 2 : Create database   
Step 3 : Create table   
Step 4 : Import data   
Step 5 : Run... First , See the effect , Learn again   
Step 6 : Imitation and troubleshooting   
Step 7 : Create project   
Step 8 : Import jar Bag   
Step 9 : Create an entity class   
Step 10 : Configuration file mybatis-config.xml   
Step 11 : Configuration file Category.xml   
Step 12 : Test class TestMybatis   
Step 13 : Basic schematic diagram   
Step 14 : Runnable project   
Step 15 : practice   

Step 1 :

Look at the effect before learning

edit top fracture
These two pieces of data are through mybatis From the database
 Look at the effect before learning
First create the database how2java
If the database is not installed , Please refer to Install mysql-server
create database how2java
create database how2java
Then create the table category_
USE how2java; CREATE TABLE category_ ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(32) DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
USE how2java;

CREATE TABLE category_ (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(32) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
USE how2java; INSERT INTO category_ VALUES (null,'category1'); INSERT INTO category_ VALUES (null,'category2');
USE how2java;
INSERT INTO category_ VALUES (null,'category1');
INSERT INTO category_ VALUES (null,'category2');
Step 5 :

Run... First , See the effect , Learn again

edit top fracture
First download the runnable project in the upper right corner , Configure to run , After confirming availability , Then learn what steps have been taken to achieve this effect .
Step 6 :

Imitation and troubleshooting

edit top fracture
After ensuring that the runnable project can run correctly , Then strictly follow the steps in the tutorial , Imitate the code again .
The imitation process inevitably has code differences , As a result, the expected operation results cannot be obtained , At this moment, by comparison The correct answer ( Runnable project ) And your own code , To locate the problem .
In this way , Learning is effective , Troubleshooting is efficient , It can obviously improve the learning speed , Across all the barriers on the way to learning .

It is recommended to use diffmerge Software , Compare folders . Put your own project folder , Compare with my runnable project folder .
This software is awesome , You can know which two files in the folder are wrong , And clearly marked
Here is a green installation and use tutorial : diffmerge Download and use tutorials
Through ecipse establish java project: mybatis
Project directory It must be e:\project\mybatis
Because the follow-up study is based on this position , And... In the runnable project downloaded at the top right jar The package dependency location is also here , So be sure to use this project directory , It helps to improve the learning efficiency in the process of using this tutorial .
Using other project locations will cause unnecessary trouble
 Create project
This project uses two jar Bag , In the upper right corner lib.rar Download .
Download and unzip , In the project directory e:/project/mybatis Create a new directory lib, And copy it
Then pass ecipse stay mybatis Import these two... On your project jar Bag
 Import jar Bag
Prepare entity classes Category, Used for mapping tables category_
package com.how2java.pojo; public class Category { private int id; private String name; 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; } }
package com.how2java.pojo;

public class Category {
	private int id;
	private String name;
	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;
	}
	
}
Step 10 :

Configuration file mybatis-config.xml

edit top fracture
stay src Create... Under the directory mybatis Main configuration file for mybatis-config.xml ( amount to hibernate.cfg.xml, without hibernate Please ignore this sentence ).
Its main function is to provide drivers for connecting to the database , Database name , Coding method , Account and password

<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>


And aliases , Auto scan com.how2java.pojo Type under , So that in the follow-up Configuration file Category.xml Used in resultType When I was , Can be used directly Category, You don't have to write it all com.how2java.pojo.Category

<typeAliases>
<package name="com.how2java.pojo"/>
</typeAliases>

Mapping Category.xml

<mappers>
<mapper resource="com/how2java/pojo/Category.xml"/>
</mappers>
<?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"> <configuration> <typeAliases> <package name="com.how2java.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="admin"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/how2java/pojo/Category.xml"/> </mappers> </configuration>
Step 11 :

Configuration file Category.xml

edit top fracture
In the bag com.how2java.pojo Next , New file Category.xml


namespace="com.how2java.pojo"

Indicates that the namespace is com.how2java.pojo, In subsequent calls sql When you say , Will use it
It defines a sql sentence

select * from category_

This one sql The statement uses id: listCategory Marked for subsequent code calls . resultType="Category" Represents the returned data and Category Associated with , What should have been used here is com.how2java.pojo.Category, But because the alias was configured in the previous step , So use directly Category Just
<?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.how2java.pojo"> <select id="listCategory" resultType="Category"> select * from category_ </select> </mapper>
<?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.how2java.pojo">
	    <select id="listCategory" resultType="Category">
	        select * from   category_      
	    </select>
	</mapper>
Run and observe the results shown in the figure .
According to Configuration file mybatis-config.xml Get sqlSessionFactory .

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

Then according to sqlSessionFactory Get session

SqlSession session=sqlSessionFactory.openSession();

Finally pass session of selectList method , Call sql sentence listCategory.listCategory This is in Configuration file Category.xml The one in the sql Statement set id.
After execution , Get a Category aggregate , You can see the data after traversing .

List<Category> cs = session.selectList("listCategory");
for (Category c : cs) {
System.out.println(c.getName());
}


notes : session.selectList("listCategory"); It can also be written as session.selectList("com.how2java.pojo.listCategory"); The effect is the same . But I dislike its bloated , Not in this way
 Test class TestMybatis
package com.how2java; import java.io.IOException; import java.io.InputStream; import java.util.List; 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 com.how2java.pojo.Category; public class TestMybatis { public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session=sqlSessionFactory.openSession(); List<Category> cs=session.selectList("listCategory"); for (Category c : cs) { System.out.println(c.getName()); } } }
1. Application found Mybatis Want data
2. mybatis Find data from the database
2.1 Through mybatis-config.xml Locate which database
2.2 Through Category.xml Execute the corresponding select sentence
2.3 be based on Category.xml Encapsulate the returned database records in Category Object
2.4 Put more Category The object is installed in a Category In the collection
3. Returns a Category aggregate
 Basic schematic diagram
If you can't figure it out , Just use the configured runnable project in the upper right corner . Then compare which part of yourself is different , Locate the problem .
Step 15 :

practice

edit top fracture   Wrong posture , get half the results with double the effort ! Click to see the correct posture for the exercise
reference resources Category, Make a Product Class mybatis Query . Product Class has three properties :
int id
String name
float price


The official account of programming , Follow and get the latest tutorials and promotions in real time , thank you .


Q & A area    
2021-10-30 spring When used ,mybatis In the log4j It doesn't work ( have maven)
Xiaoyuan




Use... In the project maven Use... At the same time spring and mybatis Import log4j, Can be in mybatis Add this code to the global settings
 <setting name="logImpl" value="LOG4J"/>
 
               





The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2021-10-30 About the problem that aliases don't work
Xiaoyuan




If the above aliases don't work , It can be written as follows ,
<typeAliases>
      <package name="com.how2java.pojo"/>
    </typeAliases>
 If the above aliases don't work , It can be written as follows ,
    <typeAliases>
        <!--  by pojo Object definition alias -->
        <typeAlias type="com.how2java.pojo.Category" alias="Category"></typeAlias>
    </typeAliases>
 
               





The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2021-06-17 Solve abnormal problems
2021-05-30 mysql The version is too high !
2021-05-20 function TestMybatis How to solve the problem when an exception occurs


Too many questions , Page rendering is too slow , To speed up rendering , Only a few questions are displayed on this page at most . also 59 Previous questions , please Click to view

Please... Before asking questions land
The question has been submitted successfully , Auditing . Please My question Check the question record at , thank you
about JAVA Frame -Mybatis- introduction Your questions

Try to provide Screenshot code and Abnormal information , Help to analyze and solve problems . You can also enter this station QQ Group communication : 496725845
Ask questions and try to provide complete code , Environment description , The more conducive to the recurrence of the problem , The faster your question can be answered .
Have questions about the code in the tutorial , Please provide which step , Which line is in doubt , This makes it easy to quickly locate the problem , Improve the speed at which questions are answered
In the thousands of questions that already exist , A considerable proportion , Because of the use of and webmaster Different versions of the development environment Resulting in , For example jdk, eclpise, idea, mysql,tomcat Wait, the version of the software is inconsistent .
Please use the same version as the webmaster , You can save yourself a lot of learning time . The webmaster sorted out the software versions used in teaching , It's all here , Convenient for everyone to download : /k/helloworld/helloworld-version/1718.html

Upload screenshot