Development environment: Idea2018
Database: mysql 8.0.16
Purpose: to learn Mybatis
- Database preparation
This instance uses mysql 8.0.16, user name root and password 123456
To create a database and create a test form:
/*Create database*/ CREATE DATABASE tms default character set utf8; /*Create data form*/ CREATE TABLE `t_members` ( -> `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, -> `nickname` varchar(255) DEFAULT NULL COMMENT 'Nickname?', -> `password` char(32) NOT NULL DEFAULT '' COMMENT 'Password', -> `realname` varchar(36) NOT NULL DEFAULT '' COMMENT 'Real name', -> `gender` enum('MALE','FEMALE','NONE') NOT NULL DEFAULT 'NONE' COMMENT 'Full name', -> `rank` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT 'Membership level', -> `email` char(50) NOT NULL DEFAULT '' COMMENT 'mailbox', -> `mobile` varchar(15) NOT NULL DEFAULT '' COMMENT 'Cell-phone number', -> `safequestion` varchar(255) NOT NULL DEFAULT '0' COMMENT 'safety problem', -> `safeanswer` char(30) NOT NULL DEFAULT '' COMMENT 'Safety answer', -> `createdTime` datetime DEFAULT NULL COMMENT 'Creation time', -> PRIMARY KEY (`id`) -> ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Membership table'; /*Insert test data*/ INSERT INTO `t_members` VALUES ('2', 'tom', '123456', 'Tom Hanks', 'MALE', '1', 'e123@t.com', '13588888888', '1+1=?', '3', 'now()'); INSERT INTO `t_members` VALUES ('3', 'andy', '123789', 'Andy Zhou', 'FEMALE', '1', 'e456@t.com', '13699999999', '2+2=?', '5', now());
-
Project creation
File - > new project, select maven, check Create from architype, select Maven archetype QuickStart, and click Next
Enter GroupId and ArtifactId to continue with Next
Then continue to Next until Finish. -
First, I will show the overall structure of the project when it is completed, and then I will introduce the creation process of various files. Add the missing folder and Package of the new project by yourself.
-
Add necessary dependency to pom.xml first after creating a new project
<?xml version="1.0" encoding="UTF-8"?> <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.gbs</groupId> <artifactId>Members</artifactId> <version>1.0-SNAPSHOT</version> <name>Members</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> </dependencies> <build> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle --> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle --> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </pluginManagement> </build> </project>
- Create entity class Member
package com.gbs.dao.entity; import java.io.Serializable; import java.util.Date; public class Member implements Serializable { private static final long serialVersionUID = 6948864912341044105L; private Integer id; private String nickname; private String password; private String realname; private String gender; private String email; private String mobile; private Integer rank=0; private String safequestion; private String safeanswer; private Date createdTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Integer getRank() { return rank; } public void setRank(Integer rank) { this.rank = rank; } public String getSafequestion() { return safequestion; } public void setSafequestion(String safequestion) { this.safequestion = safequestion; } public String getSafeanswer() { return safeanswer; } public void setSafeanswer(String safeanswer) { this.safeanswer = safeanswer; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } @Override public String toString() { return "Member{" + "id=" + id + ", nickname='" + nickname + '\'' + ", password='" + password + '\'' + ", realname='" + realname + '\'' + ", gender='" + gender + '\'' + ", email='" + email + '\'' + ", mobile='" + mobile + '\'' + ", rank=" + rank + ", safequestion='" + safequestion + '\'' + ", safeanswer='" + safeanswer + '\'' + ", createdTime=" + createdTime.toString() + '}'; } }
- Implementation of MemberDao through Dao layer interface
package com.gbs.dao; import com.gbs.dao.entity.Member; import java.util.List; public interface MemberDao { List<Member> findPageObjects(); }
- Create the mapping file MemberMapper.xml
<?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.gbs.dao.MemberDao"> <select id="findPageObjects" resultType="com.gbs.dao.entity.Member"> select * from t_members </select> </mapper>
- Write jdbc.properties
jdbc.DriverClassName=com.mysql.cj.jdbc.Driver jdbc.url =jdbc:mysql://localhost:3306/tms?serverTimezone=UTC&useSSL=false jdbc.username=root jdbc.password=123456
- Write mybatis-config.xml
<?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> <properties resource="jdbc.properties"> </properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.DriverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/MemberMapper.xml" /> </mappers> </configuration>
- The main code has been completed. Write test code TestMybatis first
package com.gbs; import com.gbs.dao.MemberDao; import com.gbs.dao.entity.Member; 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.Test; import java.io.IOException; import java.util.List; public class TestMybatis { /**Query test method*/ @Test public void testFindPageObjects() throws IOException { //Define the path to the profile String resource="mybatis-config.xml"; //Creating SqlSessionFactory through SqlSessionFactoryBuilder SqlSessionFactory factory=new SqlSessionFactoryBuilder() .build(Resources.getResourceAsStream(resource)); //Creating SqlSession through SqlSessionFactory SqlSession session=factory.openSession(); //Execute dao object MemberDao dao=session.getMapper(MemberDao.class); //Get result set List<Member> list=dao.findPageObjects(); //Output result set System.out.println(list); //Close connection session.close(); } }