Mybatis学习日志第一天

1.配置

配置pom文档



 4.0.0
 
 org.example
 Mybatis-Study
 pom
 1.0-SNAPSHOT
 
 mybatis-01
 
  
 
   
 
 mysql
 mysql-connector-java
 5.1.49
 
  
 
 org.mybatis
 mybatis
 3.5.2
 
  
 
 junit
 junit
 4.12
 
 
  
 
 
 
 src/main/resources
 
 **/*.properties
 **/*.xml
 
 true
 
 
 src/main/java
 
 **/*.properties
 **/*.xml
 
 true
 
 
 

2.连接数据库

在resources下创建一个叫mybatis-config.xml文件


















注意:手动连接数据库可能出现时区不对的情况
在url3306后面加入/?serverTimezone=GMT即可

3.创建类和接口,编写代码

3.1 mybatisUtils类

package com.kuang.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
 private  static SqlSessionFactory sqlSessionFactory;
 static {
 try {
 String resource = "mybatis-config.xml";
 InputStream inputStream = Resources.getResourceAsStream(resource);
 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 } catch (IOException e) {
 e.printStackTrace();
 }
 } // 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。org.apache.ibatis.session.SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
 public static SqlSession getSqlSession(){
 return sqlSessionFactory.openSession();
 }
}

3.2实体类

package com.kuang.pojo;
public class User {
 private int id;
 private String name;
 private String password;
 public User() {
 }
 public User(int id, String name, String password) {
 this.id = id;
 this.name = name;
 this.password = password;
 }
 public int getId() {
 return id;
 }
 public void setId(int id) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getPassword() {
 return password;
 }
 public void setPassword(String password) {
 this.password = password;
 }
 @Override
 public String toString() {
 return "User{" +
 "id=" + id +
 ", name='" + name + ''' +
 ", password='" + password + ''' +
 '}'; }
}

3.3接口

package com.kuang.dao;
import com.kuang.pojo.User;
import java.util.List;
public interface UserDao {
 ListgetUserList();
}

3.4 接口实现类(写在xml文件中)




 

每一个xml文件都需要在mybatis-config的mappers中配置


 

#### 3.5测试类

package com.kuang.dao;
import com.kuang.pojo.User;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}

## 4.测试结果
![image.png](/img/bVcKWcF)
附数据库语句
![image.png](/img/bVcKWcM)

你可能感兴趣的:(java,mysql)