Mybatis入门详细版

一.简单入门案例(案例的目标是查询数据库中user表中的全部数据)

1.1首先创建最简单的maven工程

导入mybatis,mysql,junit(测试用的)依赖

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

为了防止资源导出错误,可以在pom.xml中添加以下代码

 1   <!--在build中配置resources,来防止我们资源导出失败的问题-->
 2     <build>
 3         <resources>
 4             <resource>
 5                 <directory>src/main/resources</directory>
 6                 <includes>
 7                     <include>**/*.properties</include>
 8                     <include>**/*.xml</include>
 9                 </includes>
10                 <filtering>true</filtering>
11             </resource>
12             <resource>
13                 <directory>src/main/java</directory>
14                 <includes>
15                     <include>**/*.properties</include>
16                     <include>**/*.xml</include>
17                 </includes>
18                 <filtering>true</filtering>
19             </resource>
20         </resources>
21     </build>
View Code

1.2编写Mybatis-config.xml文件(位于resource文件下)

 1 <configuration>
 2 <environments default="development">
 3     <environment id="development">
 4         <transactionManager type="JDBC"/>
 5         <dataSource type="POOLED">
 6             <property name="driver" value="com.mysql.jdbc.Driver"/>
 7             <property name="url" value="jdbc:mysql://localhost:3306/smbms?&amp;useSSL=false"/>
 8             <property name="username" value="root"/>
 9             <property name="password" value="804907"/>
10         </dataSource>
11     </environment>
12 </environments>
13 <mappers>
14     <mapper resource="dao/userMapper.xml"/>
15 </mappers>
16 </configuration>

第六,七行的代码是针对mysql5版本的,如果是mysql8版本的,要改成以下的

1  <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
2  <property name="url" value="jdbc:mysql://localhost:3306/smbms?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF8&amp;serverTimezone=GMT"/>

1.3编写实体类

  1 package com.hanking.pojo;
  2 
  3 import java.util.Date;
  4 
  5 public class User {
  6     int id;
  7     String userCode;
  8     String userName;
  9     String userPassword;
 10     int gender;
 11     Date birthday;
 12     String phone;
 13     String address;
 14     int userRole;
 15     int createdBy;
 16     Date creationDate;
 17     int modifyBy;
 18     Date modifyDate;
 19 
 20     public int getId() {
 21         return id;
 22     }
 23 
 24     public void setId(int id) {
 25         this.id = id;
 26     }
 27 
 28     public String getUserCode() {
 29         return userCode;
 30     }
 31 
 32     public void setUserCode(String userCode) {
 33         this.userCode = userCode;
 34     }
 35 
 36     public String getUserName() {
 37         return userName;
 38     }
 39 
 40     public void setUserName(String userName) {
 41         this.userName = userName;
 42     }
 43 
 44     public String getUserPassword() {
 45         return userPassword;
 46     }
 47 
 48     public void setUserPassword(String userPassword) {
 49         this.userPassword = userPassword;
 50     }
 51 
 52     public int getGender() {
 53         return gender;
 54     }
 55 
 56     public void setGender(int gender) {
 57         this.gender = gender;
 58     }
 59 
 60     public Date getBirthday() {
 61         return birthday;
 62     }
 63 
 64     public void setBirthday(Date birthday) {
 65         this.birthday = birthday;
 66     }
 67 
 68     public String getPhone() {
 69         return phone;
 70     }
 71 
 72     public void setPhone(String phone) {
 73         this.phone = phone;
 74     }
 75 
 76     public String getAddress() {
 77         return address;
 78     }
 79 
 80     public void setAddress(String address) {
 81         this.address = address;
 82     }
 83 
 84     public int getUserRole() {
 85         return userRole;
 86     }
 87 
 88     public void setUserRole(int userRole) {
 89         this.userRole = userRole;
 90     }
 91 
 92     public int getCreatedBy() {
 93         return createdBy;
 94     }
 95 
 96     public void setCreatedBy(int createdBy) {
 97         this.createdBy = createdBy;
 98     }
 99 
100     public Date getCreationDate() {
101         return creationDate;
102     }
103 
104     public void setCreationDate(Date creationDate) {
105         this.creationDate = creationDate;
106     }
107 
108     public int getModifyBy() {
109         return modifyBy;
110     }
111 
112     public void setModifyBy(int modifyBy) {
113         this.modifyBy = modifyBy;
114     }
115 
116     public Date getModifyDate() {
117         return modifyDate;
118     }
119 
120     public void setModifyDate(Date modifyDate) {
121         this.modifyDate = modifyDate;
122     }
123 
124     public User(int id, String userCode, String userName, String userPassword, int gender, Date birthday, String phone, String address, int userRole, int createdBy, Date creationDate, int modifyBy, Date modifyDate) {
125         this.id = id;
126         this.userCode = userCode;
127         this.userName = userName;
128         this.userPassword = userPassword;
129         this.gender = gender;
130         this.birthday = birthday;
131         this.phone = phone;
132         this.address = address;
133         this.userRole = userRole;
134         this.createdBy = createdBy;
135         this.creationDate = creationDate;
136         this.modifyBy = modifyBy;
137         this.modifyDate = modifyDate;
138     }
139 
140     public User() {
141     }
142 
143     @Override
144     public String toString() {
145         return "User{" +
146                 "id=" + id +
147                 ", userCode='" + userCode + '\'' +
148                 ", userName='" + userName + '\'' +
149                 ", userPassword='" + userPassword + '\'' +
150                 ", gender=" + gender +
151                 ", birthday=" + birthday +
152                 ", phone='" + phone + '\'' +
153                 ", address='" + address + '\'' +
154                 ", userRole=" + userRole +
155                 ", createdBy=" + createdBy +
156                 ", creationDate=" + creationDate +
157                 ", modifyBy=" + modifyBy +
158                 ", modifyDate=" + modifyDate +
159                 '}';
160     }
161 }

这个看起来很长,其实很简单,而且最不容易出错。

1.4编写工具类

Mybatis要依靠sqlsessionFactory来创建sqlsession

 1 public class MybatisUtils {
 2     public static SqlSessionFactory sqlSessionFactory;
 3 
 4 
 5     static {
 6             try {
 7                 String resource = "Mybatis-config.xml";
 8                 InputStream inputStream = Resources.getResourceAsStream(resource);
 9                 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
10             } catch (IOException e) {
11                 e.printStackTrace();
12             }
13         }
14         public static SqlSession getSqlSession(){
15             return sqlSessionFactory.openSession();
16         }
17 }

1.5编写dao层接口类

public interface UserDao {
    List<User> getAllUser();
}

1.6编写Mapper.xml(实际的操作数据库的文件)

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="com.hanking.dao.UserDao">
6     <select id="getAllUser" resultType="com.hanking.pojo.User">
7         select * from smbms_user;
8     </select>
9 </mapper>

1.7编写测试类

 1 public class UserDaoTest {
 2     @Test
 3     public void getAllUser(){
 4         SqlSession sqlSession = MybatisUtils.getSqlSession();
 5         UserDao userDao = sqlSession.getMapper(UserDao.class);
 6         List<User> allUser = userDao.getAllUser();
 7         for (User u: allUser) {
 8             System.out.println(u);
 9         }
10         sqlSession.close();
11     }
12 }

二.以上案例容易出错的点

2.1其中编写实体类,pom.xml是最不容易出错的

2.2Mybatis-config.xml中要注意mysql版本的问题

2.3Mapper.xml中,有以下要注意的点

  2.3.1 namespace表示对应的接口名(要写全限定包名)

  2.3.2 id表示的是对应接口中的方法名

  2.3.3 resultType表示的是返回值类型,int可不用写,如果是类,要写全限定类名,parameterType表示的是参数的类型

posted @ 2021-04-15 19:09  。。天空之城。。  阅读(132)  评论(0编辑  收藏  举报