Java:MyBatis+SQLite使用实例

简介: Java:MyBatis+SQLite使用实例

MyBatis:

https://mybatis.org/mybatis-3/zh/index.html

项目结构

$ tree
.
├── data.db       # 数据库文件
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── mouday
        │           ├── App.java
        │           ├── dao
        │           │   ├── PersonDao.java
        │           │   └── impl
        │           │       └── PersonDaoImpl.java
        │           ├── pojo
        │           │   └── Person.java
        │           └── util
        │               └── MyBatisUtil.java
        └── resources
            ├── db.properties
            ├── mapper
            │   └── PersonMapper.xml
            └── mybatis-config.xml

配置文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mouday</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>demo</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.32.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

db.propertiesdriver=org.sqlite.JDBC

url=jdbc:sqlite:data.db


driver=org.sqlite.JDBC
url=jdbc:sqlite:data.db

mybatis-config.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" />
    <!-- 打印sql日志 -->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!-- 指定整个包下的类都是别名 -->
    <typeAliases>
        <package name="com.mouday.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 映射文件 -->
    <mappers>
        <mapper resource="mapper/PersonMapper.xml"/>
    </mappers>
</configuration>

工具类

MyBatisUtil.java

package com.mouday.util;
import org.apache.ibatis.io.Resources;
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 MyBatisUtil {
    private static SqlSessionFactory factory = null;
    // 使用static静态代码块,随着类的加载而加载,只执行一次
    static {
        try {
            String resource = "mybatis-config.xml";
            // 加载MyBatis的主配置文件
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 通过构建器(SqlSessionFactoryBuilder)构建一个SqlSessionFactory工厂对象
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession() throws IOException {
        return factory.openSession();
    }
}

POJO

Plain Ordinary Java Object

Person.java

package com.mouday.pojo;
public class Person {
    private Integer id;
    private String name;
    private Integer age;
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

DAO

Data Access Object

PersonDao.java

package com.mouday.dao;
import com.mouday.pojo.Person;
import java.util.List;
public interface PersonDao {
    Integer createTable();
    Integer dropTable();
    List<Person> selectAll();
    Person selectById(Integer id);
    Integer deleteById(Integer id);
    Integer update(Person person);
    Integer insert(Person person);
}

PersonDaoImpl.java

package com.mouday.dao.impl;
import com.mouday.dao.PersonDao;
import com.mouday.pojo.Person;
import com.mouday.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.io.IOException;
import java.util.List;
public class PersonDaoImpl implements PersonDao {
    public Integer createTable() {
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            PersonDao mapper = session.getMapper(PersonDao.class);
            Integer result = mapper.createTable();
            session.commit();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
    @Override
    public Integer dropTable() {
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            PersonDao mapper = session.getMapper(PersonDao.class);
            Integer result = mapper.dropTable();
            session.commit();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
    @Override
    public List<Person> selectAll() {
        List<Person> list = null;
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            // Person person = session.selectOne("com.mouday.dao.PersonDao.selectById", 1);
            // 等价于
            PersonDao mapper = session.getMapper(PersonDao.class);
            list = mapper.selectAll();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
    public Person selectById(Integer id) {
        Person person = null;
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            // Person person = session.selectOne("com.mouday.dao.PersonDao.selectById", 1);
            // 等价于
            PersonDao mapper = session.getMapper(PersonDao.class);
            person = mapper.selectById(id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return person;
    }
    public Integer deleteById(Integer id) {
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            PersonDao mapper = session.getMapper(PersonDao.class);
            Integer result = mapper.deleteById(id);
            session.commit();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
    public Integer insert(Person person) {
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            PersonDao mapper = session.getMapper(PersonDao.class);
            Integer result = mapper.insert(person);
            session.commit();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
    public Integer update(Person person) {
        try (SqlSession session = MyBatisUtil.getSqlSession()) {
            PersonDao mapper = session.getMapper(PersonDao.class);
            Integer result = mapper.update(person);
            session.commit();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

PersonMapper.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="com.mouday.dao.PersonDao">
    <update id="dropTable">
        drop table if exists person;
    </update>
    <update id="createTable">
   CREATE TABLE IF NOT EXISTS `person` (
    `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    `name` TEXT,
    `age` INTEGER
    )
    </update>
    <select id="selectAll" resultType="Person">
    select * from person
    </select>
    <select id="selectById" resultType="Person">
    select * from person where id = #{id} limit 1
    </select>
    <delete id="deleteById">
        delete from person where id = #{id}
    </delete>
    <insert id="insert" useGeneratedKeys="true">
        insert into person (name, age) values (#{name}, #{age})
    </insert>
    <update id="update">
        update person set name = #{name}, age = #{age} where id = #{id}
    </update>
</mapper>

接口使用

App.java

package com.mouday;
import com.mouday.dao.PersonDao;
import com.mouday.dao.impl.PersonDaoImpl;
import com.mouday.pojo.Person;
import java.io.IOException;
import java.util.List;
public class App {
    public static void main(String[] args) throws IOException {
        PersonDao personDao = new PersonDaoImpl();
        // 建表
        personDao.dropTable();
        personDao.createTable();
        // 插入数据
        personDao.insert(new Person("曹操", 23));
        personDao.insert(new Person("刘备", 24));
        personDao.insert(new Person("孙权", 21));
        // 删除
        Integer deleteResult = personDao.deleteById(1);
        System.out.println(deleteResult);
        // 查询单个
        Person person = personDao.selectById(2);
        System.out.println(person);
        // 更新
        person.setAge(25);
        Integer updateResult = personDao.update(person);
        System.out.println(updateResult);
        // 查询所有
        List<Person> list = personDao.selectAll();
        for(Person p: list){
            System.out.println(p);
        }
    }
}

完整代码:

https://github.com/mouday/MyBatis-demo

相关文章
|
7月前
|
SQL Java 数据库连接
Java系列技术之Mybatis
MyBatis 是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集,它可以使用简单的XML或注解来配置和映射SQL信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
75 0
|
6月前
|
SQL Java 关系型数据库
Java中的ORM框架——myBatis
Java中的ORM框架——myBatis
|
SQL Java 数据库连接
Java:MyBatis讲解
MyBatis是一个开源的Java持久化框架,它提供了一个简化数据库访问的方法。MyBatis的主要目标是减少编写SQL代码的工作量,并提供了将数据库操作与Java对象的映射功能。
58 1
Java:MyBatis讲解
|
SQL Java 数据库连接
【Java】Mybatis查询数据库
【Java】Mybatis查询数据库
|
SQL Java 关系型数据库
【java】——Hibernate代码创建表
小编最近正在进行Hibernate框架的学习,根据代码建立数据库表实现了一个小例子,跟读者朋友进行分享。
java202304java学习笔记第六十六天-ssm-mybatis的增删改查-插入数据注意点
java202304java学习笔记第六十六天-ssm-mybatis的增删改查-插入数据注意点
37 0
|
数据库
java202304java学习笔记第六十六天-ssm-mybatis的增删改查-插入数据库操作2
java202304java学习笔记第六十六天-ssm-mybatis的增删改查-插入数据库操作2
64 0
|
SQL XML Java
Java:MyBatis实现增删改查
MyBatis是一款开源的Java持久层框架,可以将SQL语句和Java程序代码进行分离,开发者无需直接编写JDBC代码,通过XML或注解的方式配置SQL语句和映射关系,简化了数据库操作的过程。MyBatis具有良好的扩展性和灵活性,提供了多种插件和自定义类型转换器等功能,广泛应用于企业级开发中。
110 0
|
Java 数据库连接 mybatis
Java:MyBatis+SQLite使用实例
Java:MyBatis+SQLite使用实例
453 0
|
SQL Java 数据库连接
Java 最常见的面试题:mybatis 和 hibernate 的区别有哪些?
Java 最常见的面试题:mybatis 和 hibernate 的区别有哪些?
150 0