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包

配置SqlMapConfig.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="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/student.xml"/>
    </mappers>
</configuration>

配置student.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="Test">
    <!-- 根据id查询指定条目 -->
    <select id="selectStudentById" resultType="com.yu.domain.Student"
        parameterType="int">
        <!-- 输入简单类型时,#{id} 中id不是唯一的,随便写 -->
        select * from student where id = #{id}
    </select>
    <!-- 模糊查询 -->
    <select id="selectStudentByLikeName" resultType="com.yu.domain.Student"
        parameterType="int">
        <!-- 必须是value,${}表示拼接字符串 -->
        select * from student where NAME LIKE '%${value}%'
    </select>

    <!-- 插入数据  -->
    <insert id="insertStudentId" parameterType="com.yu.domain.Student">
    <selectKey keyProperty="id" resultType="int" order="AFTER">
      SELECT LAST_INSERT_ID()
    </selectKey>
     insert into student(name,age,hobby) value(#{name},#{age},#{hobby})
    </insert>

    <!--删除数据  -->
    <delete id="deleteStudent" parameterType="java.lang.Integer">
     delete from student where id=#{value}
    </delete>

    <!--更新数据  -->
    <update id="updateStudent" parameterType="com.yu.domain.Student" >
       update student set name=#{name} ,age=#{age} ,hobby=#{hobby} where id=#{id} 
    </update>
</mapper>

配置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> 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();
    }
 }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值