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



<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.0modelVersion>

    <groupId>com.moudaygroupId>
    <artifactId>demoartifactId>
    <version>1.0-SNAPSHOTversion>

    <name>demoname>
    
    <url>http://www.example.comurl>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.xerialgroupId>
            <artifactId>sqlite-jdbcartifactId>
            <version>3.32.3version>
        dependency>

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.5version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
            <scope>testscope>
        dependency>
    dependencies>

project>

db.properties

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

mybatis-config.xml




<configuration>
    
    <properties resource="db.properties" />

    
    <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




<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

你可能感兴趣的:(java)