MyBatis(一) 入门案例实现CRUD操作

什么是MyBatis

官方文档是这么说的

MyBatis is a first class persistence framework with support for custom SQL, stored procedures
and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of
parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration
and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

简单来说就是:

MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。

入门案例

案例需求:实现基本的增删改查操作

1.创建表

代码不贴了,比较简单。

2.创建POJO类
 package com.yu.domain;

 public class Student {

@Override
public String toString() {
    return "Student [id=" + id + ", name=" + name + ", age=" + age + ", hobby=" + hobby + "]";
}
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 int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public String getHobby() {
    return hobby;
}
public void setHobby(String hobby) {
    this.hobby = hobby;
}
private int id;
private String name;
private int age;
private String hobby;



 }
3.搭建MyBatis开发环境并测试

导入jar包

MyBatis(一) 入门案例实现CRUD操作_第1张图片

配置SqlMapConfig.xml




   
    
        
            
            
                
                
                
                
            
        
    
    
        
    

配置student.xml




    
    
    
    
    
    
    
    
      SELECT LAST_INSERT_ID()
    
     insert into student(name,age,hobby) value(#{name},#{age},#{hobby})
    
    
    
    
     delete from student where id=#{value}
    
    
    
    
       update student set name=#{name} ,age=#{age} ,hobby=#{hobby} where id=#{id} 
    

配置db.properties

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/student
db.username=root
db.password=root

配置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

测试代码:

public class Test1 {
private SqlSessionFactory sqlSessionFactory;

@Before
public void setUp() throws Exception {
    // 读取配置文件
    // 全局配置文件的路径
    String resource = "SqlMapConfig.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    // 创建SqlSessionFactory
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}

//通过指定id查询
@Test
public void selectStudentById() {
    //通过SqlSessionFactory创建SqlSession对象
    SqlSession session = sqlSessionFactory.openSession();
    Student student = session.selectOne("Test.selectStudentById", 1);
    System.out.println(student);
    session.close();
}
 //模糊查询
@Test
public void selectStudentByLikeName() {
    SqlSession session = sqlSessionFactory.openSession();
    List student = session.selectList("Test.selectStudentByLikeName", "小王");
    System.out.println(student);
    session.close();
}
//插入数据
@Test
public void insertStudentTest() {
    SqlSession session = sqlSessionFactory.openSession();
    Student student = new Student();
    student.setName("Ronaldo");
    student.setAge(20);
    student.setHobby("泡妞");
    session.insert("Test.insertStudentId", student);
    session.commit();
     System.out.println(student.getId());
    session.close();
}
//删除数据
@Test
public void deleteStudentTest() {
    SqlSession session = sqlSessionFactory.openSession();
    session.delete("Test.deleteStudent", 6);
    session.commit();
    session.close();
}
//更新数据
    @Test
    public void updateStudent() {
        SqlSession session = sqlSessionFactory.openSession();
        Student student = new Student();
        student.setId(4);
        student.setName("Ronaldo");
        student.setAge(22);
        student.setHobby("泡妞2");
        session.update("Test.updateStudent", student);
        session.commit();
        System.out.println(student.getId());
        session.close();
    }
 }

你可能感兴趣的:(MyBatis(一) 入门案例实现CRUD操作)