One 、 Basic knowledge of :

1. On the original ecology jdbc Program ( Use alone jdbc Development ) The problem summary

 2.mybatis Frame principle ( master )

 3.mybatis Entry procedure

 4. User growth 、 Delete 、 Change 、 check

 5.SqlMapConfig.xml

 6. Input mapping

 7. Output mapping

 8. dynamic sql

1. On the original ecology jdbc Summary of problems in procedure

1.1  Environmental Science

java Environmental Science :jdk1.8.0_20

eclipse:luna

mysql:5.1

1.2   establish mysql data

sql Script :

/*
SQLyog v10.2
MySQL - 5.1.72-community : Database - mybatis
*********************************************************************
*/ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
/*Table structure for table `items` */ CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL COMMENT ' Name of commodity ',
`price` float(10,1) NOT NULL COMMENT ' merchandise valuation ',
`detail` text COMMENT ' Commodity Description ',
`pic` varchar(64) DEFAULT NULL COMMENT ' Commodity images ',
`createtime` datetime NOT NULL COMMENT ' Date of manufacture ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; /*Table structure for table `orderdetail` */ CREATE TABLE `orderdetail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`orders_id` int(11) NOT NULL COMMENT ' Order id',
`items_id` int(11) NOT NULL COMMENT ' goods id',
`items_num` int(11) DEFAULT NULL COMMENT ' Quantity of goods purchased ',
PRIMARY KEY (`id`),
KEY `FK_orderdetail_1` (`orders_id`),
KEY `FK_orderdetail_2` (`items_id`),
CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; /*Table structure for table `orders` */ CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT ' Order user id',
`number` varchar(32) NOT NULL COMMENT ' The order number ',
`createtime` datetime NOT NULL COMMENT ' Order creation time ',
`note` varchar(100) DEFAULT NULL COMMENT ' remarks ',
PRIMARY KEY (`id`),
KEY `FK_orders_1` (`user_id`),
CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; /*Table structure for table `user` */ CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT ' User name ',
`birthday` date DEFAULT NULL COMMENT ' Birthday ',
`sex` char(1) DEFAULT NULL COMMENT ' Gender ',
`address` varchar(256) DEFAULT NULL COMMENT ' Address ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

sql Script

1.3 jdbc Program

Use jdbc Inquire about mysql Records of user tables in the database .

establish java engineering , Join in jar package :

Database driver package (mysql5.1)

On the top is mysql drive .

Below is oracle The driver .

  Program code :

package com.dzq.mybatis.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; /**
* adopt Jdbc Program , Summarize individual jdbc Program , Summarize them
*
* @author cockroach
*
*/
public class JdbcTest {
public static void main(String[] args) {
// Database connection
Connection connection = null;
// precompiled Statement, Can improve the performance of the database
PreparedStatement preparedStatement = null;
// Result set object
ResultSet resultSet = null; try {
// Load database driver
Class.forName("com.mysql.jdbc.Driver"); // Get the database link through the driver management class
connection = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",
"root", "mysql");
// Definition sql sentence ? Represents a placeholder
String sql = "select * from user where username = ?";
// Get preprocessing statement
preparedStatement = connection.prepareStatement(sql);
// Set parameters , The first parameter is zero sql The sequence number of the parameter in the statement ( from 1 Start ), The second parameter is the set parameter value
preparedStatement.setString(1, " Wang Wu ");
// Send... To the database sql Execute the query , Query out result set
resultSet = preparedStatement.executeQuery();
// Traverse the query result set
while (resultSet.next()) {
System.out.println(resultSet.getString("id") + " "
+ resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Release resources
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } } }

JdbcTest

1.4   The problem summary

1、 Database connection , Create when you use , Immediate release without use , Frequent connections to the database, opening and closing , Cause a waste of database resources , influence Database performance .

imagine : Use the database connection pool to manage database connections .

2、 take sql The statement is hard coded to java In the code , If sql Statement modification , Recompile required java Code , Not conducive to system maintenance .

imagine : take sql The statement is configured in xml In profile , Even if sql change , No need. java The code is recompiled .

3、 towards preparedStatement Setting parameters in , Set the parameter value for the position and position of the space occupying symbol , Hard coded in java In the code , Not conducive to system maintenance .

imagine : take sql All statements, space occupying symbols and parameters are configured in xml in .

4、 from resultSet When traversing result set data in , There is hard coding , Hard code the fields that get the table ,, Not conducive to system maintenance .

imagine : The result set of the query , Automatically map to java object .

2.mybatis frame

2.1     mybatis What is it? ?

mybatis It's a framework for a persistence layer , yes apache Top projects under .

mybatis Trusteeship goolecode Next , And then to github Next (https://github.com/mybatis/mybatis-3/releases).

mybatis Let the program focus on sql On , adopt mybatis Mapping method provided , Free and flexible generation ( Semi automation , Most need to be written by programmers sql) Meet needs sql sentence .

mybatis You can turn to preparedStatement The input parameters in are mapped automatically , Flexibly map the query result set to java object .( Output mapping )

2.2    mybatis frame

3 Entry procedure

3.1  demand

According to the user id( Primary key ) Query user information

According to the user name fuzzy query user information

Add users

Delete user

Update user

3.2  Environmental Science

java Environmental Science :jdk1.8.0_20

eclipse:luna

mysql:5.1

jar package :mybatis-3.2.7.jar

lib Next : Dependency package

mybatis-3.2.7.jar: The core package

mybatis-3.2.7.pdf, Operation guide

Join in mysql Driver package

3.3  log4j.properties

# Global logging configuration
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

3.4 Engineering structure

3.5 SqlMapConfig.xml

To configure mybatis Operating environment , data source 、 Affairs, etc. .

<?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> <!-- and spring After integration environments Configuration will be abolished -->
<environments default="development">
<environment id="development">
<!-- Use jdbc Business management , Transaction control by mybatis-->
<transactionManager type="JDBC" />
<!-- Database connection pool , from mybatis management -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments> </configuration>

SqlMapConfig.xml

3.6 According to the user id( Primary key ) Query user information

3.6.1  establish po class

package com.dzq.mybatis.domain;
import java.util.Date;
public class User {
// The attribute name corresponds to the field of the database table
private int id;
private String username;// User name
private String sex;// Gender
private Date birthday;// Birthday
private String address;// Address public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} }

User.java

3.6.2     The mapping file

Map file name :

User.xml( original ibatis name ),mapper The name of the agent development mapping file is XXXMapper.xml, such as :UserMapper.xml、ItemsMapper.xml

Configure in mapping file sql sentence .

<?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 , Yes sql Manage by category , Realization sql Isolation Be careful : Use mapper Method development of agent ,namespace It plays a special and important role -->
<mapper namespace="test">
<!-- There are many configurations in the mapping file sql sentence -->
<!-- adopt id Query the record of user table -->
<!-- adopt select Perform database queries
id: Identify the sql, be called statemen Of id take sql Statement encapsulation to mappedstatement In the object
#{}: Represents a placeholder
parameterType: Specify the input parameter type , Designated here int type
{id}: Among them id Represents the received input parameter , If the input parameter is of a simple type ,#{} The parameter name can be any , It can be value Or some other name
resultType: Appoint sql Output mapped java object type ,select Appoint resultType Mapping a single record to java object
-->
<select id="findUserById" parameterType="int" resultType="com.dzq.mybatis.domain.User">
select * from user where id=#{id}
</select>
</mapper>

User.xml

3.6.3     stay SqlMapConfig.xml Load mapping file

stay sqlMapConfig.xml Load in User.xml:

<!-- load The mapping file -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>

3.6.4     Programming

package com.dzq.mybatis.first;
import java.io.IOException;
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 com.dzq.mybatis.domain.User; public class MybatisFirst {
// according to id Query user information , Get a record result
public void findUserById(int id) throws IOException {
//mybatis The configuration file
String resource="SqlMapConfig.xml";
// Get profile stream
InputStream inputStream=Resources.getResourceAsStream(resource);
// Create a session factory , Pass in mybatis Information about the configuration file for
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
// Obtained through the factory sqlsession
SqlSession sqlSession=sqlSessionFactory.openSession();
// adopt sqlsession Operating the database
// The first parameter :statement, In the mapping file statement Of id; be equal to namespace+"."statement Of id
// The second parameter : parameter Specify and map files parameter What matches parameterType The type of Parameters
//sqlSession.selectOne The result is the one that matches in the mapping file resultType Type object
User user=sqlSession.selectOne("test.findUserById", 1);
System.out.println(user);
// Release resources
sqlSession.close();
}
}

MybatisFirst.java

3.7   According to the user name fuzzy query user information

3.7.1     The mapping file

Use User.xml, Add user information fuzzy query based on user name sql sentence .

<!-- According to the user name fuzzy query user information -->
<!-- resultType: Mapped by a single record java object type
${}: Splicing sql strand , Splice the received parameters to sql In the sentence
Use ${} Splicing sql, Can cause sql Inject
${value} Represents the content of the input parameter , If the type passed in is a simple type ${} Only use value
-->
<select id="findUserByUserName" parameterType="java.lang.String" resultType="com.dzq.mybatis.domain.User">
select * from user where username like '%${value}%'
</select>

3.7.2   Program code

// According to the user name fuzzy query user information 
public void findUserByUserName() throws IOException{
//mybatis The configuration file
String resource="SqlMapConfig.xml";
// Get profile stream
InputStream inputStream=Resources.getResourceAsStream(resource);
// Create a session factory , Pass in mybatis Information about the configuration file for
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
// Obtained through the factory sqlsession
SqlSession sqlSession=sqlSessionFactory.openSession();
// adopt sqlsession Operating the database
// The first parameter :statement, In the mapping file statement Of id; be equal to namespace+"."statement Of id
// The second parameter : parameter Specify and map files parameter What matches parameterType The type of Parameters
//sqlSession.selectList The result is the one that matches in the mapping file resultType Type object
List<User> list=sqlSession.selectList("test.findUserByUserName", " Xiao Ming ");
System.out.println(list);
// Release resources
sqlSession.close();
}

3.8 Add users

3.8.1 The mapping file

stay User.xml To add users in the configuration Statement

<!-- Add users -->
<!--
parameterType: The input parameter type is pojo( Including user information )
#{}: Appoint pojo The property name , Received pojo The attribute value ,mybatis adopt ognl Get attribute value
-->
<insert id="addUser" parameterType="com.dzq.mybatis.domain.User">
insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address})
</insert>

3.8.2 Program code

// Add user information 
@Test
public void addUser() throws IOException {
// mybatis The configuration file
String resource = "SqlMapConfig.xml";
// Get profile stream
InputStream inputStream = Resources.getResourceAsStream(resource);
// Create a session factory , Pass in mybatis Information about the configuration file for
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// Obtained through the factory sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
// Insert user object
User user=new User();
user.setUsername(" Humble ");
user.setSex(" male ");
user.setAddress(" Linyi, Shandong ");
user.setBirthday(new Date());
sqlSession.insert("test.addUser", user);
// Commit transaction
sqlSession.commit();
// Release resources
sqlSession.close();
}

3.8.3     Auto increase primary key return

mysql Since the primary key , perform insert Automatically generate a self incrementing primary key before submitting .

adopt mysql Function to get the self incrementing primary key of the newly inserted record :

LAST_INSERT_ID()

yes insert Then we call this function. .

modify insertUser Definition :

<insert id="addUser" parameterType="com.dzq.mybatis.domain.User">
<!-- insert Insert data back to User In the object
select last_insert_id: Get the primary key value of the data just inserted , Only for autoincrement primary keys
keyProperty: Set the primary key value to parameterType The property of the object
order: be relative to insert The order in which statements are executed
-->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select last_insert_id()
</selectKey>
insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
</insert>

3.8.14     Non auto increment primary key return ( Use uuid())

Use mysql Of uuid() Function generate primary key , Need to modify table id Field type is string, Length set to 35 position .

Execution ideas :

Through the first uuid() Query to primary key , Enter the primary key To sql In the sentence .

perform uuid() Statement order relative to insert Execute before statement .

adopt oracle Generate primary key based on sequence of :

<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<selectKey resultType="java.lang.Integer" order="BEFORE"
keyProperty="id">
SELECT Custom sequence .NEXTVAL FROM DUAL
</selectKey>
insert into user(id,username,birthday,sex,address)
values(#{id},#{username},#{birthday},#{sex},#{address})
</insert>

Pay attention to the order yes “BEFORE”

3.9 Delete user

3.9.1 The mapping file

<!-- Delete user 
according to id Delete user , Need to enter id value
-->
<delete id="deleteUser" parameterType="int" >
delete from user where id=#{id}
</delete>

3.9.2 Program code

// Delete user information 
@Test
public void deleteUser() throws IOException {
// mybatis The configuration file
String resource = "SqlMapConfig.xml";
// Get profile stream
InputStream inputStream = Resources.getResourceAsStream(resource);
// Create a session factory , Pass in mybatis Information about the configuration file for
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// Obtained through the factory sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
// Pass in id, according to id Delete user
sqlSession.delete("test.deleteUser", 33);
// Commit transaction
sqlSession.commit();
// Release resources
sqlSession.close();
}

3.10 Update user

3.10.1 The mapping file

<!-- Update user 
analysis : The user's id
User's update information
parameterType, Appoint user object , Include id And update information , Be careful ,id There must be
#{id} receive user Property value in
-->
<update id="updateUser" parameterType="com.dzq.mybatis.domain.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>

3.10.2 Program code

// Update user information 
@Test
public void updateUser() throws IOException {
// mybatis The configuration file
String resource = "SqlMapConfig.xml";
// Get profile stream
InputStream inputStream = Resources.getResourceAsStream(resource);
// Create a session factory , Pass in mybatis Information about the configuration file for
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// Obtained through the factory sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(32);
user.setUsername(" Cheap cheap cheap ");
user.setSex(" Woman ");
user.setAddress(" Laiwu, Shandong ");
user.setBirthday(new Date());
// Pass in user object , according to id Update user
sqlSession.update("test.updateUser", user);
// Commit transaction
sqlSession.commit();
// Release resources
sqlSession.close();
}

3.11 Summary

3.11.1      #{} and ${}

#{} Represents a placeholder symbol ,#{} Receive input parameters , Types can be simple types ,pojo、hashmap.

If you receive a simple type ,#{} Can be written as value Or some other name .

#{} receive pojo The object is worth , adopt OGNL Read property values in objects , Passing attribute . attribute . attribute ... To get the value of an object's property .

${} Represents a mosaic symbol , Will quote sql Inject , So it's not recommended ${}.

${} Receive input parameters , Types can be simple types ,pojo、hashmap.

If you receive a simple type ,${} It can only be written in Chinese value.

${} receive pojo The object is worth , adopt OGNL Read property values in objects , Passing attribute . attribute . attribute ... To get the value of an object's property .

3.11.2     parameterType and resultType

parameterType: Specify the input parameter type ,mybatis adopt ognl Get the parameter value from the input object and splice it in sql in .

resultType: Specify the output result type ,mybatis take sql The row record data of the query result is mapped to resultType Object of the specified type .

3.11.3     selectOne and selectList

selectOne Look up a record , If you use selectOne Query multiple records and throw an exception :

org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3

at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:70)

selectList You can query one or more records .

3.12   mybatis and hibernate Essential differences and application scenarios

hibernate: It's a standard ORM frame ( Object relation mapping ). The entry threshold is higher , No programming required sql,sql Statements are automatically generated .

Yes sql Statement optimization 、 It's difficult to revise .

Application scenarios :

Suitable for small and medium-sized projects with little change in demand , such as : Background management system ,erp、orm、oa..

mybatis: Focus is sql In itself , The programmer has to write it himself sql sentence ,sql modify 、 Optimization is more convenient .mybatis It's an incomplete problem Of ORM frame , Although the programmer wrote it himself sql,mybatis You can also implement mapping ( Input mapping 、 Output mapping ).

Application scenarios :

It is suitable for projects with more changes in demand , such as : Internet Project .

Technology selection of enterprises , At low cost High return as the principle of technology selection , Choose according to the technical strength of the project team .

4     mybatis Development dao Methods

4.1     SqlSession Using range

4.1.1     SqlSessionFactoryBuilder

adopt SqlSessionFactoryBuilder Create a session factory SqlSessionFactory

take SqlSessionFactoryBuilder Use it as a tool class , No need to use singleton Management SqlSessionFactoryBuilder.

When you need to create SqlSessionFactory When , It only needs new once SqlSessionFactoryBuilder that will do .

4.1.2    SqlSessionFactory

adopt SqlSessionFactory establish SqlSession, Manage with singleton mode sqlSessionFactory( Once the factory is created , Use an example ).

future mybatis and spring After integration , Manage with singleton mode sqlSessionFactory.

4.1.3     SqlSession

SqlSession It's a user oriented ( The programmer ) The interface of .

SqlSession There are many ways to operate the database : Such as :selectOne( Return a single object )、selectList( Returns a single or multiple object )、.

SqlSession It's not thread safe , stay SqlSesion In addition to the methods in the interface in the implementation class ( How to operate database ) And data field properties .

SqlSession The best application is in the method body , Defined as a local variable using .

4.2     original dao development method ( Programmers need to write dao Interface and dao Implementation class )

4.2.1     Ideas

Programmers need to write dao Interface and dao Implementation class .

You need to dao Inject... Into the implementation class SqlSessionFactory, In vivo through the method SqlSessionFactory establish SqlSession

4.2.2     dao Interface

package com.dzq.mybatis.dao;
import com.dzq.mybatis.domain.User;
public interface UserDao {
// according to id Query user information
public User findUserById(int id) throws Exception; // Add users
public void addUser(User user) throws Exception; // Delete user
public void deleteUser(int id) throws Exception; // Modify user information
public void updateUser(User user) throws Exception;
}

4.2.2     dao Interface implementation class

package com.dzq.mybatis.dao.impl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import com.dzq.mybatis.dao.UserDao;
import com.dzq.mybatis.domain.User; public class UserDaoImpl implements UserDao {
// You need to dao Inject... Into the implementation class SqlSessionFactory
// Here we inject... Through the construction method
private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
} @Override
public User findUserById(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("test.findUserById", id);
// Release resources
sqlSession.close();
return user;
} @Override
public void addUser(User user) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
// Execution insert
sqlSession.insert("test.addUser", user);
// Commit transaction
sqlSession.commit();
// Release resources
sqlSession.close();
} @Override
public void deleteUser(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.delete("test.deleteUser", id);
// Commit transaction
sqlSession.commit();
// Release resources
sqlSession.close(); } @Override
public void updateUser(User user) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.update("test.updateUser", user);
// Commit transaction
sqlSession.commit();
// Release resources
sqlSession.close();
} }

4.2.4   Test code :

package com.dzq.mybatis.test;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test; import com.dzq.mybatis.dao.UserDao;
import com.dzq.mybatis.dao.impl.UserDaoImpl;
import com.dzq.mybatis.domain.User; public class UserDaoImplTest { private SqlSessionFactory sqlSessionFactory; @Before
public void setUp() throws Exception {
// establish sqlSessionFactory
// mybatis The configuration file
String resource = "SqlMapConfig.xml";
// Get profile stream
InputStream inputStream = Resources.getResourceAsStream(resource);
// Create a session factory , Pass in mybatis Information about the configuration file for
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testFindUserById() throws Exception {
// establish UserDao object
UserDao userdao = new UserDaoImpl(sqlSessionFactory);
// call userDao Method
User user=userdao.findUserById(1);
System.out.println(user.getUsername());
} }

4.2.5     Summarize the original dao Development issues

1、dao There are a lot of template methods in interface implementation class methods , Imagine if you can extract this code , Greatly reduce the workload of programmers .

2、 call sqlsession Method will be statement Of id The hard coded

3、 call sqlsession Method , because sqlsession Method uses generics , Even if the variable type is passed in incorrectly , No errors are reported in the compile phase , It's not good for programmers to develop .

4.3    mapper Proxy method ( Programmers only need mapper Interface ( Quite a On dao Interface ))

4.3.1     Ideas (mapper Agent development specification )

Programmers also need to write mapper.xml The mapping file

Written by programmer mapper The interface needs to follow some development specifications ,mybatis Can be generated automatically mapper Interface implementation class proxy object .

The development of specification :

1、 stay mapper.xml in namespace be equal to mapper Address of the interface

<!-- Namespace , Yes sql Manage by category , Realization sql Isolation Be careful : Use mapper Method development of agent ,namespace It plays a special and important role 
namespace be equal to mapper Address of the interface
-->
<mapper namespace="com.dzq.mybatis.mapper.UserMapper">

2、mapper.java Method names and in interfaces mapper.xml in statement Of id Agreement

3、mapper.java Method input parameter types and mapper.xml in statement Of parameterType The specified type is consistent .

4、mapper.java Method return value types and mapper.xml in statement Of resultType The specified type is consistent .

<select id="findUserById" parameterType="int" resultType="com.dzq.mybatis.domain.User">
select * from user where id=#{id}
</select>
// according to id Query user information 
public User findUserById(int id) throws Exception;

summary :

The above development specifications are mainly for the unified generation of the code below :

User user = sqlSession.selectOne("test.findUserById", id);

sqlSession.insert("test.insertUser", user);

....

4.3.2      mapper.java

package com.dzq.mybatis.mapper;
import java.util.List;
import com.dzq.mybatis.domain.User;
public interface UserMapper {
public User findUserById(int id) throws Exception;
}

4.3.3  mapper.xml

<select id="findUserById" parameterType="int" resultType="com.dzq.mybatis.domain.User">
select * from user where id=#{id}
</select>

4.3.4     stay SqlMapConfig.xml Load in mapper.xml

<!-- load The mapping file -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>

4.3.5     test

package com.dzq.mybatis.test;
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 org.junit.Before;
import org.junit.Test; import com.dzq.mybatis.domain.User;
import com.dzq.mybatis.mapper.UserMapper; public class UserMapperTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws Exception {
// establish sqlSessionFactory
// mybatis The configuration file
String resource = "SqlMapConfig.xml";
// Get profile stream
InputStream inputStream = Resources.getResourceAsStream(resource);
// Create a session factory , Pass in mybatis Information about the configuration file for
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testFindUserById() throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession();
// Create a usermapper The object of
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
// call userMapper Method
User user=userMapper.findUserById(1);
System.out.println(user.getUsername()); } }

4.3.6     Entire interface

package com.dzq.mybatis.mapper;
import java.util.List;
import com.dzq.mybatis.domain.User;
public interface UserMapper {
// according to id Query user information 
public User findUserById(int id) throws Exception; // Add users
public void addUser(User user) throws Exception; // Delete user
public void deleteUser(int id) throws Exception; // Query user list by user name
public List<User> findUserByUserName(String username) throws Exception;
}

4.3.7     Some questions sum up

4.3.7.1              Proxy object internal call selectOne or selectList

If mapper Method returns a single pojo object ( Non collection object ), Proxy object passed internally selectOne Query the database .

If mapper Method returns the collection object , Proxy object passed internally selectList Query the database .

4.3.7.2              mapper Only one interface method parameter can affect the system Development

mapper Interface method parameters can only have one , Is the system not conducive to extended maintenance .

System In the frame ,dao Layer code is shared by the business layer .

Even if mapper Interface has only one parameter , You can use the packaging type of pojo Meet the needs of different business methods .

Be careful : The parameters of the persistence layer method can wrap the type 、map...,service The packing type is not recommended in the method ( Not conducive to the scalability of the business layer ).

5      SqlMapConfig.xml

mybatis Global configuration file for SqlMapConfig.xml, The configuration is as follows :

properties( attribute )

settings( Global configuration parameter )

typeAliases( Type the alias )

typeHandlers( Type processor )

objectFactory( Object factory )

plugins( plug-in unit )

environments( Environment collection property object )

environment( Environment sub property object )

transactionManager( Business management )

dataSource( data source )

mappers( mapper )

5.1     properties attribute

demand :

Configure the database connection parameters separately in db.properties in , Only need SqlMapConfig.xml Load in db.properties The attribute value .

stay SqlMapConfig.xml There is no need to hard code database connection parameters in .

Configure database connection parameters only in db.properties in , reason : Convenient for unified management of parameters , Other xml You can refer to the db.properties.

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=
<!-- Load properties file -->
<properties resource="db.properties">
<!--properties You can also configure some property names and property values in -->
<!-- <property name="jdbc.driver" value=""/> -->
</properties>

properties characteristic :

Be careful : MyBatis The properties will be loaded in the following order :

stay properties The attributes defined in the element body are first read .

Then it reads properties In the elements resource or url Loaded properties , It will overwrite the read property with the same name .

Last read parameterType Properties passed , It will overwrite the read property with the same name .

Suggest :

Not in properties Add any attribute values inside the element , Define only property values in properties In file .

stay properties There must be some particularity in defining attribute names in files , Such as :XXXXX.XXXXX.XXXX

5.2   settings Global parameter configuration

mybatis The framework can adjust some operation parameters at runtime .

such as : Enable L2 cache 、 Turn on delay loading ..

Global parameters will affect mybatis The operation of .

5.3     typeAliases( Alias ) a key

5.3.1     demand

stay mapper.xml in , A lot of definitions statement,statement need parameterType Specifies the type of the input parameter 、 need resultType Specifies the mapping type of the output result .

If type full path is entered when type is specified , It's not convenient for development , Can target parameterType or resultType The specified type defines some aliases , stay mapper.xml Defined by alias in , Easy to develop .

5.3.2   mybatis Alias is supported by default

5.3.3     Custom alias

5.3.3.1              Single alias definition

<!-- The alias definition -->
<typeAliases>
<!-- Definition for a single alias
type: Type path
alias: Alias
-->
<typeAlias type="com.dzq.mybatis.domain.User" alias="user"/>
</typeAliases>

Quote aliases :

<select id="findUserById" parameterType="int" resultType="user">
select * from user where id=#{id}
</select>

5.3.3.2   Batch define aliases ( Commonly used )

<!-- Batch alias definition 
Specify package name ,mybatis Automatic scanning domain class , Automatically define aliases , An alias is a class name
-->
<package name="com.dzq.mybatis.domain"/>

5.4    typeHandlers( Type processor )

mybatis Pass through typeHandlers complete jdbc The type and java Conversion of type .

Usually ,mybatis The type of processor provided meets the daily needs , No need to customize .

mybatis Support for type processors :

5.5  mappers( Mapping configuration )

5.5.1     adopt resource Load a single mapping file

<!-- load The mapping file -->
<mappers>
<mapper resource="sqlmap/User.xml" />
<mapper resource="mapper/UserMapper.xml" />
</mappers>

5.5.2   adopt mapper Interface load single mapper

<!-- adopt mapper Interface load single mapper
Follow some rules : Need to put mapper Class name and name of the interface mapper.xml Map file names consistently , And in a directory
The premise of the above norm is : You're using mapper Proxy method
-->
<mapper class="com.dzq.mybatis.mapper.UserMapper"/>

Need to put mapper Class name and name of the interface mapper.xml Map file names consistently , And in a directory

5.5.3   Bulk load mapper( Recommended )

<!-- Bulk load mapper( Recommended )
Appoint mapper The package name of the interface ,mybatis Auto scan all files under the package mapper Interface to load
Follow some rules : Need to put mapper Class name and name of the interface mapper.xml Map file names consistently , And in a directory
The premise of the above norm is : You're using mapper Proxy method
-->
<package name="com.dzq.mybatis.mapper"/>

6     Input mapping

adopt parameterType Specifies the type of the input parameter , Types can be simple types 、hashmap、pojo Type of packaging .

6.1     Pass on pojo The packaging object of

6.1.1     demand

Complete the comprehensive query of user information , It's very complicated to need to pass in query conditions ( May include user information 、 Other information , For example, commodities 、 Order's )

6.1.2     Define the packaging type pojo

For the needs above , It is recommended to use a custom packaging type of pojo.

In the packaging type pojo Package complex query conditions .

package com.dzq.mybatis.domain;
public class UserQueryVo {
// Here are the required query conditions
// User query criteria
private UserCustom userCustom;
// You can also package other query criteria goods 、 Order public UserCustom getUserCustom() {
return userCustom;
} public void setUserCustom(UserCustom userCustom) {
this.userCustom = userCustom;
} }

6.1.3    mapper.xml

stay UserMapper.xml User information integrated query is defined in ( The query conditions are complex , Complex association query through advanced query ).

 <!-- Comprehensive query of user information 
#{userCustom.sex}: Take out the gender information of the package type
${userCustom.username}: Take out the user name in the wrapper class
-->
<select id="findUserList" parameterType="com.dzq.mybatis.domain.UserQueryVo" resultType="com.dzq.mybatis.domain.UserCustom">
select * from user where user.sex=#{userCustom.sex} and user.username like '%${userCustom.username}%'
</select>

6.1.4      mapper.java

// User information comprehensive query 
public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;

6.1.5     Test code

 @Test
public void testFindUserList() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession();
// Create a usermapper The object of
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// Create a wrapper object , Set query conditions
UserQueryVo userQueryVo=new UserQueryVo();
UserCustom userCustom=new UserCustom();
userCustom.setSex("1");
userCustom.setUsername(" Xiao Ming ");
userQueryVo.setUserCustom(userCustom);
// call userMapper Method List<UserCustom> list = userMapper.findUserList(userQueryVo);
//sqlSession.close();
System.out.println(list); }

7     Output mapping

7.1     resultType

Use resultType Do output mapping , Only the column names and pojo The property names in are the same , This column can be mapped successfully .

If the column name and pojo All attribute names in are inconsistent , Not created pojo object .

Just look up the column names and pojo There is a consistent attribute in , Will be created pojo object , The value of the inconsistent property is null.

7.1.1     Output simple type

7.1.1.1              demand

Total number of comprehensive query lists for user information , Pagination can only be realized through the total number of queries and the comprehensive query list of users above .

7.1.1.2              mapper.xml

<!-- The total number of comprehensive user information queries 
parameterType: Input type and findUserList Agreement
resultType: The output type is integer
-->
<select id="findUserCount" parameterType="com.dzq.mybatis.domain.UserQueryVo" resultType="int">
select count(*) from user where user.sex=#{userCustom.sex} and user.username like '%${userCustom.username}%'
</select>

7.1.1.3              mapper.java

// The total number of comprehensive user information queries 
public int findUserCount(UserQueryVo userQueryVo) throws Exception;

7.1.1.4             Test code

 @Test
public void testFindUserCount() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession();
// Create a usermapper The object of
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// Create a wrapper object , Set query conditions
UserQueryVo userQueryVo=new UserQueryVo();
UserCustom userCustom=new UserCustom();
userCustom.setSex("1");
userCustom.setUsername(" Xiao Ming ");
userQueryVo.setUserCustom(userCustom);
// call userMapper Method int count = userMapper.findUserCount(userQueryVo);
System.out.println(count); }

7.1.1.5             Summary

The query result set has only one row and one column , You can use simple types for output mapping .

7.1.2   Output pojo Objects and pojo list

Whether it's output pojo A single object or a list (list It includes pojo), stay mapper.xml in resultType The specified type is the same .

stay mapper.java The return value type of the specified method is different :

1、 Output single pojo object , Method return value is a single object type

 // according to id Query user information 
public User findUserById(int id) throws Exception;

2、 Output pojo object list, Method return value is List<Pojo>

 // Query user list by user name 
public List<User> findUserByUserName(String username) throws Exception;

The generated dynamic proxy object is based on mapper The return value type of the method is determined to be a call to selectOne( Returns a single object call ) still selectList ( Return collection object call ).

7.2     resultMap

mybatis Use in resultMap Complete high level output mapping .( one-on-one 、 One to many 、 Many to many )( Introduction )

7.2.1     resultMap Usage method

If the column name and pojo Inconsistent property names for , By defining a resultMap To name and pojo Make a mapping between attribute names .

1、 Definition resultMap

2、 Use resultMap As statement Output mapping type of

7.2.2     Take the next one sql Use User Complete mapping

SELECT id id_,username username_ FROM USER WHERE id=#{value}

User The property name in the class is inconsistent with the name of the query column above .

7.2.2.1              Definition reusltMap

 <!-- Definition resultMap
take select id id_,username username_ from user where id=#{id} Query and User Make a mapping
type:resultMap The final mapping is java object type , You can use aliases
id: Yes resultMap Unique identification of
-->
<resultMap type="user" id="userResultMap">
<!-- id Represents a unique identifier in the query result set
column: The name of the column to be found
property:type Specified in the pojo Attribute name in
Final resultMap Yes column and property Make a mapping relationship ( Corresponding relation )
-->
<id column="id_" property="id"/>
<!-- Definition of normal column
column: The name of the column to be found
property:type Specified in the pojo Attribute name in
Final resultMap Yes column and property Make a mapping relationship ( Corresponding relation )
-->
<result column="username_" property="username"/> </resultMap>

7.2.2.2        Use resultMap As statement Output mapping type of

 <!-- Use resultMap To map the output 
resultMap: Specify the definition of resultMap Of id, If resultMap In other mapping files , It needs to be added to the front namespace -->
<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
select id id_,username username_ from user where id=#{id}
</select>

7.2.2.3             mapper.java

// according to id Query user information , Use resultMap Output 
public User findUserByIdResultMap(int id)throws Exception;

7.2.2.4             test

@Test
public void testFindUserByIdResultMap() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession();
// Create a usermapper The object of
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// call userMapper Method
User user = userMapper.findUserByIdResultMap(1);
System.out.println(user.getUsername()); }

7.3     Summary

Use resultType Do output mapping , Only the column names and pojo The property names in are the same , This column can be mapped successfully .

If the column name and pojo Inconsistent property names for , By defining a resultMap To name and pojo Make a mapping between attribute names .

8       dynamic sql

8.1     What is dynamic sql

mybatis The core Yes sql Statement for flexible operation , Judging by expressions , Yes sql Flexible splicing 、 assemble .

8.2     demand

User information comprehensive query list and the total number of user information query lists statement The definition of using dynamic sql.

Judge the query condition , If the input parameter is not empty, the query condition is spliced .

8.3     mapper.xml

 <!-- Comprehensive query of user information 
#{userCustom.sex}: Take out the gender information of the package type
${userCustom.username}: Take out the user name in the wrapper class
-->
<select id="findUserList" parameterType="com.dzq.mybatis.domain.UserQueryVo" resultType="com.dzq.mybatis.domain.UserCustom">
select * from user
<!-- where You can automatically remove the first of the conditions and -->
<where>
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex=#{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username like '%${userCustom.username}%'
</if>
</if>
</where> </select> <!-- The total number of comprehensive user information queries
parameterType: Input type and findUserList Agreement
resultType: The output type is integer
-->
<select id="findUserCount" parameterType="com.dzq.mybatis.domain.UserQueryVo" resultType="int">
select count(*) from user
<!-- where You can automatically remove the first of the conditions and -->
<where>
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex=#{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username like '%${userCustom.username}%'
</if>
</if>
</where>
</select>

8.4   Test code

 public void testFindUserList() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
// Create a usermapper The object of
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// Create a wrapper object , Set query conditions
UserQueryVo userQueryVo=new UserQueryVo();
UserCustom userCustom=new UserCustom(); // Due to the use of dynamic sql, If you don't set a value , This condition will not be spliced to sql in
//userCustom.setSex("1");
userCustom.setUsername(" Xiao Ming ");
userQueryVo.setUserCustom(userCustom);
// call userMapper Method List<UserCustom> list = userMapper.findUserList(userQueryVo);
//sqlSession.close();
System.out.println(list); }

8.5    sql fragment

8.5.1     demand

The above dynamic sql The judgment code block is extracted , Form a sql fragment . The rest of the statement You can quote sql fragment .

Convenient for programmers to develop .

8.5.2     Definition sql fragment

!-- Definition sql fragment 
id:sql Unique identification of the fragment
Experience : Based on single table definition sql fragment , In this way, the reusability is high
sql Don't include where
-->
<sql id="query_user_where">
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex=#{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username like '%${userCustom.username}%'
</if>
</if>
</sql>

8.5.3     quote sql fragment

stay mapper.xml As defined in statement I quote sql fragment :

 <!-- Comprehensive query of user information 
#{userCustom.sex}: Take out the gender information of the package type
${userCustom.username}: Take out the user name in the wrapper class
-->
<select id="findUserList" parameterType="com.dzq.mybatis.domain.UserQueryVo" resultType="com.dzq.mybatis.domain.UserCustom">
select * from user
<!-- where You can automatically remove the first of the conditions and -->
<where>
<!-- That's citation sql Fragment id If refid Not in Ben mapper in , Need to add namespace-->
<include refid="query_user_where"> </include>
<!-- There are other references here sql fragment , Commodities, etc -->
</where> </select>
 <!-- The total number of comprehensive user information queries 
parameterType: Input type and findUserList Agreement
resultType: The output type is integer
-->
<select id="findUserCount" parameterType="com.dzq.mybatis.domain.UserQueryVo" resultType="int">
select count(*) from user
<!-- where You can automatically remove the first of the conditions and -->
<where>
<!-- That's citation sql Fragment id If refid Not in Ben mapper in , Need to add namespace-->
<include refid="query_user_where"> </include>
<!-- There are other references here sql fragment , Commodities, etc -->
</where>
</select>

8.6    foreach

towards sql Pass an array or List,mybatis Use foreach analysis

8.6.1     demand

In the user query list and the total number of queries statement Add multiple in id Input query .

sql The statement is as follows :

The two methods :

SELECT * FROM USER WHERE id=1 OR id=10 OR id=16

SELECT * FROM USER WHERE id IN(1,10,16)

8.6.2     Add... To the input parameter type List<Integer> ids Introduce more than one id

 // Introduce more than one id
private List<Integer> ids; public List<Integer> getIds() {
return ids;
} public void setIds(List<Integer> ids) {
this.ids = ids;
}

8.6.3     modify mapper.xml

WHERE id=1 OR id=10 OR id=16

In the query condition , The query condition is defined as a sql fragment , Need modification sql fragment .

 <if test="ids!=null">
<!-- Use foreach Traverse our incoming ids
collection: Specifies the set properties in the input object
item: Each iteration generates the object name
open: The string to be spliced at the beginning of traversal
close: Concatenated string at the end of traversal
separator: The string to be spliced between two traversed objects
-->
<!-- Use to achieve the following sql Splicing
and (id=1 or id=10 or id=16)
-->
<foreach collection="ids" item="user_id" open="and (" close=")" separator="or">
<!-- The string to be spliced for each traversal -->
id=#{user_id}
</foreach>
</if>

8.6.4     Test code

 @Test
public void testFindUserList() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession();
// Create a usermapper The object of
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// Create a wrapper object , Set query conditions
UserQueryVo userQueryVo=new UserQueryVo();
UserCustom userCustom=new UserCustom(); // Due to the use of dynamic sql, If you don't set a value , This condition will not be spliced to sql in
userCustom.setSex("1");
userCustom.setUsername(" Xiao Ming ");
// Introduce more than one id
List <Integer> ids=new ArrayList<Integer>();
ids.add(1);
ids.add(10);
ids.add(16);
userQueryVo.setUserCustom(userCustom);
// take ids Pass in statement in
userQueryVo.setIds(ids); // call userMapper Method List<UserCustom> list = userMapper.findUserList(userQueryVo);
//sqlSession.close();
System.out.println(list.get(0).getUsername()); }

8.6.5   Another one sql The implementation of the :

<!-- Realization and id in(1,10,16) Splicing -->
<foreach collection="ids" item="user_id" open=" and id in(" close=")" separator=",">
<!-- The string to be spliced for each traversal -->
#{user_id}
</foreach>

20160522--20160526----mybatis More articles on the basics of getting started

  1. mybatis Fundamentals of entry ( Two )---- original dao Development and mapper Agent development

    Take on the last one mybatis Fundamentals of entry ( One ) Friends who read the last article , It must be seen that , Inside MybatisService There's a lot of duplicate code in , It doesn't seem very clear , But the first time I wrote that , To understand mybatis The implementation steps of , First ...

  2. MyBatis Fundamentals of entry ( One )

    One : On the original ecology JDBC A summary of the problem New project to use mybatis As persistence layer framework , Because I have been using Hibernate, Yes mybatis It's really lacking in usage , In the next few days, we plan to mybatis Learn , I will take notes of my study ...

  3. MyBatis Fundamentals of entry

    from http://www.cnblogs.com/selene/p/4604605.html Don't talk much , First look at the original JDBC Program code , Look at the problems with this code . package com.uti ...

  4. mybatis Fundamentals of entry

    One .Mybatis Introduce MyBatis Is a first-class support custom SQL. Persistence framework for stored procedures and advanced mappings .MyBatis Almost all JDBC Code , There is no need to manually set parameters and get search results .MyBatis ...

  5. mybatis Fundamentals of entry ( 6、 ... and )---- Advanced mapping ( one-on-one , One to many , Many to many )

    One : Order product data model 1. Database execution script Create database table code : CREATE TABLE items ( id INT NOT NULL AUTO_INCREMENT, itemsname ) NOT ...

  6. mybatis Fundamentals of entry ---- Advanced mapping ( one-on-one , One to many , Many to many )

    Read the directory One : Order product data model Two . One-to-one query 3、 ... and . One-to-many query Four . Many-to-many queries Back to the top One : Order product data model 1. Database execution script Create database table code : CREATE TABLE items ( id ...

  7. 【 Introduction details 】MyBatis Detailed introduction to basic knowledge

    What is? mybatis? MyBatis Is to support the general SQL Inquire about , Excellent persistence layer framework for stored procedures and advanced mappings .MyBatis Eliminated almost all of them JDBC Manual setting of code and parameters and retrieval of result sets .MyBatis Easy to use XM ...

  8. Mybatis introduction —— The addition and deletion of basic methods should be checked 、mapper Dynamic proxy CRUD、 Type converter

    One . The addition and deletion of basic methods should be checked : 1.mybatis Appointment : Input parameters parameterType And output parameters resulrType There can only be one in form . 2. If input / Output parameters : It's a simple type (8 Two basic types plus String) ...

  9. mybatis Fundamentals of entry ( Nine )---- Reverse engineering

    One . What is reverse engineering mybaits The programmer has to write it himself sql sentence ,mybatis Official offer Reverse Engineering   It can be automatically generated for a single table mybatis Execute the required code (mapper.java,mapper.xml.po. ...

  10. mybatis Fundamentals of entry ( 8、 ... and )----- The query cache

    One . What is query caching mybatis Provide query caching , Used to relieve data pressure , Improve database performance . mybaits Provide first level cache , And L2 cache . 1.1. The first level cache is sqlSession Level cache . When operating the database, you need to construct ...

Random recommendation

  1. android Color refers to the list

    <?xml version="1.0" encoding="utf-8" ?> 2 <resources> 3 <color na ...

  2. control HTML Input You can only enter numbers and decimal points

    This paper introduces two kinds of control in <input type="text" name="name" value="0" /> Only numbers and decimal points are allowed in ...

  3. 【crunch bang】 File manager -thunar

    Thunar Practical functions : Thumbnail view CHB Renamer install : $ sudo apt-get install thunar Speed up thunar Starting speed sudo leafpad /usr/share/gv ...

  4. WebAPI Security Use TOKEN+ Signature verification ( On )

    First of all, let's ask you a question , You're writing open API How to ensure the security of data in the interface ? Let's take a look at what security issues are open api Interface , We go through http Post perhaps Get When the server is requested by , There are a lot of security issues , ...

  5. Google App Engine Study and practice

    I had fun this weekend Google App Engine, Write something casually , It's a study note . Impropriety , Please correct . author :liigo,2009/04/26 night , dalian Original link :http://blog.csdn.ne ...

  6. Use js Add components dynamically

    Before the article begins , I want to say two things 1 I'm just learning js, The content of the article may not be worth mentioning to Dashen , But everyone is from the hello world To the , Wang Gao   Don't hesitate to give advice # 2 I know the title is rather painful , You can see the picture ...

  7. eclipse Use error report collection

    problem 1.Eclipse Always prompt at startup “subversive connector discovery” Solution answer 1: stay eclipse_workSpace( Under the workspace )\.metadata\.plug ...

  8. configure: error: png.h not found.

    PHP This is a mistake configure: error: png.h not found., This is an optional installation GD Module error , The detailed error information is as follows If configure fails try - ...

  9. Scrum Legislative Council report + Burnout figure (Beta Stage 2 week 4 )

    Please refer to :https://edu.cnblogs.com/campus/nenu/2018fall/homework/2412 Project address :https://coding.net/u/wuyy694 ...

  10. DP introduction (3)—— Multistage decision making

    Multistage decision making , In short , Every time you make a decision, you get part of the solution , When all the decisions are made , A complete solution “ Surface ” 了 . In backtracking , Each decision corresponds to the generation of a new subtree for a node , The generation process of solution corresponds to a solution tree , The number of layers of a node is ...