Mabatis入门程序

一.
准备工作
1.首先从github上面下载Mabatis
2.导主要包
3.导入依赖包lib

我们使用MyBatis实现以下功能:
根据用户id查询一个用户
根据用户名称模糊查询用户列表
添加用户
更新用户
删除用户
二.
1)编写POJO
Public class User {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
get/set……
2) 创建 sqlMapConfig.xml

Mabatis入门程序_第1张图片
image.png

3)创建log4j.properties`
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4)创建与User相关联的映射文件 User.xml

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
" http://mybatis.org/dtd/mybatis-3-mapper.dtd">



*************************

5) 在 sqlMapConfig.xml 配置 映射文件mapper
![image.png](http://upload-images.jianshu.io/upload_images/6217104-cea20b04764d8911.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

下面我们完成了使用根据用户id查询一个用户


      
        
          
        

  
  
  
  
  
        
 
6)编写测试类 

public class MybatisTest {
private SqlSessionFactory sqlSessionFactory = null;

@Before
public void init() throws Exception {
    // 1. 创建SqlSessionFactoryBuilder对象
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

    // 2. 加载SqlMapConfig.xml配置文件
    InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");

    // 3. 创建SqlSessionFactory对象
    this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
}

@Test
public void testQueryUserById() throws Exception {
    // 4. 创建SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    // 5. 执行SqlSession对象执行查询,获取结果User
    // 第一个参数是User.xml的statement的id,第二个参数是执行sql需要的参数;
    Object user = sqlSession.selectOne("queryUserById", 1);

    // 6. 打印结果
    System.out.println(user);

    // 7. 释放资源
    sqlSession.close();
}

}


根据用户名称模糊查询用户列表


Mabatis入门程序_第2张图片
image.png

除了上面的写法,我们同样可以使用下面的写法,结果和刚才是一模一样的 下面的写法可以防止sql注入


Mabatis入门程序_第3张图片
image.png

Mabatis入门程序_第4张图片
image.png

添加用户


Mabatis入门程序_第5张图片
image.png

Mabatis入门程序_第6张图片
image.png

有时候需要我们在刚刚添加完用户之后, 用户的ID是自增长的 所以这个时候我们需要依赖ID来处理订单的数据库表,
这时候我们需要保存下来此ID 进而处理订单的数据库表,下面我们来修改映射文件


Mabatis入门程序_第7张图片
image.png

Mabatis入门程序_第8张图片
image.png

打印输出如下


Mabatis入门程序_第9张图片
image.png

更新用户


Mabatis入门程序_第10张图片
image.png
Mabatis入门程序_第11张图片
image.png

删除用户


Mabatis入门程序_第12张图片
image.png
Mabatis入门程序_第13张图片
image.png



你可能感兴趣的:(Mabatis入门程序)