Framework Overview:

MyBatis is an excellent Java-based persistence layer framework, which encapsulates JDBC internally, so that developers only need to focus on THE SQL statement itself, and do not need to spend energy to deal with the complex process of loading drivers, creating connections, creating statements and so on. MyBatis configures various statements to be executed through XML or annotations, and generates the final SQL statement by mapping Java objects to the dynamic parameters of the SQL in the statement. Finally, the MYBatis framework executes the SQL and maps the results to Java objects and returns them. Using ORM thought to solve the entity and database mapping problem, the JDBC encapsulation, shielding the JDBC API access details, so that we do not have to deal with JDBC API, we can complete the database persistence operation.

Traditional JDBC operations:

Of course, just from the previous paragraph, I can’t see the advantages and the necessity of mastering MyBatis framework. To review the JDBC creation process, the code is as follows:

public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Try {// Load the database driver class.forname ("com.mysql.jdbc.Driver"); / / by driving management class for database connection link = DriverManager. GetConnection ("jdbc:mysql://localhost:3306/mybatis? characterEncoding=utf-8"."ro
ot"."root"); // Define SQL statements? The placeholder String SQL ="select * from user where username = ?"; / / for preprocessing the statement preparedStatement = connection. PrepareStatement (SQL); / / set the parameters, the first parameter to the number of parameters in the SQL statement (starting at 1), the second parameter for setting the parameter values of the preparedStatement. SetString (1,"Fifty"); / / issue SQL query is executed to the database, query result set out the resultSet = preparedStatement. ExecuteQuery (); // Iterate over the query result setwhile(resultSet.next()){
		 System.out.println(resultSet.getString("id") +""+resultSet.getString("username")); } } catch (Exception e) { e.printStackTrace(); }finally{// Release resourcesif(resultSet!=null){
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} 
		}
		if(preparedStatement!=null){
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} 
		}
		if(connection! =null){ try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }}}}Copy the code

Problem analysis:

The disadvantages of traditional JDBC can be seen from the above example:

The frequent creation and release of database links waste system resources and affect system performance. This problem can be solved by using database link pools. Sql statements are hardcoded in the code, which makes the code difficult to maintain. As a result, Sql changes in actual applications may be large, and changes in Sql require changes in Java code. Hard coding exists in transferring parameters to possession bit symbols in preparedStatement, because the WHERE conditions of SQL statements are not necessarily, which may be more or less. Modifying SQL requires modifying codes, making the system difficult to maintain. There is hard coding (query column name) for result set parsing, SQL changes lead to parsing code changes, the system is not easy to maintain, if the database records can be encapsulated as POJO object parsing is more convenient.

Project construction:

Create maven project:

Parameter selection: Groupid: the company determines ArtifactId: the project name Packing: jar

Add coordinates:

Add various coordinates to the POM.xml file:

<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId>
		 <artifactId>log4 j < / artifactId > < version > 1.2.12 < / version > < / dependency > < / dependencies >Copy the code

Writing poJO classes:

public class User implements Serializable {

	private Integer id;
	private String username;
	private Date birthday;
	private String sex;
	private String address;
	
	public Integer getId() {
		return id; 
	}
	
	public void setId(Integer id) {
		this.id = id; 
	}
	
	public String getUsername() {
		return username; 
	}
	
	public void setUsername(String username) {
		this.username = username; 
	}
	
	public Date getBirthday() {
		return birthday; 
	}
	
	public void setBirthday(Date birthday) {
		this.birthday = birthday; 
	}
	
	public String getSex() {
		return sex; 
	}
	
	public void setSex(String sex) {
		this.sex = sex; 
	}
	
	public String getAddress() {
		return address; 
	}
	
	public void setAddress(String address) {
		this.address = address; 
	}
	
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address=" + address + "]"; }}Copy the code

Write the persistence layer interface:

Public interface IUserDao {/** * Queries all users * @return
	*/
	List<User> findAll();
}
Copy the code

Write a mapping file for the persistence layer interface:

<? 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.itheima.dao.IUserDao"> <! --> <select id="findAll" resultType="com.itheima.domain.User">
	select * from user
	</select>
</mapper>
Copy the code

There are two caveats:

The mapping file must be in the same package as the interface. If you are developing using IDEA, the interface is in the Java file, the mapping file is in the Resource folder, and the other package names must be the same. The name of the mapping file is named after the name of the interface, with the suffix XML.

Compile mybatis-config.xml 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"> <configuration> <! --> <environments default="mysql"> <! -- Configure the mysql environment --> <environment id="mysql"> <! -- Configure the transaction type --> <transactionManagertype="JDBC"></transactionManager> <! Configure the connection information for the database: use the dataSource (connection pool) --> <dataSourcetype="POOLED"> 
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/ee50"/>
				<property name="username" value="root"/>
				<property name="password" value="1234"/> </dataSource> </environment> </environments> <! Tell mybatis where the mapping configuration is --> <mappers> <mapper resource="com/itheima/dao/IUserDao.xml"/>
	</mappers>
</configuration>
Copy the code

Writing test classes:

public class MybatisTest { public static void main(String[] args)throws Exception { //1. Read configuration file InputStreamin = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactoryBuilder Builder = new SqlSessionFactoryBuilder(); SqlSessionFactory SqlSessionFactory factory = builder.build(in); SqlSession session = factory.openSession(); IUserDao userDao = session.getMapper(iUserDao.class); List<User> users = userdao.findAll ();for(User user : users) { System.out.println(user); } //7. Release session.close(); in.close(); }}Copy the code

Annotation-based MyBatis project:

Modify the previous section:

Add annotations to the persistence layer interface

Public interface IUserDao {/** * Queries all users * @return
	*/
	@Select("select * from user")
	List<User> findAll();
}
Copy the code

Modify mybatis-config. XML file:

In the tag, recource is changed to class, and the path of the mapping file is not changed.

<! Tell mybatis where the mapping configuration is --> <mappers> <mapper class="com.itheima.dao.IUserDao"/>
</mappers>
Copy the code

Matters needing attention:

When using annotations, there is no need to configure XML files, otherwise they will be overwritten by XML. In MyBatis, XML takes precedence over annotations.

3.3 Process of analyzing MyBatis framework:

The last

Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!