Mybatis getting started, mybatis getting started
As a java learner, I believe that JDBC is the first access to and an entry-level database connection method, so let's first recall how JDBC works as a Java API used to execute SQL statements. The following code is the most basic JDBC development process.
Before running the code, you must first import the JDBC jar package. Because the database I use is mysql
Enter the following jar package
The next step is to load the database driver and get database links. Of course, these tasks are all done by code. In order to compare with the next mybatis configuration file, I use the preprocessing method here for query. The Code is as follows:
Public class Testjdbc {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 "); // obtain the database connection = (Connection) DriverManager through the Driver management class. getConnection ("jdbc: mysql: // localhost: 3306/mybatis? CharacterEncoding = UTF-8 "," root "," 123456 "); // define an SQL statement? String SQL = "select * from user where username =? "; // Obtain the pre-processing statement preparedStatement = (PreparedStatement) connection. prepareStatement (SQL); // sets the parameter. The first parameter is the serial number of the parameter in the SQL statement (starting from 1), and the second parameter is the set parameter value preparedStatement. setString (1, ""); // sends an SQL query to the database to query the result set resultSet = preparedStatement.exe cuteQuery (); // traverses the query result set while (resultSet. next () {System. out. println (resultSet. getString ("id") + "" + resultSet. getString ("username") ;}} catch (Exception e) {e. PrintStackTrace ();} finally {// release the resource 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 ();}}}}}
Then people who have used JDBC know that it has such shortcomings. The following points are summarized:
Solution: use the database connection pool to manage databases
Solution: configure the SQL statement to the xml configuration file, so that you do not need to recompile the java code even if the SQL statement changes.
Solution: You can also configure placeholders and parameters in the xml file.
Solution: automatically map the query result set to a java object
After speaking of JDBC, we all saw the inconvenience caused by JDBC, so the object-link ing frameworks such as Hibernate and Mybatis came into being. Although they are all ORM frameworks, hibernate and Mybatis are quite different in terms of detail, but this article discusses the Mybatis framework.
First, MybatisWhat is it?
Mybatis architecture:
Next, use mybatis to write an entry program.
First, let's talk about our requirements. There is a user table in my database. The table structure is as follows:
What I want to do now is to query user information based on the user id (primary key)
Set up the environment before starting the prepare code.
Eclipse uses the java EE version.
Then the mysql driver package mentioned above
In addition to the sqlMapConfig. xml configuration file mentioned in the preceding architecture diagram, you also need a package to store the ing file (which will be mentioned later in the ing file), that is, sqlMap.
Finally, create the log4j. properties file to view logs.
The architecture of the entire project is as follows:
For easy access, the entire project code is directly pasted here.
The first is the log4j. properties file.
# Global logging configurationlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Then SqlMapconfig. xml
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configurationPUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- After integration with spring, environments configuration will be abolished --> <environments default = "development"> <environment id = "development"> <! -- Use jdbc Transaction Management --> <transactionManager type = "JDBC"/> <! -- Database connection pool --> <dataSource type = "POOLED"> <property name = "driver" value = "com. mysql. jdbc. driver "/> <property name =" url "value =" jdbc: mysql: // localhost: 3306/mybatis? CharacterEncoding = UTF-8 "/> <property name =" username "value =" root "/> <property name =" password "value =" 123456 "/> </dataSource> </ environment> </environments> </configuration>
This string of configuration files is nothing more than configuration transaction management and database connection pool. Every ORM framework is necessary, so we will not go into detail
Followed by our highlightsIng FileNow
Ing File Name:
User. xml, and the name of the er development ing file in mapper proxy is xxxMapper. xml, for example: UserMapper. xml
What we need to do in the ing file is to configure SQL statements. The most intuitive comparison is that hibernate maps java objects directly to the relational (that is, tables in the database) IN THE ing file ), in mybatis, The ing relationship is refined, and the input ing and output ing are specified.
First paste the specific ing file and then explain it one by one
<?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="test"> <select id="findUserById" parameterType="int" resultType="com.mybatis.pojo.User"> select * from user where id=#{id}; </select></mapper>
There are several statements:
Note: Using mapper proxy for development, namespace has special functions
The User class is as follows:
The ing file is then loaded into the global configuration file SqlMapConfig.
Add a sentence to the file.
<Mappers>
<Mapper resource ="SqlMap/User. xml"/>
</Mappers>
Now the configuration file is complete. The next step is to write a program to test the configuration file.
Follow the previous architecture step by step, and finally write the program as follows:
public class MybatisTest { @Test public void findUserByIdTest() throws IOException{ InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession=sqlSessionFactory.openSession(); User user=sqlSession.selectOne("test.findUserById",1); System.out.println(user); }}
There are two important points here. The first one is that the input stream (inputStream) comes from the mybatis configuration file.
The second is the two parameters in the selectOne method:
The first parameter is the statement id in the ing file. Here, it must be written as the namespace + '.' + statement id
Second parameter: Specify the parameterType parameter that matches the ing file.
The result is as follows:
Here, the Mybatis entry-level program from the configuration file to the test code has been completed. Please wait for the next update.