Introduction to mybatis: inserting data into database (eclipse version)

Keywords: Mybatis Maven xml Apache

Mybatis Knowledge Reserve:

I. framework
Understanding: framework is actually a semi-finished product of an application, a set of components for you to choose and complete your own system. Simply put, use the stage set up by others to perform. Moreover, frameworks are generally mature, upgraded software.

The relationship between Mybatis and jdbc
Mybatis is a persistence layer framework encapsulated on the basis of jdbc.
Mybatis is an ORM framework. ORM (object relational mapping): Object relational mapping

The project structure is as follows:

Database tabulation:

Preparation:

1. Configuring maven
window---->preferences—>maven


2. Creating skeleton-free maven project
file—>new —>maven project

Configuration of pom.xml
pom.xml

<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.henu.mybatis</groupId>
	<artifactId>mybatis01</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<!-- Setting Project Properties -->
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>
	<dependencies>
		<!-- Connection of database -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.39</version>
		</dependency>
		<!-- mybatis Version -->
		<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
	</dependencies>
</project>

Official start:

Configuration of files

mybatisConfig.xml (configuration file)

<?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">
<!-- Master Profile -->
<configuration>
	<!-- Configure a database connection environment -->
	<environments default="mysql"><!--Default connection -->
		<environment id="mysql">
			<!-- Configure transaction types -->
			<transactionManager type="JDBC"></transactionManager>
			<!-- Configure the data source (connection pool) -->
			<dataSource type="POOLED">
				<!-- Four basic information for configuring connection databases -->
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis0910" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<!-- Load the mapping file -->
	<mappers>
	<mapper resource="mapper/UserMapper.xml"></mapper>
	</mappers>
</configuration>


Create the mapper folder and create UserMapper.xml (mapping file) below.

<?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.henu.mybatis.bean">
        	<!--Add data to the database  -->
        	<insert id="insertUser">
        	insert into user values(1,'admin','admin',18);
        	</insert>
        </mapper>	

First: Creating Entity Classes

package com.henu.mybatis.bean;
/**
 * User Entity Class
 * @author YAN
 *
 */
public class User {
	private Integer id;
	private String uname;
	private String upass;
	private Integer uage;
	public Integer getUage() {
		return uage;
	}
	public void setUage(Integer uage) {
		this.uage = uage;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getUpass() {
		return upass;
	}
	public void setUpass(String upass) {
		this.upass = upass;
	}
	
	public User(Integer id, String uname, String upass, Integer uage) {
		super();
		this.id = id;
		this.uname = uname;
		this.upass = upass;
		this.uage = uage;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", uname=" + uname + ", upass=" + upass + ", uage=" + uage + "]";
	}
	public User() {
		super();
	}
	
}

2. Creating test classes

UserTest.java

package com.henu.mybatis.text;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import javax.annotation.Resource;

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 UserTest {

	public static void main(String[] args) throws Exception {
		//4. Loading configuration files
		Reader reader =  Resources.getResourceAsReader("mybatisConfig.xml");
		//3. Create constructor objects
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		//2. Creating factories
		SqlSessionFactory sqlSessionFactory = builder.build(reader);
		//1. Create execution objects
		SqlSession session = sqlSessionFactory.openSession();
		//Execute sql statements
		session.insert("insertUser");
		//Submission of affairs
		session.commit();
		//close resource
		session.close();
	}

}

The constraints dtd of mybatis configuration file xml in this article should be understood

<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2009-2016 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>

<!ELEMENT databaseIdProvider (property*)>
<!ATTLIST databaseIdProvider
type CDATA #REQUIRED
>

<!ELEMENT properties (property*)>
<!ATTLIST properties
resource CDATA #IMPLIED
url CDATA #IMPLIED
>

<!ELEMENT property EMPTY>
<!ATTLIST property
name CDATA #REQUIRED
value CDATA #REQUIRED
>

<!ELEMENT settings (setting+)>

<!ELEMENT setting EMPTY>
<!ATTLIST setting
name CDATA #REQUIRED
value CDATA #REQUIRED
>

<!ELEMENT typeAliases (typeAlias*,package*)>

<!ELEMENT typeAlias EMPTY>
<!ATTLIST typeAlias
type CDATA #REQUIRED
alias CDATA #IMPLIED
>

<!ELEMENT typeHandlers (typeHandler*,package*)>

<!ELEMENT typeHandler EMPTY>
<!ATTLIST typeHandler
javaType CDATA #IMPLIED
jdbcType CDATA #IMPLIED
handler CDATA #REQUIRED
>

<!ELEMENT objectFactory (property*)>
<!ATTLIST objectFactory
type CDATA #REQUIRED
>

<!ELEMENT objectWrapperFactory EMPTY>
<!ATTLIST objectWrapperFactory
type CDATA #REQUIRED
>

<!ELEMENT reflectorFactory EMPTY>
<!ATTLIST reflectorFactory
type CDATA #REQUIRED
>

<!ELEMENT plugins (plugin+)>

<!ELEMENT plugin (property*)>
<!ATTLIST plugin
interceptor CDATA #REQUIRED
>

<!ELEMENT environments (environment+)>
<!ATTLIST environments
default CDATA #REQUIRED
>

<!ELEMENT environment (transactionManager,dataSource)>
<!ATTLIST environment
id CDATA #REQUIRED
>

<!ELEMENT transactionManager (property*)>
<!ATTLIST transactionManager
type CDATA #REQUIRED
>

<!ELEMENT dataSource (property*)>
<!ATTLIST dataSource
type CDATA #REQUIRED
>

<!ELEMENT mappers (mapper*,package*)>

<!ELEMENT mapper EMPTY>
<!ATTLIST mapper
resource CDATA #IMPLIED
url CDATA #IMPLIED
class CDATA #IMPLIED
>

<!ELEMENT package EMPTY>
<!ATTLIST package
name CDATA #REQUIRED
>

Posted by Grim... on Mon, 30 Sep 2019 21:05:38 -0700